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-auth/src/index.rs | crates/uv-auth/src/index.rs | use std::fmt::{self, Display, Formatter};
use rustc_hash::FxHashSet;
use url::Url;
use uv_redacted::DisplaySafeUrl;
/// When to use authentication.
#[derive(
Copy,
Clone,
Debug,
Default,
Hash,
Eq,
PartialEq,
Ord,
PartialOrd,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum AuthPolicy {
/// Authenticate when necessary.
///
/// If credentials are provided, they will be used. Otherwise, an unauthenticated request will
/// be attempted first. If the request fails, uv will search for credentials. If credentials are
/// found, an authenticated request will be attempted.
#[default]
Auto,
/// Always authenticate.
///
/// If credentials are not provided, uv will eagerly search for credentials. If credentials
/// cannot be found, uv will error instead of attempting an unauthenticated request.
Always,
/// Never authenticate.
///
/// If credentials are provided, uv will error. uv will not search for credentials.
Never,
}
impl Display for AuthPolicy {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Auto => write!(f, "auto"),
Self::Always => write!(f, "always"),
Self::Never => write!(f, "never"),
}
}
}
// TODO(john): We are not using `uv_distribution_types::Index` directly
// here because it would cause circular crate dependencies. However, this
// could potentially make sense for a future refactor.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Index {
pub url: DisplaySafeUrl,
/// The root endpoint where authentication is applied.
/// For PEP 503 endpoints, this excludes `/simple`.
pub root_url: DisplaySafeUrl,
pub auth_policy: AuthPolicy,
}
impl Index {
pub fn is_prefix_for(&self, url: &Url) -> bool {
if self.root_url.scheme() != url.scheme()
|| self.root_url.host_str() != url.host_str()
|| self.root_url.port_or_known_default() != url.port_or_known_default()
{
return false;
}
url.path().starts_with(self.root_url.path())
}
}
// TODO(john): Multiple methods in this struct need to iterate over
// all the indexes in the set. There are probably not many URLs to
// iterate through, but we could use a trie instead of a HashSet here
// for more efficient search.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct Indexes(FxHashSet<Index>);
impl Indexes {
pub fn new() -> Self {
Self(FxHashSet::default())
}
/// Create a new [`Indexes`] instance from an iterator of [`Index`]s.
pub fn from_indexes(urls: impl IntoIterator<Item = Index>) -> Self {
let mut index_urls = Self::new();
for url in urls {
index_urls.0.insert(url);
}
index_urls
}
/// Get the index for a URL if one exists.
pub fn index_for(&self, url: &Url) -> Option<&Index> {
self.find_prefix_index(url)
}
/// Get the [`AuthPolicy`] for a URL.
pub fn auth_policy_for(&self, url: &Url) -> AuthPolicy {
self.find_prefix_index(url)
.map(|index| index.auth_policy)
.unwrap_or(AuthPolicy::Auto)
}
fn find_prefix_index(&self, url: &Url) -> Option<&Index> {
self.0.iter().find(|&index| index.is_prefix_for(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-auth/src/store.rs | crates/uv-auth/src/store.rs | use std::ops::Deref;
use std::path::{Path, PathBuf};
use fs_err as fs;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uv_fs::{LockedFile, LockedFileError, LockedFileMode, with_added_extension};
use uv_preview::{Preview, PreviewFeatures};
use uv_redacted::DisplaySafeUrl;
use uv_state::{StateBucket, StateStore};
use uv_static::EnvVars;
use crate::credentials::{Password, Token, Username};
use crate::realm::Realm;
use crate::service::Service;
use crate::{Credentials, KeyringProvider};
/// The storage backend to use in `uv auth` commands.
#[derive(Debug)]
pub enum AuthBackend {
// TODO(zanieb): Right now, we're using a keyring provider for the system store but that's just
// where the native implementation is living at the moment. We should consider refactoring these
// into a shared API in the future.
System(KeyringProvider),
TextStore(TextCredentialStore, LockedFile),
}
impl AuthBackend {
pub async fn from_settings(preview: Preview) -> Result<Self, TomlCredentialError> {
// If preview is enabled, we'll use the system-native store
if preview.is_enabled(PreviewFeatures::NATIVE_AUTH) {
return Ok(Self::System(KeyringProvider::native()));
}
// Otherwise, we'll use the plaintext credential store
let path = TextCredentialStore::default_file()?;
match TextCredentialStore::read(&path).await {
Ok((store, lock)) => Ok(Self::TextStore(store, lock)),
Err(err)
if err
.as_io_error()
.is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) =>
{
Ok(Self::TextStore(
TextCredentialStore::default(),
TextCredentialStore::lock(&path).await?,
))
}
Err(err) => Err(err),
}
}
}
/// Authentication scheme to use.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthScheme {
/// HTTP Basic Authentication
///
/// Uses a username and password.
#[default]
Basic,
/// Bearer token authentication.
///
/// Uses a token provided as `Bearer <token>` in the `Authorization` header.
Bearer,
}
/// Errors that can occur when working with TOML credential storage.
#[derive(Debug, Error)]
pub enum TomlCredentialError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
LockedFile(#[from] LockedFileError),
#[error("Failed to parse TOML credential file: {0}")]
ParseError(#[from] toml::de::Error),
#[error("Failed to serialize credentials to TOML")]
SerializeError(#[from] toml::ser::Error),
#[error(transparent)]
BasicAuthError(#[from] BasicAuthError),
#[error(transparent)]
BearerAuthError(#[from] BearerAuthError),
#[error("Failed to determine credentials directory")]
CredentialsDirError,
#[error("Token is not valid unicode")]
TokenNotUnicode(#[from] std::string::FromUtf8Error),
}
impl TomlCredentialError {
pub fn as_io_error(&self) -> Option<&std::io::Error> {
match self {
Self::Io(err) => Some(err),
Self::LockedFile(err) => err.as_io_error(),
Self::ParseError(_)
| Self::SerializeError(_)
| Self::BasicAuthError(_)
| Self::BearerAuthError(_)
| Self::CredentialsDirError
| Self::TokenNotUnicode(_) => None,
}
}
}
#[derive(Debug, Error)]
pub enum BasicAuthError {
#[error("`username` is required with `scheme = basic`")]
MissingUsername,
#[error("`token` cannot be provided with `scheme = basic`")]
UnexpectedToken,
}
#[derive(Debug, Error)]
pub enum BearerAuthError {
#[error("`token` is required with `scheme = bearer`")]
MissingToken,
#[error("`username` cannot be provided with `scheme = bearer`")]
UnexpectedUsername,
#[error("`password` cannot be provided with `scheme = bearer`")]
UnexpectedPassword,
}
/// A single credential entry in a TOML credentials file.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "TomlCredentialWire", into = "TomlCredentialWire")]
struct TomlCredential {
/// The service URL for this credential.
service: Service,
/// The credentials for this entry.
credentials: Credentials,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TomlCredentialWire {
/// The service URL for this credential.
service: Service,
/// The username to use. Only allowed with [`AuthScheme::Basic`].
username: Username,
/// The authentication scheme.
#[serde(default)]
scheme: AuthScheme,
/// The password to use. Only allowed with [`AuthScheme::Basic`].
password: Option<Password>,
/// The token to use. Only allowed with [`AuthScheme::Bearer`].
token: Option<String>,
}
impl From<TomlCredential> for TomlCredentialWire {
fn from(value: TomlCredential) -> Self {
match value.credentials {
Credentials::Basic { username, password } => Self {
service: value.service,
username,
scheme: AuthScheme::Basic,
password,
token: None,
},
Credentials::Bearer { token } => Self {
service: value.service,
username: Username::new(None),
scheme: AuthScheme::Bearer,
password: None,
token: Some(String::from_utf8(token.into_bytes()).expect("Token is valid UTF-8")),
},
}
}
}
impl TryFrom<TomlCredentialWire> for TomlCredential {
type Error = TomlCredentialError;
fn try_from(value: TomlCredentialWire) -> Result<Self, Self::Error> {
match value.scheme {
AuthScheme::Basic => {
if value.username.as_deref().is_none() {
return Err(TomlCredentialError::BasicAuthError(
BasicAuthError::MissingUsername,
));
}
if value.token.is_some() {
return Err(TomlCredentialError::BasicAuthError(
BasicAuthError::UnexpectedToken,
));
}
let credentials = Credentials::Basic {
username: value.username,
password: value.password,
};
Ok(Self {
service: value.service,
credentials,
})
}
AuthScheme::Bearer => {
if value.username.is_some() {
return Err(TomlCredentialError::BearerAuthError(
BearerAuthError::UnexpectedUsername,
));
}
if value.password.is_some() {
return Err(TomlCredentialError::BearerAuthError(
BearerAuthError::UnexpectedPassword,
));
}
if value.token.is_none() {
return Err(TomlCredentialError::BearerAuthError(
BearerAuthError::MissingToken,
));
}
let credentials = Credentials::Bearer {
token: Token::new(value.token.unwrap().into_bytes()),
};
Ok(Self {
service: value.service,
credentials,
})
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct TomlCredentials {
/// Array of credential entries.
#[serde(rename = "credential")]
credentials: Vec<TomlCredential>,
}
/// A credential store with a plain text storage backend.
#[derive(Debug, Default)]
pub struct TextCredentialStore {
credentials: FxHashMap<(Service, Username), Credentials>,
}
impl TextCredentialStore {
/// Return the directory for storing credentials.
pub fn directory_path() -> Result<PathBuf, TomlCredentialError> {
if let Some(dir) = std::env::var_os(EnvVars::UV_CREDENTIALS_DIR)
.filter(|s| !s.is_empty())
.map(PathBuf::from)
{
return Ok(dir);
}
Ok(StateStore::from_settings(None)?.bucket(StateBucket::Credentials))
}
/// Return the standard file path for storing credentials.
pub fn default_file() -> Result<PathBuf, TomlCredentialError> {
let dir = Self::directory_path()?;
Ok(dir.join("credentials.toml"))
}
/// Acquire a lock on the credentials file at the given path.
pub async fn lock(path: &Path) -> Result<LockedFile, TomlCredentialError> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let lock = with_added_extension(path, ".lock");
Ok(LockedFile::acquire(lock, LockedFileMode::Exclusive, "credentials store").await?)
}
/// Read credentials from a file.
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, TomlCredentialError> {
let content = fs::read_to_string(path)?;
let credentials: TomlCredentials = toml::from_str(&content)?;
let credentials: FxHashMap<(Service, Username), Credentials> = credentials
.credentials
.into_iter()
.map(|credential| {
let username = match &credential.credentials {
Credentials::Basic { username, .. } => username.clone(),
Credentials::Bearer { .. } => Username::none(),
};
(
(credential.service.clone(), username),
credential.credentials,
)
})
.collect();
Ok(Self { credentials })
}
/// Read credentials from a file.
///
/// Returns [`TextCredentialStore`] and a [`LockedFile`] to hold if mutating the store.
///
/// If the store will not be written to following the read, the lock can be dropped.
pub async fn read<P: AsRef<Path>>(path: P) -> Result<(Self, LockedFile), TomlCredentialError> {
let lock = Self::lock(path.as_ref()).await?;
let store = Self::from_file(path)?;
Ok((store, lock))
}
/// Persist credentials to a file.
///
/// Requires a [`LockedFile`] from [`TextCredentialStore::lock`] or
/// [`TextCredentialStore::read`] to ensure exclusive access.
pub fn write<P: AsRef<Path>>(
self,
path: P,
_lock: LockedFile,
) -> Result<(), TomlCredentialError> {
let credentials = self
.credentials
.into_iter()
.map(|((service, _username), credentials)| TomlCredential {
service,
credentials,
})
.collect::<Vec<_>>();
let toml_creds = TomlCredentials { credentials };
let content = toml::to_string_pretty(&toml_creds)?;
fs::create_dir_all(
path.as_ref()
.parent()
.ok_or(TomlCredentialError::CredentialsDirError)?,
)?;
// TODO(zanieb): We should use an atomic write here
fs::write(path, content)?;
Ok(())
}
/// Get credentials for a given URL and username.
///
/// The most specific URL prefix match in the same [`Realm`] is returned, if any.
pub fn get_credentials(
&self,
url: &DisplaySafeUrl,
username: Option<&str>,
) -> Option<&Credentials> {
let request_realm = Realm::from(url);
// Perform an exact lookup first
// TODO(zanieb): Consider adding `DisplaySafeUrlRef` so we can avoid this clone
// TODO(zanieb): We could also return early here if we can't normalize to a `Service`
if let Ok(url_service) = Service::try_from(url.clone()) {
if let Some(credential) = self.credentials.get(&(
url_service.clone(),
Username::from(username.map(str::to_string)),
)) {
return Some(credential);
}
}
// If that fails, iterate through to find a prefix match
let mut best: Option<(usize, &Service, &Credentials)> = None;
for ((service, stored_username), credential) in &self.credentials {
let service_realm = Realm::from(service.url().deref());
// Only consider services in the same realm
if service_realm != request_realm {
continue;
}
// Service path must be a prefix of request path
if !url.path().starts_with(service.url().path()) {
continue;
}
// If a username is provided, it must match
if let Some(request_username) = username {
if Some(request_username) != stored_username.as_deref() {
continue;
}
}
// Update our best matching credential based on prefix length
let specificity = service.url().path().len();
if best.is_none_or(|(best_specificity, _, _)| specificity > best_specificity) {
best = Some((specificity, service, credential));
}
}
// Return the most specific match
if let Some((_, _, credential)) = best {
return Some(credential);
}
None
}
/// Store credentials for a given service.
pub fn insert(&mut self, service: Service, credentials: Credentials) -> Option<Credentials> {
let username = match &credentials {
Credentials::Basic { username, .. } => username.clone(),
Credentials::Bearer { .. } => Username::none(),
};
self.credentials.insert((service, username), credentials)
}
/// Remove credentials for a given service.
pub fn remove(&mut self, service: &Service, username: Username) -> Option<Credentials> {
// Remove the specific credential for this service and username
self.credentials.remove(&(service.clone(), username))
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use std::str::FromStr;
use tempfile::NamedTempFile;
use super::*;
#[test]
fn test_toml_serialization() {
let credentials = TomlCredentials {
credentials: vec![
TomlCredential {
service: Service::from_str("https://example.com").unwrap(),
credentials: Credentials::Basic {
username: Username::new(Some("user1".to_string())),
password: Some(Password::new("pass1".to_string())),
},
},
TomlCredential {
service: Service::from_str("https://test.org").unwrap(),
credentials: Credentials::Basic {
username: Username::new(Some("user2".to_string())),
password: Some(Password::new("pass2".to_string())),
},
},
],
};
let toml_str = toml::to_string_pretty(&credentials).unwrap();
let parsed: TomlCredentials = toml::from_str(&toml_str).unwrap();
assert_eq!(parsed.credentials.len(), 2);
assert_eq!(
parsed.credentials[0].service.to_string(),
"https://example.com/"
);
assert_eq!(
parsed.credentials[1].service.to_string(),
"https://test.org/"
);
}
#[test]
fn test_credential_store_operations() {
let mut store = TextCredentialStore::default();
let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
let service = Service::from_str("https://example.com").unwrap();
store.insert(service.clone(), credentials.clone());
let url = DisplaySafeUrl::parse("https://example.com/").unwrap();
assert!(store.get_credentials(&url, None).is_some());
let url = DisplaySafeUrl::parse("https://example.com/path").unwrap();
let retrieved = store.get_credentials(&url, None).unwrap();
assert_eq!(retrieved.username(), Some("user"));
assert_eq!(retrieved.password(), Some("pass"));
assert!(
store
.remove(&service, Username::from(Some("user".to_string())))
.is_some()
);
let url = DisplaySafeUrl::parse("https://example.com/").unwrap();
assert!(store.get_credentials(&url, None).is_none());
}
#[tokio::test]
async fn test_file_operations() {
let mut temp_file = NamedTempFile::new().unwrap();
writeln!(
temp_file,
r#"
[[credential]]
service = "https://example.com"
username = "testuser"
scheme = "basic"
password = "testpass"
[[credential]]
service = "https://test.org"
username = "user2"
password = "pass2"
"#
)
.unwrap();
let store = TextCredentialStore::from_file(temp_file.path()).unwrap();
let url = DisplaySafeUrl::parse("https://example.com/").unwrap();
assert!(store.get_credentials(&url, None).is_some());
let url = DisplaySafeUrl::parse("https://test.org/").unwrap();
assert!(store.get_credentials(&url, None).is_some());
let url = DisplaySafeUrl::parse("https://example.com").unwrap();
let cred = store.get_credentials(&url, None).unwrap();
assert_eq!(cred.username(), Some("testuser"));
assert_eq!(cred.password(), Some("testpass"));
// Test saving
let temp_output = NamedTempFile::new().unwrap();
store
.write(
temp_output.path(),
TextCredentialStore::lock(temp_file.path()).await.unwrap(),
)
.unwrap();
let content = fs::read_to_string(temp_output.path()).unwrap();
assert!(content.contains("example.com"));
assert!(content.contains("testuser"));
}
#[test]
fn test_prefix_matching() {
let mut store = TextCredentialStore::default();
let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
// Store credentials for a specific path prefix
let service = Service::from_str("https://example.com/api").unwrap();
store.insert(service.clone(), credentials.clone());
// Should match URLs that are prefixes of the stored service
let matching_urls = [
"https://example.com/api",
"https://example.com/api/v1",
"https://example.com/api/v1/users",
];
for url_str in matching_urls {
let url = DisplaySafeUrl::parse(url_str).unwrap();
let cred = store.get_credentials(&url, None);
assert!(cred.is_some(), "Failed to match URL with prefix: {url_str}");
}
// Should NOT match URLs that are not prefixes
let non_matching_urls = [
"https://example.com/different",
"https://example.com/ap", // Not a complete path segment match
"https://example.com", // Shorter than the stored prefix
];
for url_str in non_matching_urls {
let url = DisplaySafeUrl::parse(url_str).unwrap();
let cred = store.get_credentials(&url, None);
assert!(cred.is_none(), "Should not match non-prefix URL: {url_str}");
}
}
#[test]
fn test_realm_based_matching() {
let mut store = TextCredentialStore::default();
let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
// Store by full URL (realm)
let service = Service::from_str("https://example.com").unwrap();
store.insert(service.clone(), credentials.clone());
// Should match URLs in the same realm
let matching_urls = [
"https://example.com",
"https://example.com/path",
"https://example.com/different/path",
"https://example.com:443/path", // Default HTTPS port
];
for url_str in matching_urls {
let url = DisplaySafeUrl::parse(url_str).unwrap();
let cred = store.get_credentials(&url, None);
assert!(
cred.is_some(),
"Failed to match URL in same realm: {url_str}"
);
}
// Should NOT match URLs in different realms
let non_matching_urls = [
"http://example.com", // Different scheme
"https://different.com", // Different host
"https://example.com:8080", // Different port
];
for url_str in non_matching_urls {
let url = DisplaySafeUrl::parse(url_str).unwrap();
let cred = store.get_credentials(&url, None);
assert!(
cred.is_none(),
"Should not match URL in different realm: {url_str}"
);
}
}
#[test]
fn test_most_specific_prefix_matching() {
let mut store = TextCredentialStore::default();
let general_cred =
Credentials::basic(Some("general".to_string()), Some("pass1".to_string()));
let specific_cred =
Credentials::basic(Some("specific".to_string()), Some("pass2".to_string()));
// Store credentials with different prefix lengths
let general_service = Service::from_str("https://example.com/api").unwrap();
let specific_service = Service::from_str("https://example.com/api/v1").unwrap();
store.insert(general_service.clone(), general_cred);
store.insert(specific_service.clone(), specific_cred);
// Should match the most specific prefix
let url = DisplaySafeUrl::parse("https://example.com/api/v1/users").unwrap();
let cred = store.get_credentials(&url, None).unwrap();
assert_eq!(cred.username(), Some("specific"));
// Should match the general prefix for non-specific paths
let url = DisplaySafeUrl::parse("https://example.com/api/v2").unwrap();
let cred = store.get_credentials(&url, None).unwrap();
assert_eq!(cred.username(), Some("general"));
}
#[test]
fn test_username_exact_url_match() {
let mut store = TextCredentialStore::default();
let url = DisplaySafeUrl::parse("https://example.com").unwrap();
let service = Service::from_str("https://example.com").unwrap();
let user1_creds = Credentials::basic(Some("user1".to_string()), Some("pass1".to_string()));
store.insert(service.clone(), user1_creds.clone());
// Should return credentials when username matches
let result = store.get_credentials(&url, Some("user1"));
assert!(result.is_some());
assert_eq!(result.unwrap().username(), Some("user1"));
assert_eq!(result.unwrap().password(), Some("pass1"));
// Should not return credentials when username doesn't match
let result = store.get_credentials(&url, Some("user2"));
assert!(result.is_none());
// Should return credentials when no username is specified
let result = store.get_credentials(&url, None);
assert!(result.is_some());
assert_eq!(result.unwrap().username(), Some("user1"));
}
#[test]
fn test_username_prefix_url_match() {
let mut store = TextCredentialStore::default();
// Add credentials with different usernames for overlapping URL prefixes
let general_service = Service::from_str("https://example.com/api").unwrap();
let specific_service = Service::from_str("https://example.com/api/v1").unwrap();
let general_creds = Credentials::basic(
Some("general_user".to_string()),
Some("general_pass".to_string()),
);
let specific_creds = Credentials::basic(
Some("specific_user".to_string()),
Some("specific_pass".to_string()),
);
store.insert(general_service, general_creds);
store.insert(specific_service, specific_creds);
let url = DisplaySafeUrl::parse("https://example.com/api/v1/users").unwrap();
// Should match specific credentials when username matches
let result = store.get_credentials(&url, Some("specific_user"));
assert!(result.is_some());
assert_eq!(result.unwrap().username(), Some("specific_user"));
// Should match the general credentials when requesting general_user (falls back to less specific prefix)
let result = store.get_credentials(&url, Some("general_user"));
assert!(
result.is_some(),
"Should match general_user from less specific prefix"
);
assert_eq!(result.unwrap().username(), Some("general_user"));
// Should match most specific when no username specified
let result = store.get_credentials(&url, None);
assert!(result.is_some());
assert_eq!(result.unwrap().username(), Some("specific_user"));
}
}
| 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-auth/src/access_token.rs | crates/uv-auth/src/access_token.rs | /// An encoded JWT access token.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct AccessToken(String);
impl AccessToken {
/// Return the [`AccessToken`] as a vector of bytes.
pub fn into_bytes(self) -> Vec<u8> {
self.0.into_bytes()
}
/// Return the [`AccessToken`] as a string slice.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<String> for AccessToken {
fn from(value: String) -> Self {
Self(value)
}
}
impl AsRef<[u8]> for AccessToken {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl std::fmt::Display for AccessToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(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-auth/src/pyx.rs | crates/uv-auth/src/pyx.rs | use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
use base64::Engine;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use etcetera::BaseStrategy;
use reqwest_middleware::ClientWithMiddleware;
use tracing::debug;
use url::Url;
use uv_cache_key::CanonicalUrl;
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
use uv_small_str::SmallString;
use uv_state::{StateBucket, StateStore};
use uv_static::EnvVars;
use crate::credentials::Token;
use crate::{AccessToken, Credentials, Realm};
/// Retrieve the pyx API key from the environment variable, or return `None`.
fn read_pyx_api_key() -> Option<String> {
std::env::var(EnvVars::PYX_API_KEY)
.ok()
.or_else(|| std::env::var(EnvVars::UV_API_KEY).ok())
}
/// Retrieve the pyx authentication token (JWT) from the environment variable, or return `None`.
fn read_pyx_auth_token() -> Option<AccessToken> {
std::env::var(EnvVars::PYX_AUTH_TOKEN)
.ok()
.or_else(|| std::env::var(EnvVars::UV_AUTH_TOKEN).ok())
.map(AccessToken::from)
}
/// An access token with an accompanying refresh token.
///
/// Refresh tokens are single-use tokens that can be exchanged for a renewed access token
/// and a new refresh token.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PyxOAuthTokens {
pub access_token: AccessToken,
pub refresh_token: String,
}
/// An access token with an accompanying API key.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PyxApiKeyTokens {
pub access_token: AccessToken,
pub api_key: String,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum PyxTokens {
/// An access token with an accompanying refresh token.
///
/// Refresh tokens are single-use tokens that can be exchanged for a renewed access token
/// and a new refresh token.
OAuth(PyxOAuthTokens),
/// An access token with an accompanying API key.
///
/// API keys are long-lived tokens that can be exchanged for an access token.
ApiKey(PyxApiKeyTokens),
}
impl From<PyxTokens> for AccessToken {
fn from(tokens: PyxTokens) -> Self {
match tokens {
PyxTokens::OAuth(PyxOAuthTokens { access_token, .. }) => access_token,
PyxTokens::ApiKey(PyxApiKeyTokens { access_token, .. }) => access_token,
}
}
}
impl From<PyxTokens> for Credentials {
fn from(tokens: PyxTokens) -> Self {
let access_token = match tokens {
PyxTokens::OAuth(PyxOAuthTokens { access_token, .. }) => access_token,
PyxTokens::ApiKey(PyxApiKeyTokens { access_token, .. }) => access_token,
};
Self::from(access_token)
}
}
impl From<AccessToken> for Credentials {
fn from(access_token: AccessToken) -> Self {
Self::Bearer {
token: Token::new(access_token.into_bytes()),
}
}
}
/// The default tolerance for the access token expiration.
pub const DEFAULT_TOLERANCE_SECS: u64 = 60 * 5;
#[derive(Debug, Clone)]
struct PyxDirectories {
/// The root directory for the token store (e.g., `/Users/ferris/.local/share/pyx/credentials`).
root: PathBuf,
/// The subdirectory for the token store (e.g., `/Users/ferris/.local/share/uv/credentials/3859a629b26fda96`).
subdirectory: PathBuf,
}
impl PyxDirectories {
/// Detect the [`PyxDirectories`] for a given API URL.
fn from_api(api: &DisplaySafeUrl) -> Result<Self, io::Error> {
// Store credentials in a subdirectory based on the API URL.
let digest = uv_cache_key::cache_digest(&CanonicalUrl::new(api));
// If the user explicitly set `PYX_CREDENTIALS_DIR`, use that.
if let Some(root) = std::env::var_os(EnvVars::PYX_CREDENTIALS_DIR) {
let root = std::path::absolute(root)?;
let subdirectory = root.join(&digest);
return Ok(Self { root, subdirectory });
}
// If the user has pyx credentials in their uv credentials directory, read them for
// backwards compatibility.
let root = if let Some(tool_dir) = std::env::var_os(EnvVars::UV_CREDENTIALS_DIR) {
std::path::absolute(tool_dir)?
} else {
StateStore::from_settings(None)?.bucket(StateBucket::Credentials)
};
let subdirectory = root.join(&digest);
if subdirectory.exists() {
return Ok(Self { root, subdirectory });
}
// Otherwise, use (e.g.) `~/.local/share/pyx`.
let Ok(xdg) = etcetera::base_strategy::choose_base_strategy() else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"Could not determine user data directory",
));
};
let root = xdg.data_dir().join("pyx").join("credentials");
let subdirectory = root.join(&digest);
Ok(Self { root, subdirectory })
}
}
#[derive(Debug, Clone)]
pub struct PyxTokenStore {
/// The root directory for the token store (e.g., `/Users/ferris/.local/share/pyx/credentials`).
root: PathBuf,
/// The subdirectory for the token store (e.g., `/Users/ferris/.local/share/uv/credentials/3859a629b26fda96`).
subdirectory: PathBuf,
/// The API URL for the token store (e.g., `https://api.pyx.dev`).
api: DisplaySafeUrl,
/// The CDN domain for the token store (e.g., `astralhosted.com`).
cdn: SmallString,
}
impl PyxTokenStore {
/// Create a new [`PyxTokenStore`] from settings.
pub fn from_settings() -> Result<Self, TokenStoreError> {
// Read the API URL and CDN domain from the environment variables, or fallback to the
// defaults.
let api = if let Ok(api_url) = std::env::var(EnvVars::PYX_API_URL) {
DisplaySafeUrl::parse(&api_url)
} else {
DisplaySafeUrl::parse("https://api.pyx.dev")
}?;
let cdn = std::env::var(EnvVars::PYX_CDN_DOMAIN)
.ok()
.map(SmallString::from)
.unwrap_or_else(|| SmallString::from(arcstr::literal!("astralhosted.com")));
// Determine the root directory for the token store.
let PyxDirectories { root, subdirectory } = PyxDirectories::from_api(&api)?;
Ok(Self {
root,
subdirectory,
api,
cdn,
})
}
/// Return the root directory for the token store.
pub fn root(&self) -> &Path {
&self.root
}
/// Return the API URL for the token store.
pub fn api(&self) -> &DisplaySafeUrl {
&self.api
}
/// Get or initialize an [`AccessToken`] from the store.
///
/// If an access token is set in the environment, it will be returned as-is.
///
/// If an access token is present on-disk, it will be returned (and refreshed, if necessary).
///
/// If no access token is found, but an API key is present, the API key will be used to
/// bootstrap an access token.
pub async fn access_token(
&self,
client: &ClientWithMiddleware,
tolerance_secs: u64,
) -> Result<Option<AccessToken>, TokenStoreError> {
// If the access token is already set in the environment, return it.
if let Some(access_token) = read_pyx_auth_token() {
return Ok(Some(access_token));
}
// Initialize the tokens from the store.
let tokens = self.init(client, tolerance_secs).await?;
// Extract the access token from the OAuth tokens or API key.
Ok(tokens.map(AccessToken::from))
}
/// Initialize the [`PyxTokens`] from the store.
///
/// If an access token is already present, it will be returned (and refreshed, if necessary).
///
/// If no access token is found, but an API key is present, the API key will be used to
/// bootstrap an access token.
pub async fn init(
&self,
client: &ClientWithMiddleware,
tolerance_secs: u64,
) -> Result<Option<PyxTokens>, TokenStoreError> {
match self.read().await? {
Some(tokens) => {
// Refresh the tokens if they are expired.
let tokens = self.refresh(tokens, client, tolerance_secs).await?;
Ok(Some(tokens))
}
None => {
// If no tokens are present, bootstrap them from an API key.
self.bootstrap(client).await
}
}
}
/// Write the tokens to the store.
pub async fn write(&self, tokens: &PyxTokens) -> Result<(), TokenStoreError> {
fs_err::tokio::create_dir_all(&self.subdirectory).await?;
match tokens {
PyxTokens::OAuth(tokens) => {
// Write OAuth tokens to a generic `tokens.json` file.
fs_err::tokio::write(
self.subdirectory.join("tokens.json"),
serde_json::to_vec(tokens)?,
)
.await?;
}
PyxTokens::ApiKey(tokens) => {
// Write API key tokens to a file based on the API key.
let digest = uv_cache_key::cache_digest(&tokens.api_key);
fs_err::tokio::write(
self.subdirectory.join(format!("{digest}.json")),
&tokens.access_token,
)
.await?;
}
}
Ok(())
}
/// Returns `true` if the user appears to have an authentication token set.
pub fn has_auth_token(&self) -> bool {
read_pyx_auth_token().is_some()
}
/// Returns `true` if the user appears to have an API key set.
pub fn has_api_key(&self) -> bool {
read_pyx_api_key().is_some()
}
/// Returns `true` if the user appears to have OAuth tokens stored on disk.
pub fn has_oauth_tokens(&self) -> bool {
self.subdirectory.join("tokens.json").is_file()
}
/// Returns `true` if the user appears to have credentials (which may be invalid).
pub fn has_credentials(&self) -> bool {
self.has_auth_token() || self.has_api_key() || self.has_oauth_tokens()
}
/// Read the tokens from the store.
pub async fn read(&self) -> Result<Option<PyxTokens>, TokenStoreError> {
if let Some(api_key) = read_pyx_api_key() {
// Read the API key tokens from a file based on the API key.
let digest = uv_cache_key::cache_digest(&api_key);
match fs_err::tokio::read(self.subdirectory.join(format!("{digest}.json"))).await {
Ok(data) => {
let access_token =
AccessToken::from(String::from_utf8(data).expect("Invalid UTF-8"));
Ok(Some(PyxTokens::ApiKey(PyxApiKeyTokens {
access_token,
api_key,
})))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
} else {
match fs_err::tokio::read(self.subdirectory.join("tokens.json")).await {
Ok(data) => {
let tokens: PyxOAuthTokens = serde_json::from_slice(&data)?;
Ok(Some(PyxTokens::OAuth(tokens)))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
}
/// Remove the tokens from the store.
pub async fn delete(&self) -> Result<(), io::Error> {
fs_err::tokio::remove_dir_all(&self.subdirectory).await?;
Ok(())
}
/// Bootstrap the tokens from the store.
async fn bootstrap(
&self,
client: &ClientWithMiddleware,
) -> Result<Option<PyxTokens>, TokenStoreError> {
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
struct Payload {
access_token: AccessToken,
}
// Retrieve the API key from the environment variable, if set.
let Some(api_key) = read_pyx_api_key() else {
return Ok(None);
};
debug!("Bootstrapping access token from an API key");
// Parse the API URL.
let mut url = self.api.clone();
url.set_path("auth/cli/access-token");
let mut request = reqwest::Request::new(reqwest::Method::POST, Url::from(url));
request.headers_mut().insert(
"Authorization",
reqwest::header::HeaderValue::from_str(&format!("Bearer {api_key}"))?,
);
let response = client.execute(request).await?;
let Payload { access_token } = response.error_for_status()?.json::<Payload>().await?;
let tokens = PyxTokens::ApiKey(PyxApiKeyTokens {
access_token,
api_key,
});
// Write the tokens to disk.
self.write(&tokens).await?;
Ok(Some(tokens))
}
/// Refresh the tokens in the store, if they are expired.
///
/// In theory, we should _also_ refresh if we hit a 401; but for now, we only refresh ahead of
/// time.
async fn refresh(
&self,
tokens: PyxTokens,
client: &ClientWithMiddleware,
tolerance_secs: u64,
) -> Result<PyxTokens, TokenStoreError> {
// Decode the access token.
let jwt = PyxJwt::decode(match &tokens {
PyxTokens::OAuth(PyxOAuthTokens { access_token, .. }) => access_token,
PyxTokens::ApiKey(PyxApiKeyTokens { access_token, .. }) => access_token,
})?;
// If the access token is expired, refresh it.
let is_up_to_date = match jwt.exp {
None => {
debug!("Access token has no expiration; refreshing...");
false
}
Some(..) if tolerance_secs == 0 => {
debug!("Refreshing access token due to zero tolerance...");
false
}
Some(jwt) => {
let exp = jiff::Timestamp::from_second(jwt)?;
let now = jiff::Timestamp::now();
if exp < now {
debug!("Access token is expired (`{exp}`); refreshing...");
false
} else if exp < now + Duration::from_secs(tolerance_secs) {
debug!(
"Access token will expire within the tolerance (`{exp}`); refreshing..."
);
false
} else {
debug!("Access token is up-to-date (`{exp}`)");
true
}
}
};
if is_up_to_date {
return Ok(tokens);
}
let tokens = match tokens {
PyxTokens::OAuth(PyxOAuthTokens { refresh_token, .. }) => {
// Parse the API URL.
let mut url = self.api.clone();
url.set_path("auth/cli/refresh");
let mut request = reqwest::Request::new(reqwest::Method::POST, Url::from(url));
let body = serde_json::json!({
"refresh_token": refresh_token
});
*request.body_mut() = Some(body.to_string().into());
let response = client.execute(request).await?;
let tokens = response
.error_for_status()?
.json::<PyxOAuthTokens>()
.await?;
PyxTokens::OAuth(tokens)
}
PyxTokens::ApiKey(PyxApiKeyTokens { api_key, .. }) => {
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
struct Payload {
access_token: AccessToken,
}
// Parse the API URL.
let mut url = self.api.clone();
url.set_path("auth/cli/access-token");
let mut request = reqwest::Request::new(reqwest::Method::POST, Url::from(url));
request.headers_mut().insert(
"Authorization",
reqwest::header::HeaderValue::from_str(&format!("Bearer {api_key}"))?,
);
let response = client.execute(request).await?;
let Payload { access_token } =
response.error_for_status()?.json::<Payload>().await?;
PyxTokens::ApiKey(PyxApiKeyTokens {
access_token,
api_key,
})
}
};
// Write the new tokens to disk.
self.write(&tokens).await?;
Ok(tokens)
}
/// Returns `true` if the given URL is "known" to this token store (i.e., should be
/// authenticated using the store's tokens).
pub fn is_known_url(&self, url: &Url) -> bool {
is_known_url(url, &self.api, &self.cdn)
}
/// Returns `true` if the URL is on a "known" domain (i.e., the same domain as the API or CDN).
///
/// Like [`is_known_url`](Self::is_known_url), but also returns `true` if the API is on the
/// subdomain of the URL (e.g., if the API is `api.pyx.dev` and the URL is `pyx.dev`).
pub fn is_known_domain(&self, url: &Url) -> bool {
is_known_domain(url, &self.api, &self.cdn)
}
}
#[derive(thiserror::Error, Debug)]
pub enum TokenStoreError {
#[error(transparent)]
Url(#[from] DisplaySafeUrlError),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Serialization(#[from] serde_json::Error),
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error(transparent)]
ReqwestMiddleware(#[from] reqwest_middleware::Error),
#[error(transparent)]
InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),
#[error(transparent)]
Jiff(#[from] jiff::Error),
#[error(transparent)]
Jwt(#[from] JwtError),
}
impl TokenStoreError {
/// Returns `true` if the error is a 401 (Unauthorized) error.
pub fn is_unauthorized(&self) -> bool {
match self {
Self::Reqwest(err) => err.status() == Some(reqwest::StatusCode::UNAUTHORIZED),
Self::ReqwestMiddleware(err) => err.status() == Some(reqwest::StatusCode::UNAUTHORIZED),
_ => false,
}
}
}
/// The payload of the JWT.
#[derive(Debug, serde::Deserialize)]
pub struct PyxJwt {
/// The expiration time of the JWT, as a Unix timestamp.
pub exp: Option<i64>,
/// The issuer of the JWT.
pub iss: Option<String>,
/// The name of the organization, if any.
#[serde(rename = "urn:pyx:org_name")]
pub name: Option<String>,
}
impl PyxJwt {
/// Decode the JWT from the access token.
pub fn decode(access_token: &AccessToken) -> Result<Self, JwtError> {
let mut token_segments = access_token.as_str().splitn(3, '.');
let _header = token_segments.next().ok_or(JwtError::MissingHeader)?;
let payload = token_segments.next().ok_or(JwtError::MissingPayload)?;
let _signature = token_segments.next().ok_or(JwtError::MissingSignature)?;
if token_segments.next().is_some() {
return Err(JwtError::TooManySegments);
}
let decoded = BASE64_URL_SAFE_NO_PAD.decode(payload)?;
let jwt = serde_json::from_slice::<Self>(&decoded)?;
Ok(jwt)
}
}
#[derive(thiserror::Error, Debug)]
pub enum JwtError {
#[error("JWT is missing a header")]
MissingHeader,
#[error("JWT is missing a payload")]
MissingPayload,
#[error("JWT is missing a signature")]
MissingSignature,
#[error("JWT has too many segments")]
TooManySegments,
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error(transparent)]
Serde(#[from] serde_json::Error),
}
fn is_known_url(url: &Url, api: &DisplaySafeUrl, cdn: &str) -> bool {
// Determine whether the URL matches the API realm.
if Realm::from(url) == Realm::from(&**api) {
return true;
}
// Determine whether the URL matches the CDN domain (or a subdomain of it).
//
// For example, if URL is on `files.astralhosted.com` and the CDN domain is
// `astralhosted.com`, consider it known.
if matches!(url.scheme(), "https") && matches_domain(url, cdn) {
return true;
}
false
}
fn is_known_domain(url: &Url, api: &DisplaySafeUrl, cdn: &str) -> bool {
// Determine whether the URL matches the API domain.
if let Some(domain) = url.domain() {
if matches_domain(api, domain) {
return true;
}
}
is_known_url(url, api, cdn)
}
/// Returns `true` if the target URL is on the given domain.
fn matches_domain(url: &Url, domain: &str) -> bool {
url.domain().is_some_and(|subdomain| {
subdomain == domain
|| subdomain
.strip_suffix(domain)
.is_some_and(|prefix| prefix.ends_with('.'))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_known_url() {
let api_url = DisplaySafeUrl::parse("https://api.pyx.dev").unwrap();
let cdn_domain = "astralhosted.com";
// Same realm as API.
assert!(is_known_url(
&Url::parse("https://api.pyx.dev/simple/").unwrap(),
&api_url,
cdn_domain
));
// Different path on same API domain
assert!(is_known_url(
&Url::parse("https://api.pyx.dev/v1/").unwrap(),
&api_url,
cdn_domain
));
// CDN domain.
assert!(is_known_url(
&Url::parse("https://astralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
// CDN subdomain.
assert!(is_known_url(
&Url::parse("https://files.astralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
// CDN on HTTP.
assert!(!is_known_url(
&Url::parse("http://astralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
// Unknown domain.
assert!(!is_known_url(
&Url::parse("https://pypi.org/simple/").unwrap(),
&api_url,
cdn_domain
));
// Similar but not matching domain.
assert!(!is_known_url(
&Url::parse("https://badastralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
}
#[test]
fn test_is_known_domain() {
let api_url = DisplaySafeUrl::parse("https://api.pyx.dev").unwrap();
let cdn_domain = "astralhosted.com";
// Same realm as API.
assert!(is_known_domain(
&Url::parse("https://api.pyx.dev/simple/").unwrap(),
&api_url,
cdn_domain
));
// API super-domain.
assert!(is_known_domain(
&Url::parse("https://pyx.dev").unwrap(),
&api_url,
cdn_domain
));
// API subdomain.
assert!(!is_known_domain(
&Url::parse("https://foo.api.pyx.dev").unwrap(),
&api_url,
cdn_domain
));
// Different subdomain.
assert!(!is_known_domain(
&Url::parse("https://beta.pyx.dev/").unwrap(),
&api_url,
cdn_domain
));
// CDN domain.
assert!(is_known_domain(
&Url::parse("https://astralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
// CDN subdomain.
assert!(is_known_domain(
&Url::parse("https://files.astralhosted.com/packages/").unwrap(),
&api_url,
cdn_domain
));
// Unknown domain.
assert!(!is_known_domain(
&Url::parse("https://pypi.org/simple/").unwrap(),
&api_url,
cdn_domain
));
// Different TLD.
assert!(!is_known_domain(
&Url::parse("https://pyx.com/").unwrap(),
&api_url,
cdn_domain
));
}
#[test]
fn test_matches_domain() {
assert!(matches_domain(
&Url::parse("https://example.com").unwrap(),
"example.com"
));
assert!(matches_domain(
&Url::parse("https://foo.example.com").unwrap(),
"example.com"
));
assert!(matches_domain(
&Url::parse("https://bar.foo.example.com").unwrap(),
"example.com"
));
assert!(!matches_domain(
&Url::parse("https://example.com").unwrap(),
"other.com"
));
assert!(!matches_domain(
&Url::parse("https://example.org").unwrap(),
"example.com"
));
assert!(!matches_domain(
&Url::parse("https://badexample.com").unwrap(),
"example.com"
));
}
}
| 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-auth/src/middleware.rs | crates/uv-auth/src/middleware.rs | use std::sync::{Arc, LazyLock};
use anyhow::{anyhow, format_err};
use http::{Extensions, StatusCode};
use netrc::Netrc;
use reqwest::{Request, Response};
use reqwest_middleware::{ClientWithMiddleware, Error, Middleware, Next};
use tokio::sync::Mutex;
use tracing::{debug, trace, warn};
use uv_preview::{Preview, PreviewFeatures};
use uv_redacted::DisplaySafeUrl;
use uv_static::EnvVars;
use uv_warnings::owo_colors::OwoColorize;
use crate::credentials::Authentication;
use crate::providers::{HuggingFaceProvider, S3EndpointProvider};
use crate::pyx::{DEFAULT_TOLERANCE_SECS, PyxTokenStore};
use crate::{
AccessToken, CredentialsCache, KeyringProvider,
cache::FetchUrl,
credentials::{Credentials, Username},
index::{AuthPolicy, Indexes},
realm::Realm,
};
use crate::{Index, TextCredentialStore};
/// Cached check for whether we're running in Dependabot.
static IS_DEPENDABOT: LazyLock<bool> =
LazyLock::new(|| std::env::var(EnvVars::DEPENDABOT).is_ok_and(|value| value == "true"));
/// Strategy for loading netrc files.
enum NetrcMode {
Automatic(LazyLock<Option<Netrc>>),
Enabled(Netrc),
Disabled,
}
impl Default for NetrcMode {
fn default() -> Self {
Self::Automatic(LazyLock::new(|| match Netrc::new() {
Ok(netrc) => Some(netrc),
Err(netrc::Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
debug!("No netrc file found");
None
}
Err(err) => {
warn!("Error reading netrc file: {err}");
None
}
}))
}
}
impl NetrcMode {
/// Get the parsed netrc file if enabled.
fn get(&self) -> Option<&Netrc> {
match self {
Self::Automatic(lock) => lock.as_ref(),
Self::Enabled(netrc) => Some(netrc),
Self::Disabled => None,
}
}
}
/// Strategy for loading text-based credential files.
enum TextStoreMode {
Automatic(tokio::sync::OnceCell<Option<TextCredentialStore>>),
Enabled(TextCredentialStore),
Disabled,
}
impl Default for TextStoreMode {
fn default() -> Self {
Self::Automatic(tokio::sync::OnceCell::new())
}
}
impl TextStoreMode {
async fn load_default_store() -> Option<TextCredentialStore> {
let path = TextCredentialStore::default_file()
.inspect_err(|err| {
warn!("Failed to determine credentials file path: {}", err);
})
.ok()?;
match TextCredentialStore::read(&path).await {
Ok((store, _lock)) => {
debug!("Loaded credential file {}", path.display());
Some(store)
}
Err(err)
if err
.as_io_error()
.is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) =>
{
debug!("No credentials file found at {}", path.display());
None
}
Err(err) => {
warn!(
"Failed to load credentials from {}: {}",
path.display(),
err
);
None
}
}
}
/// Get the parsed credential store, if enabled.
async fn get(&self) -> Option<&TextCredentialStore> {
match self {
// TODO(zanieb): Reconsider this pattern. We're just mirroring the [`NetrcMode`]
// implementation for now.
Self::Automatic(lock) => lock.get_or_init(Self::load_default_store).await.as_ref(),
Self::Enabled(store) => Some(store),
Self::Disabled => None,
}
}
}
#[derive(Debug, Clone)]
enum TokenState {
/// The token state has not yet been initialized from the store.
Uninitialized,
/// The token state has been initialized, and the store either returned tokens or `None` if
/// the user has not yet authenticated.
Initialized(Option<AccessToken>),
}
#[derive(Clone)]
enum S3CredentialState {
/// The S3 credential state has not yet been initialized.
Uninitialized,
/// The S3 credential state has been initialized, with either a signer or `None` if
/// no S3 endpoint is configured.
Initialized(Option<Arc<Authentication>>),
}
/// A middleware that adds basic authentication to requests.
///
/// Uses a cache to propagate credentials from previously seen requests and
/// fetches credentials from a netrc file, TOML file, and the keyring.
pub struct AuthMiddleware {
netrc: NetrcMode,
text_store: TextStoreMode,
keyring: Option<KeyringProvider>,
/// Global authentication cache for a uv invocation to share credentials across uv clients.
cache: Arc<CredentialsCache>,
/// Auth policies for specific URLs.
indexes: Indexes,
/// Set all endpoints as needing authentication. We never try to send an
/// unauthenticated request, avoiding cloning an uncloneable request.
only_authenticated: bool,
/// The base client to use for requests within the middleware.
base_client: Option<ClientWithMiddleware>,
/// The pyx token store to use for persistent credentials.
pyx_token_store: Option<PyxTokenStore>,
/// Tokens to use for persistent credentials.
pyx_token_state: Mutex<TokenState>,
/// Cached S3 credentials to avoid running the credential helper multiple times.
s3_credential_state: Mutex<S3CredentialState>,
preview: Preview,
}
impl Default for AuthMiddleware {
fn default() -> Self {
Self::new()
}
}
impl AuthMiddleware {
pub fn new() -> Self {
Self {
netrc: NetrcMode::default(),
text_store: TextStoreMode::default(),
keyring: None,
// TODO(konsti): There shouldn't be a credential cache without that in the initializer.
cache: Arc::new(CredentialsCache::default()),
indexes: Indexes::new(),
only_authenticated: false,
base_client: None,
pyx_token_store: None,
pyx_token_state: Mutex::new(TokenState::Uninitialized),
s3_credential_state: Mutex::new(S3CredentialState::Uninitialized),
preview: Preview::default(),
}
}
/// Configure the [`Netrc`] credential file to use.
///
/// `None` disables authentication via netrc.
#[must_use]
pub fn with_netrc(mut self, netrc: Option<Netrc>) -> Self {
self.netrc = if let Some(netrc) = netrc {
NetrcMode::Enabled(netrc)
} else {
NetrcMode::Disabled
};
self
}
/// Configure the text credential store to use.
///
/// `None` disables authentication via text store.
#[must_use]
pub fn with_text_store(mut self, store: Option<TextCredentialStore>) -> Self {
self.text_store = if let Some(store) = store {
TextStoreMode::Enabled(store)
} else {
TextStoreMode::Disabled
};
self
}
/// Configure the [`KeyringProvider`] to use.
#[must_use]
pub fn with_keyring(mut self, keyring: Option<KeyringProvider>) -> Self {
self.keyring = keyring;
self
}
/// Configure the [`Preview`] features to use.
#[must_use]
pub fn with_preview(mut self, preview: Preview) -> Self {
self.preview = preview;
self
}
/// Configure the [`CredentialsCache`] to use.
#[must_use]
pub fn with_cache(mut self, cache: CredentialsCache) -> Self {
self.cache = Arc::new(cache);
self
}
/// Configure the [`CredentialsCache`] to use from an existing [`Arc`].
#[must_use]
pub fn with_cache_arc(mut self, cache: Arc<CredentialsCache>) -> Self {
self.cache = cache;
self
}
/// Configure the [`AuthPolicy`]s to use for URLs.
#[must_use]
pub fn with_indexes(mut self, indexes: Indexes) -> Self {
self.indexes = indexes;
self
}
/// Set all endpoints as needing authentication. We never try to send an
/// unauthenticated request, avoiding cloning an uncloneable request.
#[must_use]
pub fn with_only_authenticated(mut self, only_authenticated: bool) -> Self {
self.only_authenticated = only_authenticated;
self
}
/// Configure the [`ClientWithMiddleware`] to use for requests within the middleware.
#[must_use]
pub fn with_base_client(mut self, client: ClientWithMiddleware) -> Self {
self.base_client = Some(client);
self
}
/// Configure the [`PyxTokenStore`] to use for persistent credentials.
#[must_use]
pub fn with_pyx_token_store(mut self, token_store: PyxTokenStore) -> Self {
self.pyx_token_store = Some(token_store);
self
}
/// Global authentication cache for a uv invocation to share credentials across uv clients.
fn cache(&self) -> &CredentialsCache {
&self.cache
}
}
#[async_trait::async_trait]
impl Middleware for AuthMiddleware {
/// Handle authentication for a request.
///
/// ## If the request has a username and password
///
/// We already have a fully authenticated request and we don't need to perform a look-up.
///
/// - Perform the request
/// - Add the username and password to the cache if successful
///
/// ## If the request only has a username
///
/// We probably need additional authentication, because a username is provided.
/// We'll avoid making a request we expect to fail and look for a password.
/// The discovered credentials must have the requested username to be used.
///
/// - Check the cache (index URL or realm key) for a password
/// - Check the netrc for a password
/// - Check the keyring for a password
/// - Perform the request
/// - Add the username and password to the cache if successful
///
/// ## If the request has no authentication
///
/// We may or may not need authentication. We'll check for cached credentials for the URL,
/// which is relatively specific and can save us an expensive failed request. Otherwise,
/// we'll make the request and look for less-specific credentials on failure i.e. if the
/// server tells us authorization is needed. This pattern avoids attaching credentials to
/// requests that do not need them, which can cause some servers to deny the request.
///
/// - Check the cache (URL key)
/// - Perform the request
/// - On 401, 403, or 404 check for authentication if there was a cache miss
/// - Check the cache (index URL or realm key) for the username and password
/// - Check the netrc for a username and password
/// - Perform the request again if found
/// - Add the username and password to the cache if successful
async fn handle(
&self,
mut request: Request,
extensions: &mut Extensions,
next: Next<'_>,
) -> reqwest_middleware::Result<Response> {
// Check for credentials attached to the request already
let request_credentials = Credentials::from_request(&request).map(Authentication::from);
// In the middleware, existing credentials are already moved from the URL
// to the headers so for display purposes we restore some information
let url = tracing_url(&request, request_credentials.as_ref());
let index = self.indexes.index_for(request.url());
let auth_policy = self.indexes.auth_policy_for(request.url());
trace!("Handling request for {url} with authentication policy {auth_policy}");
let credentials: Option<Arc<Authentication>> = if matches!(auth_policy, AuthPolicy::Never) {
None
} else {
if let Some(request_credentials) = request_credentials {
return self
.complete_request_with_request_credentials(
request_credentials,
request,
extensions,
next,
&url,
index,
auth_policy,
)
.await;
}
// We have no credentials
trace!("Request for {url} is unauthenticated, checking cache");
// Check the cache for a URL match first. This can save us from
// making a failing request
let credentials = self.cache().get_url(request.url(), &Username::none());
if let Some(credentials) = credentials.as_ref() {
request = credentials.authenticate(request).await;
// If it's fully authenticated, finish the request
if credentials.is_authenticated() {
trace!("Request for {url} is fully authenticated");
return self
.complete_request(None, request, extensions, next, auth_policy)
.await;
}
// If we just found a username, we'll make the request then look for password elsewhere
// if it fails
trace!("Found username for {url} in cache, attempting request");
}
credentials
};
let attempt_has_username = credentials
.as_ref()
.is_some_and(|credentials| credentials.username().is_some());
// Determine whether this is a "known" URL.
let is_known_url = self
.pyx_token_store
.as_ref()
.is_some_and(|token_store| token_store.is_known_url(request.url()));
let must_authenticate = self.only_authenticated
|| (match auth_policy {
AuthPolicy::Auto => is_known_url,
AuthPolicy::Always => true,
AuthPolicy::Never => false,
}
// Dependabot intercepts HTTP requests and injects credentials, which means that we
// cannot eagerly enforce an `AuthPolicy` as we don't know whether credentials will be
// added outside of uv.
&& !*IS_DEPENDABOT);
let (mut retry_request, response) = if !must_authenticate {
let url = tracing_url(&request, credentials.as_deref());
if credentials.is_none() {
trace!("Attempting unauthenticated request for {url}");
} else {
trace!("Attempting partially authenticated request for {url}");
}
// <https://github.com/TrueLayer/reqwest-middleware/blob/abdf1844c37092d323683c2396b7eefda1418d3c/reqwest-retry/src/middleware.rs#L141-L149>
// Clone the request so we can retry it on authentication failure
let retry_request = request.try_clone().ok_or_else(|| {
Error::Middleware(anyhow!(
"Request object is not cloneable. Are you passing a streaming body?"
.to_string()
))
})?;
let response = next.clone().run(request, extensions).await?;
// If we don't fail with authorization related codes or
// authentication policy is Never, return the response.
if !matches!(
response.status(),
StatusCode::FORBIDDEN | StatusCode::NOT_FOUND | StatusCode::UNAUTHORIZED
) || matches!(auth_policy, AuthPolicy::Never)
{
return Ok(response);
}
// Otherwise, search for credentials
trace!(
"Request for {url} failed with {}, checking for credentials",
response.status()
);
(retry_request, Some(response))
} else {
// For endpoints where we require the user to provide credentials, we don't try the
// unauthenticated request first.
trace!("Checking for credentials for {url}");
(request, None)
};
let retry_request_url = DisplaySafeUrl::ref_cast(retry_request.url());
let username = credentials
.as_ref()
.map(|credentials| credentials.to_username())
.unwrap_or(Username::none());
let credentials = if let Some(index) = index {
self.cache().get_url(&index.url, &username).or_else(|| {
self.cache()
.get_realm(Realm::from(&**retry_request_url), username)
})
} else {
// Since there is no known index for this URL, check if there are credentials in
// the realm-level cache.
self.cache()
.get_realm(Realm::from(&**retry_request_url), username)
}
.or(credentials);
if let Some(credentials) = credentials.as_ref() {
if credentials.is_authenticated() {
trace!("Retrying request for {url} with credentials from cache {credentials:?}");
retry_request = credentials.authenticate(retry_request).await;
return self
.complete_request(None, retry_request, extensions, next, auth_policy)
.await;
}
}
// Then, fetch from external services.
// Here, we use the username from the cache if present.
if let Some(credentials) = self
.fetch_credentials(
credentials.as_deref(),
retry_request_url,
index,
auth_policy,
)
.await
{
retry_request = credentials.authenticate(retry_request).await;
trace!("Retrying request for {url} with {credentials:?}");
return self
.complete_request(
Some(credentials),
retry_request,
extensions,
next,
auth_policy,
)
.await;
}
if let Some(credentials) = credentials.as_ref() {
if !attempt_has_username {
trace!("Retrying request for {url} with username from cache {credentials:?}");
retry_request = credentials.authenticate(retry_request).await;
return self
.complete_request(None, retry_request, extensions, next, auth_policy)
.await;
}
}
if let Some(response) = response {
Ok(response)
} else if let Some(store) = is_known_url
.then_some(self.pyx_token_store.as_ref())
.flatten()
{
let domain = store
.api()
.domain()
.unwrap_or("pyx.dev")
.trim_start_matches("api.");
Err(Error::Middleware(format_err!(
"Run `{}` to authenticate uv with pyx",
format!("uv auth login {domain}").green()
)))
} else {
Err(Error::Middleware(format_err!(
"Missing credentials for {url}"
)))
}
}
}
impl AuthMiddleware {
/// Run a request to completion.
///
/// If credentials are present, insert them into the cache on success.
async fn complete_request(
&self,
credentials: Option<Arc<Authentication>>,
request: Request,
extensions: &mut Extensions,
next: Next<'_>,
auth_policy: AuthPolicy,
) -> reqwest_middleware::Result<Response> {
let Some(credentials) = credentials else {
// Nothing to insert into the cache if we don't have credentials
return next.run(request, extensions).await;
};
let url = DisplaySafeUrl::from_url(request.url().clone());
if matches!(auth_policy, AuthPolicy::Always) && credentials.password().is_none() {
return Err(Error::Middleware(format_err!("Missing password for {url}")));
}
let result = next.run(request, extensions).await;
// Update the cache with new credentials on a successful request
if result
.as_ref()
.is_ok_and(|response| response.error_for_status_ref().is_ok())
{
// TODO(zanieb): Consider also updating the system keyring after successful use
trace!("Updating cached credentials for {url} to {credentials:?}");
self.cache().insert(&url, credentials);
}
result
}
/// Use known request credentials to complete the request.
async fn complete_request_with_request_credentials(
&self,
credentials: Authentication,
mut request: Request,
extensions: &mut Extensions,
next: Next<'_>,
url: &DisplaySafeUrl,
index: Option<&Index>,
auth_policy: AuthPolicy,
) -> reqwest_middleware::Result<Response> {
let credentials = Arc::new(credentials);
// If there's a password, send the request and cache
if credentials.is_authenticated() {
trace!("Request for {url} already contains username and password");
return self
.complete_request(Some(credentials), request, extensions, next, auth_policy)
.await;
}
trace!("Request for {url} is missing a password, looking for credentials");
// There's just a username, try to find a password.
// If we have an index, check the cache for that URL. Otherwise,
// check for the realm.
let maybe_cached_credentials = if let Some(index) = index {
self.cache()
.get_url(&index.url, credentials.as_username().as_ref())
.or_else(|| {
self.cache()
.get_url(&index.root_url, credentials.as_username().as_ref())
})
} else {
self.cache()
.get_realm(Realm::from(request.url()), credentials.to_username())
};
if let Some(credentials) = maybe_cached_credentials {
request = credentials.authenticate(request).await;
// Do not insert already-cached credentials
let credentials = None;
return self
.complete_request(credentials, request, extensions, next, auth_policy)
.await;
}
let credentials = if let Some(credentials) = self
.cache()
.get_url(request.url(), credentials.as_username().as_ref())
{
request = credentials.authenticate(request).await;
// Do not insert already-cached credentials
None
} else if let Some(credentials) = self
.fetch_credentials(
Some(&credentials),
DisplaySafeUrl::ref_cast(request.url()),
index,
auth_policy,
)
.await
{
request = credentials.authenticate(request).await;
Some(credentials)
} else if index.is_some() {
// If this is a known index, we fall back to checking for the realm.
if let Some(credentials) = self
.cache()
.get_realm(Realm::from(request.url()), credentials.to_username())
{
request = credentials.authenticate(request).await;
Some(credentials)
} else {
Some(credentials)
}
} else {
// If we don't find a password, we'll still attempt the request with the existing credentials
Some(credentials)
};
self.complete_request(credentials, request, extensions, next, auth_policy)
.await
}
/// Fetch credentials for a URL.
///
/// Supports netrc file and keyring lookups.
async fn fetch_credentials(
&self,
credentials: Option<&Authentication>,
url: &DisplaySafeUrl,
index: Option<&Index>,
auth_policy: AuthPolicy,
) -> Option<Arc<Authentication>> {
let username = Username::from(
credentials.map(|credentials| credentials.username().unwrap_or_default().to_string()),
);
// Fetches can be expensive, so we will only run them _once_ per realm or index URL and username combination
// All other requests for the same realm or index URL will wait until the first one completes
let key = if let Some(index) = index {
(FetchUrl::Index(index.url.clone()), username)
} else {
(FetchUrl::Realm(Realm::from(&**url)), username)
};
if !self.cache().fetches.register(key.clone()) {
let credentials = self
.cache()
.fetches
.wait(&key)
.await
.expect("The key must exist after register is called");
if credentials.is_some() {
trace!("Using credentials from previous fetch for {}", key.0);
} else {
trace!(
"Skipping fetch of credentials for {}, previous attempt failed",
key.0
);
}
return credentials;
}
// Support for known providers, like Hugging Face and S3.
if let Some(credentials) = HuggingFaceProvider::credentials_for(url)
.map(Authentication::from)
.map(Arc::new)
{
debug!("Found Hugging Face credentials for {url}");
self.cache().fetches.done(key, Some(credentials.clone()));
return Some(credentials);
}
if S3EndpointProvider::is_s3_endpoint(url, self.preview) {
let mut s3_state = self.s3_credential_state.lock().await;
// If the S3 credential state is uninitialized, initialize it.
let credentials = match &*s3_state {
S3CredentialState::Uninitialized => {
trace!("Initializing S3 credentials for {url}");
let signer = S3EndpointProvider::create_signer();
let credentials = Arc::new(Authentication::from(signer));
*s3_state = S3CredentialState::Initialized(Some(credentials.clone()));
Some(credentials)
}
S3CredentialState::Initialized(credentials) => credentials.clone(),
};
if let Some(credentials) = credentials {
debug!("Found S3 credentials for {url}");
self.cache().fetches.done(key, Some(credentials.clone()));
return Some(credentials);
}
}
// If this is a known URL, authenticate it via the token store.
if let Some(base_client) = self.base_client.as_ref() {
if let Some(token_store) = self.pyx_token_store.as_ref() {
if token_store.is_known_url(url) {
let mut token_state = self.pyx_token_state.lock().await;
// If the token store is uninitialized, initialize it.
let token = match *token_state {
TokenState::Uninitialized => {
trace!("Initializing token store for {url}");
let generated = match token_store
.access_token(base_client, DEFAULT_TOLERANCE_SECS)
.await
{
Ok(Some(token)) => Some(token),
Ok(None) => None,
Err(err) => {
warn!("Failed to generate access tokens: {err}");
None
}
};
*token_state = TokenState::Initialized(generated.clone());
generated
}
TokenState::Initialized(ref tokens) => tokens.clone(),
};
let credentials = token.map(|token| {
trace!("Using credentials from token store for {url}");
Arc::new(Authentication::from(Credentials::from(token)))
});
// Register the fetch for this key
self.cache().fetches.done(key.clone(), credentials.clone());
return credentials;
}
}
}
// Netrc support based on: <https://github.com/gribouille/netrc>.
let credentials = if let Some(credentials) = self.netrc.get().and_then(|netrc| {
debug!("Checking netrc for credentials for {url}");
Credentials::from_netrc(
netrc,
url,
credentials
.as_ref()
.and_then(|credentials| credentials.username()),
)
}) {
debug!("Found credentials in netrc file for {url}");
Some(credentials)
// Text credential store support.
} else if let Some(credentials) = self.text_store.get().await.and_then(|text_store| {
debug!("Checking text store for credentials for {url}");
text_store
.get_credentials(
url,
credentials
.as_ref()
.and_then(|credentials| credentials.username()),
)
.cloned()
}) {
debug!("Found credentials in plaintext store for {url}");
Some(credentials)
} else if let Some(credentials) = {
if self.preview.is_enabled(PreviewFeatures::NATIVE_AUTH) {
let native_store = KeyringProvider::native();
let username = credentials.and_then(|credentials| credentials.username());
let display_username = if let Some(username) = username {
format!("{username}@")
} else {
String::new()
};
if let Some(index) = index {
// N.B. The native store performs an exact look up right now, so we use the root
// URL of the index instead of relying on prefix-matching.
debug!(
"Checking native store for credentials for index URL {}{}",
display_username, index.root_url
);
native_store.fetch(&index.root_url, username).await
} else {
debug!(
"Checking native store for credentials for URL {}{}",
display_username, url
);
native_store.fetch(url, username).await
}
// TODO(zanieb): We should have a realm fallback here too
} else {
None
}
} {
debug!("Found credentials in native store for {url}");
Some(credentials)
// N.B. The keyring provider performs lookups for the exact URL then falls back to the host.
// But, in the absence of an index URL, we cache the result per realm. So in that case,
// if a keyring implementation returns different credentials for different URLs in the
// same realm we will use the wrong credentials.
} else if let Some(credentials) = match self.keyring {
Some(ref keyring) => {
// The subprocess keyring provider is _slow_ so we do not perform fetches for all
// URLs; instead, we fetch if there's a username or if the user has requested to
// always authenticate.
if let Some(username) = credentials.and_then(|credentials| credentials.username()) {
if let Some(index) = index {
debug!(
"Checking keyring for credentials for index URL {}@{}",
username, index.url
);
keyring
.fetch(DisplaySafeUrl::ref_cast(&index.url), Some(username))
.await
} else {
debug!(
"Checking keyring for credentials for full URL {}@{}",
username, url
);
keyring.fetch(url, Some(username)).await
}
| 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-auth/src/service.rs | crates/uv-auth/src/service.rs | use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;
use url::Url;
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
#[derive(Error, Debug)]
pub enum ServiceParseError {
#[error(transparent)]
InvalidUrl(#[from] DisplaySafeUrlError),
#[error("Unsupported scheme: {0}")]
UnsupportedScheme(String),
#[error("HTTPS is required for non-local hosts")]
HttpsRequired,
}
/// A service URL that wraps [`DisplaySafeUrl`] for CLI usage.
///
/// This type provides automatic URL parsing and validation when used as a CLI argument,
/// eliminating the need for manual parsing in command functions.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct Service(DisplaySafeUrl);
impl Service {
/// Get the underlying [`DisplaySafeUrl`].
pub fn url(&self) -> &DisplaySafeUrl {
&self.0
}
/// Convert into the underlying [`DisplaySafeUrl`].
pub fn into_url(self) -> DisplaySafeUrl {
self.0
}
/// Validate that the URL scheme is supported.
fn check_scheme(url: &Url) -> Result<(), ServiceParseError> {
match url.scheme() {
"https" => Ok(()),
"http" if matches!(url.host_str(), Some("localhost" | "127.0.0.1")) => Ok(()),
"http" => Err(ServiceParseError::HttpsRequired),
value => Err(ServiceParseError::UnsupportedScheme(value.to_string())),
}
}
}
impl FromStr for Service {
type Err = ServiceParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// First try parsing as-is
let url = match DisplaySafeUrl::parse(s) {
Ok(url) => url,
Err(DisplaySafeUrlError::Url(url::ParseError::RelativeUrlWithoutBase)) => {
// If it's a relative URL, try prepending https://
let with_https = format!("https://{s}");
DisplaySafeUrl::parse(&with_https)?
}
Err(err) => return Err(err.into()),
};
Self::check_scheme(&url)?;
Ok(Self(url))
}
}
impl std::fmt::Display for Service {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl TryFrom<String> for Service {
type Error = ServiceParseError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
}
}
impl From<Service> for String {
fn from(service: Service) -> Self {
service.to_string()
}
}
impl TryFrom<DisplaySafeUrl> for Service {
type Error = ServiceParseError;
fn try_from(value: DisplaySafeUrl) -> Result<Self, Self::Error> {
Self::check_scheme(&value)?;
Ok(Self(value))
}
}
| 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-auth/src/realm.rs | crates/uv-auth/src/realm.rs | use std::hash::{Hash, Hasher};
use std::{fmt::Display, fmt::Formatter};
use url::Url;
use uv_redacted::DisplaySafeUrl;
use uv_small_str::SmallString;
/// Used to determine if authentication information should be retained on a new URL.
/// Based on the specification defined in RFC 7235 and 7230.
///
/// <https://datatracker.ietf.org/doc/html/rfc7235#section-2.2>
/// <https://datatracker.ietf.org/doc/html/rfc7230#section-5.5>
//
// The "scheme" and "authority" components must match to retain authentication
// The "authority", is composed of the host and port.
//
// The scheme must always be an exact match.
// Note some clients such as Python's `requests` library allow an upgrade
// from `http` to `https` but this is not spec-compliant.
// <https://github.com/pypa/pip/blob/75f54cae9271179b8cc80435f92336c97e349f9d/src/pip/_vendor/requests/sessions.py#L133-L136>
//
// The host must always be an exact match.
//
// The port is only allowed to differ if it matches the "default port" for the scheme.
// However, `url` (and therefore `reqwest`) sets the `port` to `None` if it matches the default port
// so we do not need any special handling here.
#[derive(Debug, Clone)]
pub struct Realm {
scheme: SmallString,
host: Option<SmallString>,
port: Option<u16>,
}
impl From<&DisplaySafeUrl> for Realm {
fn from(url: &DisplaySafeUrl) -> Self {
Self::from(&**url)
}
}
impl From<&Url> for Realm {
fn from(url: &Url) -> Self {
Self {
scheme: SmallString::from(url.scheme()),
host: url.host_str().map(SmallString::from),
port: url.port(),
}
}
}
impl Display for Realm {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(port) = self.port {
write!(
f,
"{}://{}:{port}",
self.scheme,
self.host.as_deref().unwrap_or_default()
)
} else {
write!(
f,
"{}://{}",
self.scheme,
self.host.as_deref().unwrap_or_default()
)
}
}
}
impl PartialEq for Realm {
fn eq(&self, other: &Self) -> bool {
RealmRef::from(self) == RealmRef::from(other)
}
}
impl Eq for Realm {}
impl Hash for Realm {
fn hash<H: Hasher>(&self, state: &mut H) {
RealmRef::from(self).hash(state);
}
}
/// A reference to a [`Realm`] that can be used for zero-allocation comparisons.
#[derive(Debug, Copy, Clone)]
pub struct RealmRef<'a> {
scheme: &'a str,
host: Option<&'a str>,
port: Option<u16>,
}
impl RealmRef<'_> {
/// Returns true if this realm is a subdomain of the other realm.
pub(crate) fn is_subdomain_of(&self, other: Self) -> bool {
other.scheme == self.scheme
&& other.port == self.port
&& other.host.is_some_and(|other_host| {
self.host.is_some_and(|self_host| {
self_host
.strip_suffix(other_host)
.is_some_and(|prefix| prefix.ends_with('.'))
})
})
}
}
impl<'a> From<&'a Url> for RealmRef<'a> {
fn from(url: &'a Url) -> Self {
Self {
scheme: url.scheme(),
host: url.host_str(),
port: url.port(),
}
}
}
impl PartialEq for RealmRef<'_> {
fn eq(&self, other: &Self) -> bool {
self.scheme == other.scheme && self.host == other.host && self.port == other.port
}
}
impl Eq for RealmRef<'_> {}
impl Hash for RealmRef<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.scheme.hash(state);
self.host.hash(state);
self.port.hash(state);
}
}
impl<'a> PartialEq<RealmRef<'a>> for Realm {
fn eq(&self, rhs: &RealmRef<'a>) -> bool {
RealmRef::from(self) == *rhs
}
}
impl PartialEq<Realm> for RealmRef<'_> {
fn eq(&self, rhs: &Realm) -> bool {
*self == RealmRef::from(rhs)
}
}
impl<'a> From<&'a Realm> for RealmRef<'a> {
fn from(realm: &'a Realm) -> Self {
Self {
scheme: &realm.scheme,
host: realm.host.as_deref(),
port: realm.port,
}
}
}
#[cfg(test)]
mod tests {
use url::{ParseError, Url};
use crate::Realm;
#[test]
fn test_should_retain_auth() -> Result<(), ParseError> {
// Exact match (https)
assert_eq!(
Realm::from(&Url::parse("https://example.com")?),
Realm::from(&Url::parse("https://example.com")?)
);
// Exact match (with port)
assert_eq!(
Realm::from(&Url::parse("https://example.com:1234")?),
Realm::from(&Url::parse("https://example.com:1234")?)
);
// Exact match (http)
assert_eq!(
Realm::from(&Url::parse("http://example.com")?),
Realm::from(&Url::parse("http://example.com")?)
);
// Okay, path differs
assert_eq!(
Realm::from(&Url::parse("http://example.com/foo")?),
Realm::from(&Url::parse("http://example.com/bar")?)
);
// Okay, default port differs (https)
assert_eq!(
Realm::from(&Url::parse("https://example.com:443")?),
Realm::from(&Url::parse("https://example.com")?)
);
// Okay, default port differs (http)
assert_eq!(
Realm::from(&Url::parse("http://example.com:80")?),
Realm::from(&Url::parse("http://example.com")?)
);
// Mismatched scheme
assert_ne!(
Realm::from(&Url::parse("https://example.com")?),
Realm::from(&Url::parse("http://example.com")?)
);
// Mismatched scheme, we explicitly do not allow upgrade to https
assert_ne!(
Realm::from(&Url::parse("http://example.com")?),
Realm::from(&Url::parse("https://example.com")?)
);
// Mismatched host
assert_ne!(
Realm::from(&Url::parse("https://foo.com")?),
Realm::from(&Url::parse("https://bar.com")?)
);
// Mismatched port
assert_ne!(
Realm::from(&Url::parse("https://example.com:1234")?),
Realm::from(&Url::parse("https://example.com:5678")?)
);
// Mismatched port, with one as default for scheme
assert_ne!(
Realm::from(&Url::parse("https://example.com:443")?),
Realm::from(&Url::parse("https://example.com:5678")?)
);
assert_ne!(
Realm::from(&Url::parse("https://example.com:1234")?),
Realm::from(&Url::parse("https://example.com:443")?)
);
// Mismatched port, with default for a different scheme
assert_ne!(
Realm::from(&Url::parse("https://example.com:80")?),
Realm::from(&Url::parse("https://example.com")?)
);
Ok(())
}
#[test]
fn test_is_subdomain_of() -> Result<(), ParseError> {
use crate::realm::RealmRef;
// Subdomain relationship: sub.example.com is a subdomain of example.com
let subdomain_url = Url::parse("https://sub.example.com")?;
let domain_url = Url::parse("https://example.com")?;
let subdomain = RealmRef::from(&subdomain_url);
let domain = RealmRef::from(&domain_url);
assert!(subdomain.is_subdomain_of(domain));
// Deeper subdomain: foo.bar.example.com is a subdomain of example.com
let deep_subdomain_url = Url::parse("https://foo.bar.example.com")?;
let deep_subdomain = RealmRef::from(&deep_subdomain_url);
assert!(deep_subdomain.is_subdomain_of(domain));
// Deeper subdomain: foo.bar.example.com is also a subdomain of bar.example.com
let parent_subdomain_url = Url::parse("https://bar.example.com")?;
let parent_subdomain = RealmRef::from(&parent_subdomain_url);
assert!(deep_subdomain.is_subdomain_of(parent_subdomain));
// Not a subdomain: example.com is not a subdomain of sub.example.com
assert!(!domain.is_subdomain_of(subdomain));
// Same domain is not a subdomain of itself
assert!(!domain.is_subdomain_of(domain));
// Different TLD: example.org is not a subdomain of example.com
let different_tld_url = Url::parse("https://example.org")?;
let different_tld = RealmRef::from(&different_tld_url);
assert!(!different_tld.is_subdomain_of(domain));
// Partial match but not a subdomain: notexample.com is not a subdomain of example.com
let partial_match_url = Url::parse("https://notexample.com")?;
let partial_match = RealmRef::from(&partial_match_url);
assert!(!partial_match.is_subdomain_of(domain));
// Different scheme: http subdomain is not a subdomain of https domain
let http_subdomain_url = Url::parse("http://sub.example.com")?;
let https_domain_url = Url::parse("https://example.com")?;
let http_subdomain = RealmRef::from(&http_subdomain_url);
let https_domain = RealmRef::from(&https_domain_url);
assert!(!http_subdomain.is_subdomain_of(https_domain));
// Different port: same subdomain with different port is not a subdomain
let subdomain_port_8080_url = Url::parse("https://sub.example.com:8080")?;
let domain_port_9090_url = Url::parse("https://example.com:9090")?;
let subdomain_port_8080 = RealmRef::from(&subdomain_port_8080_url);
let domain_port_9090 = RealmRef::from(&domain_port_9090_url);
assert!(!subdomain_port_8080.is_subdomain_of(domain_port_9090));
// Same port: subdomain with same explicit port is a subdomain
let subdomain_with_port_url = Url::parse("https://sub.example.com:8080")?;
let domain_with_port_url = Url::parse("https://example.com:8080")?;
let subdomain_with_port = RealmRef::from(&subdomain_with_port_url);
let domain_with_port = RealmRef::from(&domain_with_port_url);
assert!(subdomain_with_port.is_subdomain_of(domain_with_port));
// Default port handling: subdomain with implicit port is a subdomain
let subdomain_default_url = Url::parse("https://sub.example.com")?;
let domain_explicit_443_url = Url::parse("https://example.com:443")?;
let subdomain_default = RealmRef::from(&subdomain_default_url);
let domain_explicit_443 = RealmRef::from(&domain_explicit_443_url);
assert!(subdomain_default.is_subdomain_of(domain_explicit_443));
// Edge case: empty host (shouldn't happen with valid URLs but testing defensive code)
let file_url = Url::parse("file:///path/to/file")?;
let https_url = Url::parse("https://example.com")?;
let file_realm = RealmRef::from(&file_url);
let https_realm = RealmRef::from(&https_url);
assert!(!file_realm.is_subdomain_of(https_realm));
assert!(!https_realm.is_subdomain_of(file_realm));
// Subdomain with path (path should be ignored)
let subdomain_with_path_url = Url::parse("https://sub.example.com/path")?;
let domain_with_path_url = Url::parse("https://example.com/other")?;
let subdomain_with_path = RealmRef::from(&subdomain_with_path_url);
let domain_with_path = RealmRef::from(&domain_with_path_url);
assert!(subdomain_with_path.is_subdomain_of(domain_with_path));
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-auth/src/credentials.rs | crates/uv-auth/src/credentials.rs | use std::borrow::Cow;
use std::fmt;
use std::io::Read;
use std::io::Write;
use std::str::FromStr;
use base64::prelude::BASE64_STANDARD;
use base64::read::DecoderReader;
use base64::write::EncoderWriter;
use http::Uri;
use netrc::Netrc;
use reqsign::aws::DefaultSigner;
use reqwest::Request;
use reqwest::header::HeaderValue;
use serde::{Deserialize, Serialize};
use url::Url;
use uv_redacted::DisplaySafeUrl;
use uv_static::EnvVars;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Credentials {
/// RFC 7617 HTTP Basic Authentication
Basic {
/// The username to use for authentication.
username: Username,
/// The password to use for authentication.
password: Option<Password>,
},
/// RFC 6750 Bearer Token Authentication
Bearer {
/// The token to use for authentication.
token: Token,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Username(Option<String>);
impl Username {
/// Create a new username.
///
/// Unlike `reqwest`, empty usernames are be encoded as `None` instead of an empty string.
pub(crate) fn new(value: Option<String>) -> Self {
// Ensure empty strings are `None`
Self(value.filter(|s| !s.is_empty()))
}
pub(crate) fn none() -> Self {
Self::new(None)
}
pub(crate) fn is_none(&self) -> bool {
self.0.is_none()
}
pub(crate) fn is_some(&self) -> bool {
self.0.is_some()
}
pub(crate) fn as_deref(&self) -> Option<&str> {
self.0.as_deref()
}
}
impl From<String> for Username {
fn from(value: String) -> Self {
Self::new(Some(value))
}
}
impl From<Option<String>> for Username {
fn from(value: Option<String>) -> Self {
Self::new(value)
}
}
#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Password(String);
impl Password {
pub fn new(password: String) -> Self {
Self(password)
}
/// Return the [`Password`] as a string slice.
pub fn as_str(&self) -> &str {
self.0.as_str()
}
/// Convert the [`Password`] into its underlying [`String`].
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Debug for Password {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "****")
}
}
#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Default, Deserialize)]
#[serde(transparent)]
pub struct Token(Vec<u8>);
impl Token {
pub fn new(token: Vec<u8>) -> Self {
Self(token)
}
/// Return the [`Token`] as a byte slice.
pub fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}
/// Convert the [`Token`] into its underlying [`Vec<u8>`].
pub fn into_bytes(self) -> Vec<u8> {
self.0
}
/// Return whether the [`Token`] is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "****")
}
}
impl Credentials {
/// Create a set of HTTP Basic Authentication credentials.
#[allow(dead_code)]
pub fn basic(username: Option<String>, password: Option<String>) -> Self {
Self::Basic {
username: Username::new(username),
password: password.map(Password),
}
}
/// Create a set of Bearer Authentication credentials.
#[allow(dead_code)]
pub fn bearer(token: Vec<u8>) -> Self {
Self::Bearer {
token: Token::new(token),
}
}
pub fn username(&self) -> Option<&str> {
match self {
Self::Basic { username, .. } => username.as_deref(),
Self::Bearer { .. } => None,
}
}
pub(crate) fn to_username(&self) -> Username {
match self {
Self::Basic { username, .. } => username.clone(),
Self::Bearer { .. } => Username::none(),
}
}
pub(crate) fn as_username(&self) -> Cow<'_, Username> {
match self {
Self::Basic { username, .. } => Cow::Borrowed(username),
Self::Bearer { .. } => Cow::Owned(Username::none()),
}
}
pub fn password(&self) -> Option<&str> {
match self {
Self::Basic { password, .. } => password.as_ref().map(Password::as_str),
Self::Bearer { .. } => None,
}
}
pub fn is_authenticated(&self) -> bool {
match self {
Self::Basic {
username: _,
password,
} => password.is_some(),
Self::Bearer { token } => !token.is_empty(),
}
}
pub(crate) fn is_empty(&self) -> bool {
match self {
Self::Basic { username, password } => username.is_none() && password.is_none(),
Self::Bearer { token } => token.is_empty(),
}
}
/// Return [`Credentials`] for a [`Url`] from a [`Netrc`] file, if any.
///
/// If a username is provided, it must match the login in the netrc file or [`None`] is returned.
pub(crate) fn from_netrc(
netrc: &Netrc,
url: &DisplaySafeUrl,
username: Option<&str>,
) -> Option<Self> {
let host = url.host_str()?;
let entry = netrc
.hosts
.get(host)
.or_else(|| netrc.hosts.get("default"))?;
// Ensure the username matches if provided
if username.is_some_and(|username| username != entry.login) {
return None;
}
Some(Self::Basic {
username: Username::new(Some(entry.login.clone())),
password: Some(Password(entry.password.clone())),
})
}
/// Parse [`Credentials`] from a URL, if any.
///
/// Returns [`None`] if both [`Url::username`] and [`Url::password`] are not populated.
pub fn from_url(url: &Url) -> Option<Self> {
if url.username().is_empty() && url.password().is_none() {
return None;
}
Some(Self::Basic {
// Remove percent-encoding from URL credentials
// See <https://github.com/pypa/pip/blob/06d21db4ff1ab69665c22a88718a4ea9757ca293/src/pip/_internal/utils/misc.py#L497-L499>
username: if url.username().is_empty() {
None
} else {
Some(
percent_encoding::percent_decode_str(url.username())
.decode_utf8()
.expect("An encoded username should always decode")
.into_owned(),
)
}
.into(),
password: url.password().map(|password| {
Password(
percent_encoding::percent_decode_str(password)
.decode_utf8()
.expect("An encoded password should always decode")
.into_owned(),
)
}),
})
}
/// Extract the [`Credentials`] from the environment, given a named source.
///
/// For example, given a name of `"pytorch"`, search for `UV_INDEX_PYTORCH_USERNAME` and
/// `UV_INDEX_PYTORCH_PASSWORD`.
pub fn from_env(name: impl AsRef<str>) -> Option<Self> {
let username = std::env::var(EnvVars::index_username(name.as_ref())).ok();
let password = std::env::var(EnvVars::index_password(name.as_ref())).ok();
if username.is_none() && password.is_none() {
None
} else {
Some(Self::basic(username, password))
}
}
/// Parse [`Credentials`] from an HTTP request, if any.
///
/// Only HTTP Basic Authentication is supported.
pub(crate) fn from_request(request: &Request) -> Option<Self> {
// First, attempt to retrieve the credentials from the URL
Self::from_url(request.url()).or(
// Then, attempt to pull the credentials from the headers
request
.headers()
.get(reqwest::header::AUTHORIZATION)
.map(Self::from_header_value)?,
)
}
/// Parse [`Credentials`] from an authorization header, if any.
///
/// HTTP Basic and Bearer Authentication are both supported.
/// [`None`] will be returned if another authorization scheme is detected.
///
/// Panics if the authentication is not conformant to the HTTP Basic Authentication scheme:
/// - The contents must be base64 encoded
/// - There must be a `:` separator
pub(crate) fn from_header_value(header: &HeaderValue) -> Option<Self> {
// Parse a `Basic` authentication header.
if let Some(mut value) = header.as_bytes().strip_prefix(b"Basic ") {
let mut decoder = DecoderReader::new(&mut value, &BASE64_STANDARD);
let mut buf = String::new();
decoder
.read_to_string(&mut buf)
.expect("HTTP Basic Authentication should be base64 encoded");
let (username, password) = buf
.split_once(':')
.expect("HTTP Basic Authentication should include a `:` separator");
let username = if username.is_empty() {
None
} else {
Some(username.to_string())
};
let password = if password.is_empty() {
None
} else {
Some(password.to_string())
};
return Some(Self::Basic {
username: Username::new(username),
password: password.map(Password),
});
}
// Parse a `Bearer` authentication header.
if let Some(token) = header.as_bytes().strip_prefix(b"Bearer ") {
return Some(Self::Bearer {
token: Token::new(token.to_vec()),
});
}
None
}
/// Create an HTTP Basic Authentication header for the credentials.
///
/// Panics if the username or password cannot be base64 encoded.
pub fn to_header_value(&self) -> HeaderValue {
match self {
Self::Basic { .. } => {
// See: <https://github.com/seanmonstar/reqwest/blob/2c11ef000b151c2eebeed2c18a7b81042220c6b0/src/util.rs#L3>
let mut buf = b"Basic ".to_vec();
{
let mut encoder = EncoderWriter::new(&mut buf, &BASE64_STANDARD);
write!(encoder, "{}:", self.username().unwrap_or_default())
.expect("Write to base64 encoder should succeed");
if let Some(password) = self.password() {
write!(encoder, "{password}")
.expect("Write to base64 encoder should succeed");
}
}
let mut header =
HeaderValue::from_bytes(&buf).expect("base64 is always valid HeaderValue");
header.set_sensitive(true);
header
}
Self::Bearer { token } => {
let mut header = HeaderValue::from_bytes(&[b"Bearer ", token.as_slice()].concat())
.expect("Bearer token is always valid HeaderValue");
header.set_sensitive(true);
header
}
}
}
/// Apply the credentials to the given URL.
///
/// Any existing credentials will be overridden.
#[must_use]
pub fn apply(&self, mut url: DisplaySafeUrl) -> DisplaySafeUrl {
if let Some(username) = self.username() {
let _ = url.set_username(username);
}
if let Some(password) = self.password() {
let _ = url.set_password(Some(password));
}
url
}
/// Attach the credentials to the given request.
///
/// Any existing credentials will be overridden.
#[must_use]
pub fn authenticate(&self, mut request: Request) -> Request {
request
.headers_mut()
.insert(reqwest::header::AUTHORIZATION, Self::to_header_value(self));
request
}
}
#[derive(Clone, Debug)]
pub(crate) enum Authentication {
/// HTTP Basic or Bearer Authentication credentials.
Credentials(Credentials),
/// AWS Signature Version 4 signing.
Signer(DefaultSigner),
}
impl PartialEq for Authentication {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Credentials(a), Self::Credentials(b)) => a == b,
(Self::Signer(..), Self::Signer(..)) => true,
_ => false,
}
}
}
impl Eq for Authentication {}
impl From<Credentials> for Authentication {
fn from(credentials: Credentials) -> Self {
Self::Credentials(credentials)
}
}
impl From<DefaultSigner> for Authentication {
fn from(signer: DefaultSigner) -> Self {
Self::Signer(signer)
}
}
impl Authentication {
/// Return the password used for authentication, if any.
pub(crate) fn password(&self) -> Option<&str> {
match self {
Self::Credentials(credentials) => credentials.password(),
Self::Signer(..) => None,
}
}
/// Return the username used for authentication, if any.
pub(crate) fn username(&self) -> Option<&str> {
match self {
Self::Credentials(credentials) => credentials.username(),
Self::Signer(..) => None,
}
}
/// Return the username used for authentication, if any.
pub(crate) fn as_username(&self) -> Cow<'_, Username> {
match self {
Self::Credentials(credentials) => credentials.as_username(),
Self::Signer(..) => Cow::Owned(Username::none()),
}
}
/// Return the username used for authentication, if any.
pub(crate) fn to_username(&self) -> Username {
match self {
Self::Credentials(credentials) => credentials.to_username(),
Self::Signer(..) => Username::none(),
}
}
/// Return `true` if the object contains a means of authenticating.
pub(crate) fn is_authenticated(&self) -> bool {
match self {
Self::Credentials(credentials) => credentials.is_authenticated(),
Self::Signer(..) => true,
}
}
/// Return `true` if the object contains no credentials.
pub(crate) fn is_empty(&self) -> bool {
match self {
Self::Credentials(credentials) => credentials.is_empty(),
Self::Signer(..) => false,
}
}
/// Apply the authentication to the given request.
///
/// Any existing credentials will be overridden.
#[must_use]
pub(crate) async fn authenticate(&self, mut request: Request) -> Request {
match self {
Self::Credentials(credentials) => credentials.authenticate(request),
Self::Signer(signer) => {
// Build an `http::Request` from the `reqwest::Request`.
// SAFETY: If we have a valid `reqwest::Request`, we expect (e.g.) the URL to be valid.
let uri = Uri::from_str(request.url().as_str()).unwrap();
let mut http_req = http::Request::builder()
.method(request.method().clone())
.uri(uri)
.body(())
.unwrap();
*http_req.headers_mut() = request.headers().clone();
// Sign the parts.
let (mut parts, ()) = http_req.into_parts();
signer
.sign(&mut parts, None)
.await
.expect("AWS signing should succeed");
// Copy over the signed headers.
request.headers_mut().extend(parts.headers);
// Copy over the signed path and query, if any.
if let Some(path_and_query) = parts.uri.path_and_query() {
request.url_mut().set_path(path_and_query.path());
request.url_mut().set_query(path_and_query.query());
}
request
}
}
}
}
#[cfg(test)]
mod tests {
use insta::assert_debug_snapshot;
use super::*;
#[test]
fn from_url_no_credentials() {
let url = &Url::parse("https://example.com/simple/first/").unwrap();
assert_eq!(Credentials::from_url(url), None);
}
#[test]
fn from_url_username_and_password() {
let url = &Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_username("user").unwrap();
auth_url.set_password(Some("password")).unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
assert_eq!(credentials.username(), Some("user"));
assert_eq!(credentials.password(), Some("password"));
}
#[test]
fn from_url_no_username() {
let url = &Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_password(Some("password")).unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
assert_eq!(credentials.username(), None);
assert_eq!(credentials.password(), Some("password"));
}
#[test]
fn from_url_no_password() {
let url = &Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_username("user").unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
assert_eq!(credentials.username(), Some("user"));
assert_eq!(credentials.password(), None);
}
#[test]
fn authenticated_request_from_url() {
let url = Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_username("user").unwrap();
auth_url.set_password(Some("password")).unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
let mut request = Request::new(reqwest::Method::GET, url);
request = credentials.authenticate(request);
let mut header = request
.headers()
.get(reqwest::header::AUTHORIZATION)
.expect("Authorization header should be set")
.clone();
header.set_sensitive(false);
assert_debug_snapshot!(header, @r###""Basic dXNlcjpwYXNzd29yZA==""###);
assert_eq!(Credentials::from_header_value(&header), Some(credentials));
}
#[test]
fn authenticated_request_from_url_with_percent_encoded_user() {
let url = Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_username("user@domain").unwrap();
auth_url.set_password(Some("password")).unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
let mut request = Request::new(reqwest::Method::GET, url);
request = credentials.authenticate(request);
let mut header = request
.headers()
.get(reqwest::header::AUTHORIZATION)
.expect("Authorization header should be set")
.clone();
header.set_sensitive(false);
assert_debug_snapshot!(header, @r###""Basic dXNlckBkb21haW46cGFzc3dvcmQ=""###);
assert_eq!(Credentials::from_header_value(&header), Some(credentials));
}
#[test]
fn authenticated_request_from_url_with_percent_encoded_password() {
let url = Url::parse("https://example.com/simple/first/").unwrap();
let mut auth_url = url.clone();
auth_url.set_username("user").unwrap();
auth_url.set_password(Some("password==")).unwrap();
let credentials = Credentials::from_url(&auth_url).unwrap();
let mut request = Request::new(reqwest::Method::GET, url);
request = credentials.authenticate(request);
let mut header = request
.headers()
.get(reqwest::header::AUTHORIZATION)
.expect("Authorization header should be set")
.clone();
header.set_sensitive(false);
assert_debug_snapshot!(header, @r###""Basic dXNlcjpwYXNzd29yZD09""###);
assert_eq!(Credentials::from_header_value(&header), Some(credentials));
}
// Test that we don't include the password in debug messages.
#[test]
fn test_password_obfuscation() {
let credentials =
Credentials::basic(Some(String::from("user")), Some(String::from("password")));
let debugged = format!("{credentials:?}");
assert_eq!(
debugged,
"Basic { username: Username(Some(\"user\")), password: Some(****) }"
);
}
#[test]
fn test_bearer_token_obfuscation() {
let token = "super_secret_token";
let credentials = Credentials::bearer(token.into());
let debugged = format!("{credentials:?}");
assert!(
!debugged.contains(token),
"Token should be obfuscated in Debug impl: {debugged}"
);
}
}
| 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-auth/src/keyring.rs | crates/uv-auth/src/keyring.rs | use std::{io::Write, process::Stdio};
use tokio::process::Command;
use tracing::{debug, instrument, trace, warn};
use uv_redacted::DisplaySafeUrl;
use uv_warnings::warn_user_once;
use crate::credentials::Credentials;
/// Service name prefix for storing credentials in a keyring.
static UV_SERVICE_PREFIX: &str = "uv:";
/// A backend for retrieving credentials from a keyring.
///
/// See pip's implementation for reference
/// <https://github.com/pypa/pip/blob/ae5fff36b0aad6e5e0037884927eaa29163c0611/src/pip/_internal/network/auth.py#L102>
#[derive(Debug)]
pub struct KeyringProvider {
backend: KeyringProviderBackend,
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Keyring(#[from] uv_keyring::Error),
#[error("The '{0}' keyring provider does not support storing credentials")]
StoreUnsupported(KeyringProviderBackend),
#[error("The '{0}' keyring provider does not support removing credentials")]
RemoveUnsupported(KeyringProviderBackend),
}
#[derive(Debug, Clone)]
pub enum KeyringProviderBackend {
/// Use a native system keyring integration for credentials.
Native,
/// Use the external `keyring` command for credentials.
Subprocess,
#[cfg(test)]
Dummy(Vec<(String, &'static str, &'static str)>),
}
impl std::fmt::Display for KeyringProviderBackend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Native => write!(f, "native"),
Self::Subprocess => write!(f, "subprocess"),
#[cfg(test)]
Self::Dummy(_) => write!(f, "dummy"),
}
}
}
impl KeyringProvider {
/// Create a new [`KeyringProvider::Native`].
pub fn native() -> Self {
Self {
backend: KeyringProviderBackend::Native,
}
}
/// Create a new [`KeyringProvider::Subprocess`].
pub fn subprocess() -> Self {
Self {
backend: KeyringProviderBackend::Subprocess,
}
}
/// Store credentials for the given [`DisplaySafeUrl`] to the keyring.
///
/// Only [`KeyringProviderBackend::Native`] is supported at this time.
#[instrument(skip_all, fields(url = % url.to_string(), username))]
pub async fn store(
&self,
url: &DisplaySafeUrl,
credentials: &Credentials,
) -> Result<bool, Error> {
let Some(username) = credentials.username() else {
trace!("Unable to store credentials in keyring for {url} due to missing username");
return Ok(false);
};
let Some(password) = credentials.password() else {
trace!("Unable to store credentials in keyring for {url} due to missing password");
return Ok(false);
};
// Ensure we strip credentials from the URL before storing
let url = url.without_credentials();
// If there's no path, we'll perform a host-level login
let target = if let Some(host) = url.host_str().filter(|_| !url.path().is_empty()) {
let mut target = String::new();
if url.scheme() != "https" {
target.push_str(url.scheme());
target.push_str("://");
}
target.push_str(host);
if let Some(port) = url.port() {
target.push(':');
target.push_str(&port.to_string());
}
target
} else {
url.to_string()
};
match &self.backend {
KeyringProviderBackend::Native => {
self.store_native(&target, username, password).await?;
Ok(true)
}
KeyringProviderBackend::Subprocess => {
Err(Error::StoreUnsupported(self.backend.clone()))
}
#[cfg(test)]
KeyringProviderBackend::Dummy(_) => Err(Error::StoreUnsupported(self.backend.clone())),
}
}
/// Store credentials to the system keyring.
#[instrument(skip(self))]
async fn store_native(
&self,
service: &str,
username: &str,
password: &str,
) -> Result<(), Error> {
let prefixed_service = format!("{UV_SERVICE_PREFIX}{service}");
let entry = uv_keyring::Entry::new(&prefixed_service, username)?;
entry.set_password(password).await?;
Ok(())
}
/// Remove credentials for the given [`DisplaySafeUrl`] and username from the keyring.
///
/// Only [`KeyringProviderBackend::Native`] is supported at this time.
#[instrument(skip_all, fields(url = % url.to_string(), username))]
pub async fn remove(&self, url: &DisplaySafeUrl, username: &str) -> Result<(), Error> {
// Ensure we strip credentials from the URL before storing
let url = url.without_credentials();
// If there's no path, we'll perform a host-level login
let target = if let Some(host) = url.host_str().filter(|_| !url.path().is_empty()) {
let mut target = String::new();
if url.scheme() != "https" {
target.push_str(url.scheme());
target.push_str("://");
}
target.push_str(host);
if let Some(port) = url.port() {
target.push(':');
target.push_str(&port.to_string());
}
target
} else {
url.to_string()
};
match &self.backend {
KeyringProviderBackend::Native => {
self.remove_native(&target, username).await?;
Ok(())
}
KeyringProviderBackend::Subprocess => {
Err(Error::RemoveUnsupported(self.backend.clone()))
}
#[cfg(test)]
KeyringProviderBackend::Dummy(_) => Err(Error::RemoveUnsupported(self.backend.clone())),
}
}
/// Remove credentials from the system keyring for the given `service_name`/`username`
/// pair.
#[instrument(skip(self))]
async fn remove_native(
&self,
service_name: &str,
username: &str,
) -> Result<(), uv_keyring::Error> {
let prefixed_service = format!("{UV_SERVICE_PREFIX}{service_name}");
let entry = uv_keyring::Entry::new(&prefixed_service, username)?;
entry.delete_credential().await?;
trace!("Removed credentials for {username}@{service_name} from system keyring");
Ok(())
}
/// Fetch credentials for the given [`Url`] from the keyring.
///
/// Returns [`None`] if no password was found for the username or if any errors
/// are encountered in the keyring backend.
#[instrument(skip_all, fields(url = % url.to_string(), username))]
pub async fn fetch(&self, url: &DisplaySafeUrl, username: Option<&str>) -> Option<Credentials> {
// Validate the request
debug_assert!(
url.host_str().is_some(),
"Should only use keyring for URLs with host"
);
debug_assert!(
url.password().is_none(),
"Should only use keyring for URLs without a password"
);
debug_assert!(
!username.map(str::is_empty).unwrap_or(false),
"Should only use keyring with a non-empty username"
);
// Check the full URL first
// <https://github.com/pypa/pip/blob/ae5fff36b0aad6e5e0037884927eaa29163c0611/src/pip/_internal/network/auth.py#L376C1-L379C14>
trace!("Checking keyring for URL {url}");
let mut credentials = match self.backend {
KeyringProviderBackend::Native => self.fetch_native(url.as_str(), username).await,
KeyringProviderBackend::Subprocess => {
self.fetch_subprocess(url.as_str(), username).await
}
#[cfg(test)]
KeyringProviderBackend::Dummy(ref store) => {
Self::fetch_dummy(store, url.as_str(), username)
}
};
// And fallback to a check for the host
if credentials.is_none() {
let host = if let Some(port) = url.port() {
format!("{}:{}", url.host_str()?, port)
} else {
url.host_str()?.to_string()
};
trace!("Checking keyring for host {host}");
credentials = match self.backend {
KeyringProviderBackend::Native => self.fetch_native(&host, username).await,
KeyringProviderBackend::Subprocess => self.fetch_subprocess(&host, username).await,
#[cfg(test)]
KeyringProviderBackend::Dummy(ref store) => {
Self::fetch_dummy(store, &host, username)
}
};
}
credentials.map(|(username, password)| Credentials::basic(Some(username), Some(password)))
}
#[instrument(skip(self))]
async fn fetch_subprocess(
&self,
service_name: &str,
username: Option<&str>,
) -> Option<(String, String)> {
// https://github.com/pypa/pip/blob/24.0/src/pip/_internal/network/auth.py#L136-L141
let mut command = Command::new("keyring");
command.arg("get").arg(service_name);
if let Some(username) = username {
command.arg(username);
} else {
command.arg("--mode").arg("creds");
}
let child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
// If we're using `--mode creds`, we need to capture the output in order to avoid
// showing users an "unrecognized arguments: --mode" error; otherwise, we stream stderr
// so the user has visibility into keyring's behavior if it's doing something slow
.stderr(if username.is_some() {
Stdio::inherit()
} else {
Stdio::piped()
})
.spawn()
.inspect_err(|err| warn!("Failure running `keyring` command: {err}"))
.ok()?;
let output = child
.wait_with_output()
.await
.inspect_err(|err| warn!("Failed to wait for `keyring` output: {err}"))
.ok()?;
if output.status.success() {
// If we captured stderr, display it in case it's helpful to the user
// TODO(zanieb): This was done when we added `--mode creds` support for parity with the
// existing behavior, but it might be a better UX to hide this on success? It also
// might be problematic that we're not streaming it. We could change this given some
// user feedback.
std::io::stderr().write_all(&output.stderr).ok();
// On success, parse the newline terminated credentials
let output = String::from_utf8(output.stdout)
.inspect_err(|err| warn!("Failed to parse response from `keyring` command: {err}"))
.ok()?;
let (username, password) = if let Some(username) = username {
// We're only expecting a password
let password = output.trim_end();
(username, password)
} else {
// We're expecting a username and password
let mut lines = output.lines();
let username = lines.next()?;
let Some(password) = lines.next() else {
warn!(
"Got username without password for `{service_name}` from `keyring` command"
);
return None;
};
(username, password)
};
if password.is_empty() {
// We allow this for backwards compatibility, but it might be better to return
// `None` instead if there's confusion from users — we haven't seen this in practice
// yet.
warn!("Got empty password for `{username}@{service_name}` from `keyring` command");
}
Some((username.to_string(), password.to_string()))
} else {
// On failure, no password was available
let stderr = std::str::from_utf8(&output.stderr).ok()?;
if stderr.contains("unrecognized arguments: --mode") {
// N.B. We do not show the `service_name` here because we'll show the warning twice
// otherwise, once for the URL and once for the realm.
warn_user_once!(
"Attempted to fetch credentials using the `keyring` command, but it does not support `--mode creds`; upgrade to `keyring>=v25.2.1` or provide a username"
);
} else if username.is_none() {
// If we captured stderr, display it in case it's helpful to the user
std::io::stderr().write_all(&output.stderr).ok();
}
None
}
}
#[instrument(skip(self))]
async fn fetch_native(
&self,
service: &str,
username: Option<&str>,
) -> Option<(String, String)> {
let prefixed_service = format!("{UV_SERVICE_PREFIX}{service}");
let username = username?;
let Ok(entry) = uv_keyring::Entry::new(&prefixed_service, username) else {
return None;
};
match entry.get_password().await {
Ok(password) => return Some((username.to_string(), password)),
Err(uv_keyring::Error::NoEntry) => {
debug!("No entry found in system keyring for {service}");
}
Err(err) => {
warn_user_once!(
"Unable to fetch credentials for {service} from system keyring: {err}"
);
}
}
None
}
#[cfg(test)]
fn fetch_dummy(
store: &Vec<(String, &'static str, &'static str)>,
service_name: &str,
username: Option<&str>,
) -> Option<(String, String)> {
store.iter().find_map(|(service, user, password)| {
if service == service_name && username.is_none_or(|username| username == *user) {
Some(((*user).to_string(), (*password).to_string()))
} else {
None
}
})
}
/// Create a new provider with [`KeyringProviderBackend::Dummy`].
#[cfg(test)]
pub fn dummy<S: Into<String>, T: IntoIterator<Item = (S, &'static str, &'static str)>>(
iter: T,
) -> Self {
Self {
backend: KeyringProviderBackend::Dummy(
iter.into_iter()
.map(|(service, username, password)| (service.into(), username, password))
.collect(),
),
}
}
/// Create a new provider with no credentials available.
#[cfg(test)]
pub fn empty() -> Self {
Self {
backend: KeyringProviderBackend::Dummy(Vec::new()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::FutureExt;
use url::Url;
#[tokio::test]
async fn fetch_url_no_host() {
let url = Url::parse("file:/etc/bin/").unwrap();
let keyring = KeyringProvider::empty();
// Panics due to debug assertion; returns `None` in production
let fetch = keyring.fetch(DisplaySafeUrl::ref_cast(&url), Some("user"));
if cfg!(debug_assertions) {
let result = std::panic::AssertUnwindSafe(fetch).catch_unwind().await;
assert!(result.is_err());
} else {
assert_eq!(fetch.await, None);
}
}
#[tokio::test]
async fn fetch_url_with_password() {
let url = Url::parse("https://user:password@example.com").unwrap();
let keyring = KeyringProvider::empty();
// Panics due to debug assertion; returns `None` in production
let fetch = keyring.fetch(DisplaySafeUrl::ref_cast(&url), Some(url.username()));
if cfg!(debug_assertions) {
let result = std::panic::AssertUnwindSafe(fetch).catch_unwind().await;
assert!(result.is_err());
} else {
assert_eq!(fetch.await, None);
}
}
#[tokio::test]
async fn fetch_url_with_empty_username() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::empty();
// Panics due to debug assertion; returns `None` in production
let fetch = keyring.fetch(DisplaySafeUrl::ref_cast(&url), Some(url.username()));
if cfg!(debug_assertions) {
let result = std::panic::AssertUnwindSafe(fetch).catch_unwind().await;
assert!(result.is_err());
} else {
assert_eq!(fetch.await, None);
}
}
#[tokio::test]
async fn fetch_url_no_auth() {
let url = Url::parse("https://example.com").unwrap();
let url = DisplaySafeUrl::ref_cast(&url);
let keyring = KeyringProvider::empty();
let credentials = keyring.fetch(url, Some("user"));
assert!(credentials.await.is_none());
}
#[tokio::test]
async fn fetch_url() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::dummy([(url.host_str().unwrap(), "user", "password")]);
assert_eq!(
keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("user"))
.await,
Some(Credentials::basic(
Some("user".to_string()),
Some("password".to_string())
))
);
assert_eq!(
keyring
.fetch(
DisplaySafeUrl::ref_cast(&url.join("test").unwrap()),
Some("user")
)
.await,
Some(Credentials::basic(
Some("user".to_string()),
Some("password".to_string())
))
);
}
#[tokio::test]
async fn fetch_url_no_match() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::dummy([("other.com", "user", "password")]);
let credentials = keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("user"))
.await;
assert_eq!(credentials, None);
}
#[tokio::test]
async fn fetch_url_prefers_url_to_host() {
let url = Url::parse("https://example.com/").unwrap();
let keyring = KeyringProvider::dummy([
(url.join("foo").unwrap().as_str(), "user", "password"),
(url.host_str().unwrap(), "user", "other-password"),
]);
assert_eq!(
keyring
.fetch(
DisplaySafeUrl::ref_cast(&url.join("foo").unwrap()),
Some("user")
)
.await,
Some(Credentials::basic(
Some("user".to_string()),
Some("password".to_string())
))
);
assert_eq!(
keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("user"))
.await,
Some(Credentials::basic(
Some("user".to_string()),
Some("other-password".to_string())
))
);
assert_eq!(
keyring
.fetch(
DisplaySafeUrl::ref_cast(&url.join("bar").unwrap()),
Some("user")
)
.await,
Some(Credentials::basic(
Some("user".to_string()),
Some("other-password".to_string())
))
);
}
#[tokio::test]
async fn fetch_url_username() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::dummy([(url.host_str().unwrap(), "user", "password")]);
let credentials = keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("user"))
.await;
assert_eq!(
credentials,
Some(Credentials::basic(
Some("user".to_string()),
Some("password".to_string())
))
);
}
#[tokio::test]
async fn fetch_url_no_username() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::dummy([(url.host_str().unwrap(), "user", "password")]);
let credentials = keyring.fetch(DisplaySafeUrl::ref_cast(&url), None).await;
assert_eq!(
credentials,
Some(Credentials::basic(
Some("user".to_string()),
Some("password".to_string())
))
);
}
#[tokio::test]
async fn fetch_url_username_no_match() {
let url = Url::parse("https://example.com").unwrap();
let keyring = KeyringProvider::dummy([(url.host_str().unwrap(), "foo", "password")]);
let credentials = keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("bar"))
.await;
assert_eq!(credentials, None);
// Still fails if we have `foo` in the URL itself
let url = Url::parse("https://foo@example.com").unwrap();
let credentials = keyring
.fetch(DisplaySafeUrl::ref_cast(&url), Some("bar"))
.await;
assert_eq!(credentials, 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-auth/src/cache.rs | crates/uv-auth/src/cache.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::hash::BuildHasherDefault;
use std::sync::Arc;
use std::sync::RwLock;
use rustc_hash::{FxHashMap, FxHasher};
use tracing::trace;
use url::Url;
use uv_once_map::OnceMap;
use uv_redacted::DisplaySafeUrl;
use crate::credentials::{Authentication, Username};
use crate::{Credentials, Realm};
type FxOnceMap<K, V> = OnceMap<K, V, BuildHasherDefault<FxHasher>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum FetchUrl {
/// A full index URL
Index(DisplaySafeUrl),
/// A realm URL
Realm(Realm),
}
impl Display for FetchUrl {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
Self::Index(index) => Display::fmt(index, f),
Self::Realm(realm) => Display::fmt(realm, f),
}
}
}
#[derive(Debug)] // All internal types are redacted.
pub struct CredentialsCache {
/// A cache per realm and username
realms: RwLock<FxHashMap<(Realm, Username), Arc<Authentication>>>,
/// A cache tracking the result of realm or index URL fetches from external services
pub(crate) fetches: FxOnceMap<(FetchUrl, Username), Option<Arc<Authentication>>>,
/// A cache per URL, uses a trie for efficient prefix queries.
urls: RwLock<UrlTrie<Arc<Authentication>>>,
}
impl Default for CredentialsCache {
fn default() -> Self {
Self::new()
}
}
impl CredentialsCache {
/// Create a new cache.
pub fn new() -> Self {
Self {
fetches: FxOnceMap::default(),
realms: RwLock::new(FxHashMap::default()),
urls: RwLock::new(UrlTrie::new()),
}
}
/// Populate the global authentication store with credentials on a URL, if there are any.
///
/// Returns `true` if the store was updated.
pub fn store_credentials_from_url(&self, url: &DisplaySafeUrl) -> bool {
if let Some(credentials) = Credentials::from_url(url) {
trace!("Caching credentials for {url}");
self.insert(url, Arc::new(Authentication::from(credentials)));
true
} else {
false
}
}
/// Populate the global authentication store with credentials on a URL, if there are any.
///
/// Returns `true` if the store was updated.
pub fn store_credentials(&self, url: &DisplaySafeUrl, credentials: Credentials) {
trace!("Caching credentials for {url}");
self.insert(url, Arc::new(Authentication::from(credentials)));
}
/// Return the credentials that should be used for a realm and username, if any.
pub(crate) fn get_realm(
&self,
realm: Realm,
username: Username,
) -> Option<Arc<Authentication>> {
let realms = self.realms.read().unwrap();
let given_username = username.is_some();
let key = (realm, username);
let Some(credentials) = realms.get(&key).cloned() else {
trace!(
"No credentials in cache for realm {}",
RealmUsername::from(key)
);
return None;
};
if given_username && credentials.password().is_none() {
// If given a username, don't return password-less credentials
trace!(
"No password in cache for realm {}",
RealmUsername::from(key)
);
return None;
}
trace!(
"Found cached credentials for realm {}",
RealmUsername::from(key)
);
Some(credentials)
}
/// Return the cached credentials for a URL and username, if any.
///
/// Note we do not cache per username, but if a username is passed we will confirm that the
/// cached credentials have a username equal to the provided one — otherwise `None` is returned.
/// If multiple usernames are used per URL, the realm cache should be queried instead.
pub(crate) fn get_url(&self, url: &Url, username: &Username) -> Option<Arc<Authentication>> {
let urls = self.urls.read().unwrap();
let credentials = urls.get(url);
if let Some(credentials) = credentials {
if username.is_none() || username.as_deref() == credentials.username() {
if username.is_some() && credentials.password().is_none() {
// If given a username, don't return password-less credentials
trace!("No password in cache for URL {url}");
return None;
}
trace!("Found cached credentials for URL {url}");
return Some(credentials.clone());
}
}
trace!("No credentials in cache for URL {url}");
None
}
/// Update the cache with the given credentials.
pub(crate) fn insert(&self, url: &Url, credentials: Arc<Authentication>) {
// Do not cache empty credentials
if credentials.is_empty() {
return;
}
// Insert an entry for requests including the username
let username = credentials.to_username();
if username.is_some() {
let realm = (Realm::from(url), username);
self.insert_realm(realm, &credentials);
}
// Insert an entry for requests with no username
self.insert_realm((Realm::from(url), Username::none()), &credentials);
// Insert an entry for the URL
let mut urls = self.urls.write().unwrap();
urls.insert(url, credentials);
}
/// Private interface to update a realm cache entry.
///
/// Returns replaced credentials, if any.
fn insert_realm(
&self,
key: (Realm, Username),
credentials: &Arc<Authentication>,
) -> Option<Arc<Authentication>> {
// Do not cache empty credentials
if credentials.is_empty() {
return None;
}
let mut realms = self.realms.write().unwrap();
// Always replace existing entries if we have a password or token
if credentials.is_authenticated() {
return realms.insert(key, credentials.clone());
}
// If we only have a username, add a new entry or replace an existing entry if it doesn't have a password
let existing = realms.get(&key);
if existing.is_none()
|| existing.is_some_and(|credentials| credentials.password().is_none())
{
return realms.insert(key, credentials.clone());
}
None
}
}
#[derive(Debug)]
struct UrlTrie<T> {
states: Vec<TrieState<T>>,
}
#[derive(Debug)]
struct TrieState<T> {
children: Vec<(String, usize)>,
value: Option<T>,
}
impl<T> Default for TrieState<T> {
fn default() -> Self {
Self {
children: vec![],
value: None,
}
}
}
impl<T> UrlTrie<T> {
fn new() -> Self {
let mut trie = Self { states: vec![] };
trie.alloc();
trie
}
fn get(&self, url: &Url) -> Option<&T> {
let mut state = 0;
let realm = Realm::from(url).to_string();
for component in [realm.as_str()]
.into_iter()
.chain(url.path_segments().unwrap().filter(|item| !item.is_empty()))
{
state = self.states[state].get(component)?;
if let Some(ref value) = self.states[state].value {
return Some(value);
}
}
self.states[state].value.as_ref()
}
fn insert(&mut self, url: &Url, value: T) {
let mut state = 0;
let realm = Realm::from(url).to_string();
for component in [realm.as_str()]
.into_iter()
.chain(url.path_segments().unwrap().filter(|item| !item.is_empty()))
{
match self.states[state].index(component) {
Ok(i) => state = self.states[state].children[i].1,
Err(i) => {
let new_state = self.alloc();
self.states[state]
.children
.insert(i, (component.to_string(), new_state));
state = new_state;
}
}
}
self.states[state].value = Some(value);
}
fn alloc(&mut self) -> usize {
let id = self.states.len();
self.states.push(TrieState::default());
id
}
}
impl<T> TrieState<T> {
fn get(&self, component: &str) -> Option<usize> {
let i = self.index(component).ok()?;
Some(self.children[i].1)
}
fn index(&self, component: &str) -> Result<usize, usize> {
self.children
.binary_search_by(|(label, _)| label.as_str().cmp(component))
}
}
#[derive(Debug)]
struct RealmUsername(Realm, Username);
impl std::fmt::Display for RealmUsername {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let Self(realm, username) = self;
if let Some(username) = username.as_deref() {
write!(f, "{username}@{realm}")
} else {
write!(f, "{realm}")
}
}
}
impl From<(Realm, Username)> for RealmUsername {
fn from((realm, username): (Realm, Username)) -> Self {
Self(realm, username)
}
}
#[cfg(test)]
mod tests {
use crate::Credentials;
use crate::credentials::Password;
use super::*;
#[test]
fn test_trie() {
let credentials1 =
Credentials::basic(Some("username1".to_string()), Some("password1".to_string()));
let credentials2 =
Credentials::basic(Some("username2".to_string()), Some("password2".to_string()));
let credentials3 =
Credentials::basic(Some("username3".to_string()), Some("password3".to_string()));
let credentials4 =
Credentials::basic(Some("username4".to_string()), Some("password4".to_string()));
let mut trie = UrlTrie::new();
trie.insert(
&Url::parse("https://burntsushi.net").unwrap(),
credentials1.clone(),
);
trie.insert(
&Url::parse("https://astral.sh").unwrap(),
credentials2.clone(),
);
trie.insert(
&Url::parse("https://example.com/foo").unwrap(),
credentials3.clone(),
);
trie.insert(
&Url::parse("https://example.com/bar").unwrap(),
credentials4.clone(),
);
let url = Url::parse("https://burntsushi.net/regex-internals").unwrap();
assert_eq!(trie.get(&url), Some(&credentials1));
let url = Url::parse("https://burntsushi.net/").unwrap();
assert_eq!(trie.get(&url), Some(&credentials1));
let url = Url::parse("https://astral.sh/about").unwrap();
assert_eq!(trie.get(&url), Some(&credentials2));
let url = Url::parse("https://example.com/foo").unwrap();
assert_eq!(trie.get(&url), Some(&credentials3));
let url = Url::parse("https://example.com/foo/").unwrap();
assert_eq!(trie.get(&url), Some(&credentials3));
let url = Url::parse("https://example.com/foo/bar").unwrap();
assert_eq!(trie.get(&url), Some(&credentials3));
let url = Url::parse("https://example.com/bar").unwrap();
assert_eq!(trie.get(&url), Some(&credentials4));
let url = Url::parse("https://example.com/bar/").unwrap();
assert_eq!(trie.get(&url), Some(&credentials4));
let url = Url::parse("https://example.com/bar/foo").unwrap();
assert_eq!(trie.get(&url), Some(&credentials4));
let url = Url::parse("https://example.com/about").unwrap();
assert_eq!(trie.get(&url), None);
let url = Url::parse("https://example.com/foobar").unwrap();
assert_eq!(trie.get(&url), None);
}
#[test]
fn test_url_with_credentials() {
let username = Username::new(Some(String::from("username")));
let password = Password::new(String::from("password"));
let credentials = Arc::new(Authentication::from(Credentials::Basic {
username: username.clone(),
password: Some(password),
}));
let cache = CredentialsCache::default();
// Insert with URL with credentials and get with redacted URL.
let url = Url::parse("https://username:password@example.com/foobar").unwrap();
cache.insert(&url, credentials.clone());
assert_eq!(cache.get_url(&url, &username), Some(credentials.clone()));
// Insert with redacted URL and get with URL with credentials.
let url = Url::parse("https://username:password@second-example.com/foobar").unwrap();
cache.insert(&url, credentials.clone());
assert_eq!(cache.get_url(&url, &username), Some(credentials.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-auth/src/providers.rs | crates/uv-auth/src/providers.rs | use std::borrow::Cow;
use std::sync::LazyLock;
use reqsign::aws::DefaultSigner;
use tracing::debug;
use url::Url;
use uv_preview::{Preview, PreviewFeatures};
use uv_static::EnvVars;
use uv_warnings::warn_user_once;
use crate::Credentials;
use crate::credentials::Token;
use crate::realm::{Realm, RealmRef};
/// The [`Realm`] for the Hugging Face platform.
static HUGGING_FACE_REALM: LazyLock<Realm> = LazyLock::new(|| {
let url = Url::parse("https://huggingface.co").expect("Failed to parse Hugging Face URL");
Realm::from(&url)
});
/// The authentication token for the Hugging Face platform, if set.
static HUGGING_FACE_TOKEN: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
// Extract the Hugging Face token from the environment variable, if it exists.
let hf_token = std::env::var(EnvVars::HF_TOKEN)
.ok()
.map(String::into_bytes)
.filter(|token| !token.is_empty())?;
if std::env::var_os(EnvVars::UV_NO_HF_TOKEN).is_some() {
debug!("Ignoring Hugging Face token from environment due to `UV_NO_HF_TOKEN`");
return None;
}
debug!("Found Hugging Face token in environment");
Some(hf_token)
});
/// A provider for authentication credentials for the Hugging Face platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HuggingFaceProvider;
impl HuggingFaceProvider {
/// Returns the credentials for the Hugging Face platform, if available.
pub(crate) fn credentials_for(url: &Url) -> Option<Credentials> {
if RealmRef::from(url) == *HUGGING_FACE_REALM {
if let Some(token) = HUGGING_FACE_TOKEN.as_ref() {
return Some(Credentials::Bearer {
token: Token::new(token.clone()),
});
}
}
None
}
}
/// The [`Url`] for the S3 endpoint, if set.
static S3_ENDPOINT_REALM: LazyLock<Option<Realm>> = LazyLock::new(|| {
let s3_endpoint_url = std::env::var(EnvVars::UV_S3_ENDPOINT_URL).ok()?;
let url = Url::parse(&s3_endpoint_url).expect("Failed to parse S3 endpoint URL");
Some(Realm::from(&url))
});
/// A provider for authentication credentials for S3 endpoints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct S3EndpointProvider;
impl S3EndpointProvider {
/// Returns `true` if the URL matches the configured S3 endpoint.
pub(crate) fn is_s3_endpoint(url: &Url, preview: Preview) -> bool {
if let Some(s3_endpoint_realm) = S3_ENDPOINT_REALM.as_ref().map(RealmRef::from) {
if !preview.is_enabled(PreviewFeatures::S3_ENDPOINT) {
warn_user_once!(
"The `s3-endpoint` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.",
PreviewFeatures::S3_ENDPOINT
);
}
// Treat any URL on the same domain or subdomain as available for S3 signing.
let realm = RealmRef::from(url);
if realm == s3_endpoint_realm || realm.is_subdomain_of(s3_endpoint_realm) {
return true;
}
}
false
}
/// Creates a new S3 signer with the configured region.
///
/// This is potentially expensive as it may invoke credential helpers, so the result
/// should be cached.
pub(crate) fn create_signer() -> DefaultSigner {
// TODO(charlie): Can `reqsign` infer the region for us? Profiles, for example,
// often have a region set already.
let region = std::env::var(EnvVars::AWS_REGION)
.map(Cow::Owned)
.unwrap_or_else(|_| {
std::env::var(EnvVars::AWS_DEFAULT_REGION)
.map(Cow::Owned)
.unwrap_or_else(|_| Cow::Borrowed("us-east-1"))
});
reqsign::aws::default_signer("s3", ®ion)
}
}
| 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-pep508/src/verbatim_url.rs | crates/uv-pep508/src/verbatim_url.rs | use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use arcstr::ArcStr;
use regex::Regex;
use thiserror::Error;
use url::Url;
use uv_cache_key::{CacheKey, CacheKeyHasher};
#[cfg_attr(not(feature = "non-pep508-extensions"), allow(unused_imports))]
use uv_fs::{normalize_absolute_path, normalize_url_path};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
use crate::Pep508Url;
/// A wrapper around [`Url`] that preserves the original string.
///
/// The original string is not preserved after serialization/deserialization.
#[derive(Debug, Clone, Eq)]
pub struct VerbatimUrl {
/// The parsed URL.
url: DisplaySafeUrl,
/// The URL as it was provided by the user.
///
/// Even if originally set, this will be [`None`] after
/// serialization/deserialization.
given: Option<ArcStr>,
}
impl Hash for VerbatimUrl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.url.hash(state);
}
}
impl CacheKey for VerbatimUrl {
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.url.as_str().cache_key(state);
}
}
impl PartialEq for VerbatimUrl {
fn eq(&self, other: &Self) -> bool {
self.url == other.url
}
}
impl VerbatimUrl {
/// Create a [`VerbatimUrl`] from a [`Url`].
pub fn from_url(url: DisplaySafeUrl) -> Self {
Self { url, given: None }
}
/// Parse a URL from a string.
pub fn parse_url(given: impl AsRef<str>) -> Result<Self, VerbatimUrlError> {
let given = given.as_ref();
let url = DisplaySafeUrl::parse(given)?;
Ok(Self { url, given: None })
}
/// Convert a [`VerbatimUrl`] from a path or a URL.
///
/// If no root directory is provided, relative paths are resolved against the current working
/// directory.
#[cfg(feature = "non-pep508-extensions")] // PEP 508 arguably only allows absolute file URLs.
pub fn from_url_or_path(
input: &str,
root_dir: Option<&Path>,
) -> Result<Self, VerbatimUrlError> {
let url = match split_scheme(input) {
Some((scheme, ..)) => {
match Scheme::parse(scheme) {
Some(_) => {
// Ex) `https://pypi.org/simple`
Self::parse_url(input)?
}
None => {
// Ex) `C:\Users\user\index`
if let Some(root_dir) = root_dir {
Self::from_path(input, root_dir)?
} else {
let absolute_path = std::path::absolute(input).map_err(|err| {
VerbatimUrlError::Absolute(input.to_string(), err)
})?;
Self::from_absolute_path(absolute_path)?
}
}
}
}
None => {
// Ex) `/Users/user/index`
if let Some(root_dir) = root_dir {
Self::from_path(input, root_dir)?
} else {
let absolute_path = std::path::absolute(input)
.map_err(|err| VerbatimUrlError::Absolute(input.to_string(), err))?;
Self::from_absolute_path(absolute_path)?
}
}
};
Ok(url.with_given(input))
}
/// Parse a URL from an absolute or relative path.
#[cfg(feature = "non-pep508-extensions")] // PEP 508 arguably only allows absolute file URLs.
pub fn from_path(
path: impl AsRef<Path>,
base_dir: impl AsRef<Path>,
) -> Result<Self, VerbatimUrlError> {
debug_assert!(base_dir.as_ref().is_absolute(), "base dir must be absolute");
let path = path.as_ref();
// Convert the path to an absolute path, if necessary.
let path = if path.is_absolute() {
Cow::Borrowed(path)
} else {
Cow::Owned(base_dir.as_ref().join(path))
};
let path = normalize_absolute_path(&path)
.map_err(|err| VerbatimUrlError::Normalization(path.to_path_buf(), err))?;
// Extract the fragment, if it exists.
let (path, fragment) = split_fragment(&path);
// Convert to a URL.
let mut url = DisplaySafeUrl::from_file_path(path.clone())
.map_err(|()| VerbatimUrlError::UrlConversion(path.to_path_buf()))?;
// Set the fragment, if it exists.
if let Some(fragment) = fragment {
url.set_fragment(Some(fragment));
}
Ok(Self { url, given: None })
}
/// Parse a URL from an absolute path.
pub fn from_absolute_path(path: impl AsRef<Path>) -> Result<Self, VerbatimUrlError> {
let path = path.as_ref();
// Error if the path is relative.
let path = if path.is_absolute() {
path
} else {
return Err(VerbatimUrlError::WorkingDirectory(path.to_path_buf()));
};
// Normalize the path.
let path = normalize_absolute_path(path)
.map_err(|err| VerbatimUrlError::Normalization(path.to_path_buf(), err))?;
// Extract the fragment, if it exists.
let (path, fragment) = split_fragment(&path);
// Convert to a URL.
let mut url = DisplaySafeUrl::from_file_path(path.clone())
.unwrap_or_else(|()| panic!("path is absolute: {}", path.display()));
// Set the fragment, if it exists.
if let Some(fragment) = fragment {
url.set_fragment(Some(fragment));
}
Ok(Self { url, given: None })
}
/// Parse a URL from a normalized path.
///
/// Like [`VerbatimUrl::from_absolute_path`], but skips the normalization step.
pub fn from_normalized_path(path: impl AsRef<Path>) -> Result<Self, VerbatimUrlError> {
let path = path.as_ref();
// Error if the path is relative.
let path = if path.is_absolute() {
path
} else {
return Err(VerbatimUrlError::WorkingDirectory(path.to_path_buf()));
};
// Extract the fragment, if it exists.
let (path, fragment) = split_fragment(path);
// Convert to a URL.
let mut url = DisplaySafeUrl::from_file_path(path.clone())
.unwrap_or_else(|()| panic!("path is absolute: {}", path.display()));
// Set the fragment, if it exists.
if let Some(fragment) = fragment {
url.set_fragment(Some(fragment));
}
Ok(Self { url, given: None })
}
/// Set the verbatim representation of the URL.
#[must_use]
pub fn with_given(self, given: impl AsRef<str>) -> Self {
Self {
given: Some(ArcStr::from(given.as_ref())),
..self
}
}
/// Return the original string as given by the user, if available.
pub fn given(&self) -> Option<&str> {
self.given.as_deref()
}
/// Return the underlying [`DisplaySafeUrl`].
pub fn raw(&self) -> &DisplaySafeUrl {
&self.url
}
/// Convert a [`VerbatimUrl`] into a [`DisplaySafeUrl`].
pub fn to_url(&self) -> DisplaySafeUrl {
self.url.clone()
}
/// Convert a [`VerbatimUrl`] into a [`DisplaySafeUrl`].
pub fn into_url(self) -> DisplaySafeUrl {
self.url
}
/// Return the underlying [`Path`], if the URL is a file URL.
#[cfg(feature = "non-pep508-extensions")]
pub fn as_path(&self) -> Result<PathBuf, VerbatimUrlError> {
self.url
.to_file_path()
.map_err(|()| VerbatimUrlError::UrlConversion(self.url.to_file_path().unwrap()))
}
}
impl Ord for VerbatimUrl {
fn cmp(&self, other: &Self) -> Ordering {
self.url.cmp(&other.url)
}
}
impl PartialOrd for VerbatimUrl {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl std::str::FromStr for VerbatimUrl {
type Err = VerbatimUrlError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse_url(s).map(|url| url.with_given(s))
}
}
impl std::fmt::Display for VerbatimUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.url, f)
}
}
impl Deref for VerbatimUrl {
type Target = DisplaySafeUrl;
fn deref(&self) -> &Self::Target {
&self.url
}
}
impl From<Url> for VerbatimUrl {
fn from(url: Url) -> Self {
Self::from_url(DisplaySafeUrl::from_url(url))
}
}
impl From<DisplaySafeUrl> for VerbatimUrl {
fn from(url: DisplaySafeUrl) -> Self {
Self::from_url(url)
}
}
impl From<VerbatimUrl> for Url {
fn from(url: VerbatimUrl) -> Self {
Self::from(url.url)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for VerbatimUrl {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.url.serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for VerbatimUrl {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let url = DisplaySafeUrl::deserialize(deserializer)?;
Ok(Self::from_url(url))
}
}
impl Pep508Url for VerbatimUrl {
type Err = VerbatimUrlError;
/// Create a [`VerbatimUrl`] to represent a PEP 508 requirement.
///
/// Any environment variables in the URL will be expanded.
#[cfg_attr(not(feature = "non-pep508-extensions"), allow(unused_variables))]
fn parse_url(url: &str, working_dir: Option<&Path>) -> Result<Self, Self::Err> {
// Expand environment variables in the URL.
let expanded = expand_env_vars(url);
if let Some((scheme, path)) = split_scheme(&expanded) {
match Scheme::parse(scheme) {
// Ex) `file:///home/ferris/project/scripts/...`, `file://localhost/home/ferris/project/scripts/...`, or `file:../ferris/`
Some(Scheme::File) => {
// Strip the leading slashes, along with the `localhost` host, if present.
// Transform, e.g., `/C:/Users/ferris/wheel-0.42.0.tar.gz` to `C:\Users\ferris\wheel-0.42.0.tar.gz`.
#[cfg(feature = "non-pep508-extensions")]
{
let path = strip_host(path);
let path = normalize_url_path(path);
if let Some(working_dir) = working_dir {
return Ok(Self::from_path(path.as_ref(), working_dir)?.with_given(url));
}
Ok(Self::from_absolute_path(path.as_ref())?.with_given(url))
}
#[cfg(not(feature = "non-pep508-extensions"))]
Ok(Self::parse_url(expanded)?.with_given(url))
}
// Ex) `https://download.pytorch.org/whl/torch_stable.html`
Some(_) => {
// Ex) `https://download.pytorch.org/whl/torch_stable.html`
Ok(Self::parse_url(expanded.as_ref())?.with_given(url))
}
// Ex) `C:\Users\ferris\wheel-0.42.0.tar.gz`
_ => {
#[cfg(feature = "non-pep508-extensions")]
{
if let Some(working_dir) = working_dir {
return Ok(
Self::from_path(expanded.as_ref(), working_dir)?.with_given(url)
);
}
Ok(Self::from_absolute_path(expanded.as_ref())?.with_given(url))
}
#[cfg(not(feature = "non-pep508-extensions"))]
Err(Self::Err::NotAUrl(expanded.to_string()))
}
}
} else {
// Ex) `../editable/`
#[cfg(feature = "non-pep508-extensions")]
{
if let Some(working_dir) = working_dir {
return Ok(Self::from_path(expanded.as_ref(), working_dir)?.with_given(url));
}
Ok(Self::from_absolute_path(expanded.as_ref())?.with_given(url))
}
#[cfg(not(feature = "non-pep508-extensions"))]
Err(Self::Err::NotAUrl(expanded.to_string()))
}
}
fn displayable_with_credentials(&self) -> impl Display {
self.url.displayable_with_credentials()
}
}
/// An error that can occur when parsing a [`VerbatimUrl`].
#[derive(Error, Debug)]
pub enum VerbatimUrlError {
/// Failed to parse a URL.
#[error(transparent)]
Url(#[from] DisplaySafeUrlError),
/// Received a relative path, but no working directory was provided.
#[error("relative path without a working directory: {0}")]
WorkingDirectory(PathBuf),
/// Received a path that could not be converted to a URL.
#[error("path could not be converted to a URL: {0}")]
UrlConversion(PathBuf),
/// Received a path that could not be normalized.
#[error("path could not be normalized: {0}")]
Normalization(PathBuf, #[source] std::io::Error),
/// Received a path that could not be converted to an absolute path.
#[error("path could not be converted to an absolute path: {0}")]
Absolute(String, #[source] std::io::Error),
/// Received a path that could not be normalized.
#[cfg(not(feature = "non-pep508-extensions"))]
#[error("Not a URL (missing scheme): {0}")]
NotAUrl(String),
}
/// Expand all available environment variables.
///
/// This is modeled off of pip's environment variable expansion, which states:
///
/// The only allowed format for environment variables defined in the
/// requirement file is `${MY_VARIABLE_1}` to ensure two things:
///
/// 1. Strings that contain a `$` aren't accidentally (partially) expanded.
/// 2. Ensure consistency across platforms for requirement files.
///
/// ...
///
/// Valid characters in variable names follow the `POSIX standard
/// <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
/// to uppercase letter, digits and the `_` (underscore).
pub fn expand_env_vars(s: &str) -> Cow<'_, str> {
// Generate the project root, to be used via the `${PROJECT_ROOT}`
// environment variable.
static PROJECT_ROOT_FRAGMENT: LazyLock<String> = LazyLock::new(|| {
let project_root = std::env::current_dir().unwrap();
project_root.to_string_lossy().to_string()
});
static RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?P<var>\$\{(?P<name>[A-Z0-9_]+)})").unwrap());
RE.replace_all(s, |caps: ®ex::Captures<'_>| {
let name = caps.name("name").unwrap().as_str();
std::env::var(name).unwrap_or_else(|_| match name {
"PROJECT_ROOT" => PROJECT_ROOT_FRAGMENT.to_string(),
_ => caps["var"].to_owned(),
})
})
}
/// Like [`Url::parse`], but only splits the scheme. Derived from the `url` crate.
pub fn split_scheme(s: &str) -> Option<(&str, &str)> {
/// <https://url.spec.whatwg.org/#c0-controls-and-space>
#[inline]
fn c0_control_or_space(ch: char) -> bool {
ch <= ' ' // U+0000 to U+0020
}
/// <https://url.spec.whatwg.org/#ascii-alpha>
#[inline]
fn ascii_alpha(ch: char) -> bool {
ch.is_ascii_alphabetic()
}
// Trim control characters and spaces from the start and end.
let s = s.trim_matches(c0_control_or_space);
if s.is_empty() || !s.starts_with(ascii_alpha) {
return None;
}
// Find the `:` following any alpha characters.
let mut iter = s.char_indices();
let end = loop {
match iter.next() {
Some((_i, 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.')) => {}
Some((i, ':')) => break i,
_ => return None,
}
};
let scheme = &s[..end];
let rest = &s[end + 1..];
Some((scheme, rest))
}
/// Strip the `file://localhost/` host from a file path.
pub fn strip_host(path: &str) -> &str {
// Ex) `file://localhost/...`.
if let Some(path) = path
.strip_prefix("//localhost")
.filter(|path| path.starts_with('/'))
{
return path;
}
// Ex) `file:///...`.
if let Some(path) = path.strip_prefix("//") {
return path;
}
path
}
/// Returns `true` if a URL looks like a reference to a Git repository (e.g., `https://github.com/user/repo.git`).
pub fn looks_like_git_repository(url: &Url) -> bool {
matches!(
url.host_str(),
Some("github.com" | "gitlab.com" | "bitbucket.org")
) && Path::new(url.path())
.extension()
.is_none_or(|ext| ext.eq_ignore_ascii_case("git"))
&& url
.path_segments()
.is_some_and(|segments| segments.count() == 2)
}
/// Split the fragment from a URL.
///
/// For example, given `file:///home/ferris/project/scripts#hash=somehash`, returns
/// `("/home/ferris/project/scripts", Some("hash=somehash"))`.
fn split_fragment(path: &Path) -> (Cow<'_, Path>, Option<&str>) {
let Some(s) = path.to_str() else {
return (Cow::Borrowed(path), None);
};
let Some((path, fragment)) = s.split_once('#') else {
return (Cow::Borrowed(path), None);
};
(Cow::Owned(PathBuf::from(path)), Some(fragment))
}
/// A supported URL scheme for PEP 508 direct-URL requirements.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Scheme {
/// `file://...`
File,
/// `git+{transport}://...` as git supports arbitrary transports through gitremote-helpers
Git(String),
/// `bzr+http://...`
BzrHttp,
/// `bzr+https://...`
BzrHttps,
/// `bzr+ssh://...`
BzrSsh,
/// `bzr+sftp://...`
BzrSftp,
/// `bzr+ftp://...`
BzrFtp,
/// `bzr+lp://...`
BzrLp,
/// `bzr+file://...`
BzrFile,
/// `hg+file://...`
HgFile,
/// `hg+http://...`
HgHttp,
/// `hg+https://...`
HgHttps,
/// `hg+ssh://...`
HgSsh,
/// `hg+static-http://...`
HgStaticHttp,
/// `svn+ssh://...`
SvnSsh,
/// `svn+http://...`
SvnHttp,
/// `svn+https://...`
SvnHttps,
/// `svn+svn://...`
SvnSvn,
/// `svn+file://...`
SvnFile,
/// `http://...`
Http,
/// `https://...`
Https,
}
impl Scheme {
/// Determine the [`Scheme`] from the given string, if possible.
pub fn parse(s: &str) -> Option<Self> {
if let Some(("git", transport)) = s.split_once('+') {
return Some(Self::Git(transport.into()));
}
match s {
"file" => Some(Self::File),
"bzr+http" => Some(Self::BzrHttp),
"bzr+https" => Some(Self::BzrHttps),
"bzr+ssh" => Some(Self::BzrSsh),
"bzr+sftp" => Some(Self::BzrSftp),
"bzr+ftp" => Some(Self::BzrFtp),
"bzr+lp" => Some(Self::BzrLp),
"bzr+file" => Some(Self::BzrFile),
"hg+file" => Some(Self::HgFile),
"hg+http" => Some(Self::HgHttp),
"hg+https" => Some(Self::HgHttps),
"hg+ssh" => Some(Self::HgSsh),
"hg+static-http" => Some(Self::HgStaticHttp),
"svn+ssh" => Some(Self::SvnSsh),
"svn+http" => Some(Self::SvnHttp),
"svn+https" => Some(Self::SvnHttps),
"svn+svn" => Some(Self::SvnSvn),
"svn+file" => Some(Self::SvnFile),
"http" => Some(Self::Http),
"https" => Some(Self::Https),
_ => None,
}
}
/// Returns `true` if the scheme is a file scheme.
pub fn is_file(self) -> bool {
matches!(self, Self::File)
}
}
impl std::fmt::Display for Scheme {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::File => write!(f, "file"),
Self::Git(transport) => write!(f, "git+{transport}"),
Self::BzrHttp => write!(f, "bzr+http"),
Self::BzrHttps => write!(f, "bzr+https"),
Self::BzrSsh => write!(f, "bzr+ssh"),
Self::BzrSftp => write!(f, "bzr+sftp"),
Self::BzrFtp => write!(f, "bzr+ftp"),
Self::BzrLp => write!(f, "bzr+lp"),
Self::BzrFile => write!(f, "bzr+file"),
Self::HgFile => write!(f, "hg+file"),
Self::HgHttp => write!(f, "hg+http"),
Self::HgHttps => write!(f, "hg+https"),
Self::HgSsh => write!(f, "hg+ssh"),
Self::HgStaticHttp => write!(f, "hg+static-http"),
Self::SvnSsh => write!(f, "svn+ssh"),
Self::SvnHttp => write!(f, "svn+http"),
Self::SvnHttps => write!(f, "svn+https"),
Self::SvnSvn => write!(f, "svn+svn"),
Self::SvnFile => write!(f, "svn+file"),
Self::Http => write!(f, "http"),
Self::Https => write!(f, "https"),
}
}
}
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
use super::*;
#[test]
fn scheme() {
assert_eq!(
split_scheme("file:///home/ferris/project/scripts"),
Some(("file", "///home/ferris/project/scripts"))
);
assert_eq!(
split_scheme("file:home/ferris/project/scripts"),
Some(("file", "home/ferris/project/scripts"))
);
assert_eq!(
split_scheme("https://example.com"),
Some(("https", "//example.com"))
);
assert_eq!(split_scheme("https:"), Some(("https", "")));
}
#[test]
fn fragment() {
assert_eq!(
split_fragment(Path::new(
"file:///home/ferris/project/scripts#hash=somehash"
)),
(
Cow::Owned(PathBuf::from("file:///home/ferris/project/scripts")),
Some("hash=somehash")
)
);
assert_eq!(
split_fragment(Path::new("file:home/ferris/project/scripts#hash=somehash")),
(
Cow::Owned(PathBuf::from("file:home/ferris/project/scripts")),
Some("hash=somehash")
)
);
assert_eq!(
split_fragment(Path::new("/home/ferris/project/scripts#hash=somehash")),
(
Cow::Owned(PathBuf::from("/home/ferris/project/scripts")),
Some("hash=somehash")
)
);
assert_eq!(
split_fragment(Path::new("file:///home/ferris/project/scripts")),
(
Cow::Borrowed(Path::new("file:///home/ferris/project/scripts")),
None
)
);
assert_eq!(
split_fragment(Path::new("")),
(Cow::Borrowed(Path::new("")), None)
);
}
#[test]
fn git_repository() {
let url = Url::parse("https://github.com/user/repo.git").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://gitlab.com/user/repo.git").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://bitbucket.org/user/repo.git").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user/repo").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://example.com/user/repo.git").unwrap();
assert!(!looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user").unwrap();
assert!(!looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user/repo.zip").unwrap();
assert!(!looks_like_git_repository(&url));
let url = Url::parse("https://github.com/").unwrap();
assert!(!looks_like_git_repository(&url));
let url = Url::parse("").unwrap_err();
assert_eq!(url.to_string(), "relative URL without a base");
let url = Url::parse("github.com/user/repo.git").unwrap_err();
assert_eq!(url.to_string(), "relative URL without a base");
let url = Url::parse("https://github.com/user/repo/extra.git").unwrap();
assert!(!looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user/repo.GIT").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user/repo.git?foo=bar").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://github.com/user/repo.git#readme").unwrap();
assert!(looks_like_git_repository(&url));
let url = Url::parse("https://github.com/pypa/pip/archive/1.3.1.zip#sha1=da9234ee9982d4bbb3c72346a6de940a148ea686").unwrap();
assert!(!looks_like_git_repository(&url));
}
#[test]
fn parse_url_ambiguous() {
assert_snapshot!(
VerbatimUrl::parse_url("https://user/name:password@domain/a/b/c").unwrap_err().to_string(),
@"ambiguous user/pass authority in URL (not percent-encoded?): https:***@domain/a/b/c"
);
assert_snapshot!(
VerbatimUrl::parse_url("https://user\\name:password@domain/a/b/c").unwrap_err().to_string(),
@"ambiguous user/pass authority in URL (not percent-encoded?): https:***@domain/a/b/c"
);
assert_snapshot!(
VerbatimUrl::parse_url("https://user#name:password@domain/a/b/c").unwrap_err().to_string(),
@"ambiguous user/pass authority in URL (not percent-encoded?): https:***@domain/a/b/c"
);
assert_snapshot!(
VerbatimUrl::parse_url("https://user.com/name:password@domain/a/b/c").unwrap_err().to_string(),
@"ambiguous user/pass authority in URL (not percent-encoded?): https:***@domain/a/b/c"
);
}
}
| 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-pep508/src/cursor.rs | crates/uv-pep508/src/cursor.rs | use std::fmt::{Display, Formatter};
use std::str::Chars;
use crate::{Pep508Error, Pep508ErrorSource, Pep508Url};
/// A [`Cursor`] over a string.
#[derive(Debug, Clone)]
pub(crate) struct Cursor<'a> {
input: &'a str,
chars: Chars<'a>,
pos: usize,
}
impl<'a> Cursor<'a> {
/// Convert from `&str`.
pub(crate) fn new(input: &'a str) -> Self {
Self {
input,
chars: input.chars(),
pos: 0,
}
}
/// Returns a new cursor starting at the given position.
pub(crate) fn at(self, pos: usize) -> Self {
Self {
input: self.input,
chars: self.input[pos..].chars(),
pos,
}
}
/// Returns the current byte position of the cursor.
pub(crate) fn pos(&self) -> usize {
self.pos
}
/// Returns a slice over the input string.
pub(crate) fn slice(&self, start: usize, len: usize) -> &str {
&self.input[start..start + len]
}
/// Peeks the next character and position from the input stream without consuming it.
pub(crate) fn peek(&self) -> Option<(usize, char)> {
self.chars.clone().next().map(|char| (self.pos, char))
}
/// Peeks the next character from the input stream without consuming it.
pub(crate) fn peek_char(&self) -> Option<char> {
self.chars.clone().next()
}
/// Eats the next character from the input stream if it matches the given token.
pub(crate) fn eat_char(&mut self, token: char) -> Option<usize> {
let (start_pos, peek_char) = self.peek()?;
if peek_char == token {
self.next();
Some(start_pos)
} else {
None
}
}
/// Consumes whitespace from the cursor.
pub(crate) fn eat_whitespace(&mut self) {
while let Some(char) = self.peek_char() {
if char.is_whitespace() {
self.next();
} else {
return;
}
}
}
/// Returns the next character and position from the input stream and consumes it.
pub(crate) fn next(&mut self) -> Option<(usize, char)> {
let pos = self.pos;
let char = self.chars.next()?;
self.pos += char.len_utf8();
Some((pos, char))
}
pub(crate) fn remaining(&self) -> usize {
self.chars.clone().count()
}
/// Peeks over the cursor as long as the condition is met, without consuming it.
pub(crate) fn peek_while(&mut self, condition: impl Fn(char) -> bool) -> (usize, usize) {
let peeker = self.chars.clone();
let start = self.pos();
let len = peeker.take_while(|c| condition(*c)).count();
(start, len)
}
/// Consumes characters from the cursor as long as the condition is met.
pub(crate) fn take_while(&mut self, condition: impl Fn(char) -> bool) -> (usize, usize) {
let start = self.pos();
let mut len = 0;
while let Some(char) = self.peek_char() {
if !condition(char) {
break;
}
self.next();
len += char.len_utf8();
}
(start, len)
}
/// Consumes characters from the cursor, raising an error if it doesn't match the given token.
pub(crate) fn next_expect_char<T: Pep508Url>(
&mut self,
expected: char,
span_start: usize,
) -> Result<(), Pep508Error<T>> {
match self.next() {
None => Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected '{expected}', found end of dependency specification"
)),
start: span_start,
len: 1,
input: self.to_string(),
}),
Some((_, value)) if value == expected => Ok(()),
Some((pos, other)) => Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected `{expected}`, found `{other}`"
)),
start: pos,
len: other.len_utf8(),
input: self.to_string(),
}),
}
}
}
impl Display for Cursor<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.input)
}
}
| 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-pep508/src/lib.rs | crates/uv-pep508/src/lib.rs | //! A library for [dependency specifiers](https://packaging.python.org/en/latest/specifications/dependency-specifiers/)
//! previously known as [PEP 508](https://peps.python.org/pep-0508/)
//!
//! ## Usage
//!
//! ```
//! use std::str::FromStr;
//! use uv_pep508::{Requirement, VerbatimUrl};
//! use uv_normalize::ExtraName;
//!
//! let marker = r#"requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8""#;
//! let dependency_specification = Requirement::<VerbatimUrl>::from_str(marker).unwrap();
//! assert_eq!(dependency_specification.name.as_ref(), "requests");
//! assert_eq!(dependency_specification.extras, vec![ExtraName::from_str("security").unwrap(), ExtraName::from_str("tests").unwrap()].into());
//! ```
#![warn(missing_docs)]
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::path::Path;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use thiserror::Error;
use url::Url;
use uv_cache_key::{CacheKey, CacheKeyHasher};
use uv_normalize::{ExtraName, PackageName};
use crate::cursor::Cursor;
pub use crate::marker::{
CanonicalMarkerValueExtra, CanonicalMarkerValueString, CanonicalMarkerValueVersion,
ContainsMarkerTree, ExtraMarkerTree, ExtraOperator, InMarkerTree, MarkerEnvironment,
MarkerEnvironmentBuilder, MarkerExpression, MarkerOperator, MarkerTree, MarkerTreeContents,
MarkerTreeKind, MarkerValue, MarkerValueExtra, MarkerValueList, MarkerValueString,
MarkerValueVersion, MarkerWarningKind, StringMarkerTree, StringVersion, VersionMarkerTree,
};
pub use crate::origin::RequirementOrigin;
#[cfg(feature = "non-pep508-extensions")]
pub use crate::unnamed::{UnnamedRequirement, UnnamedRequirementUrl};
pub use crate::verbatim_url::{
Scheme, VerbatimUrl, VerbatimUrlError, expand_env_vars, looks_like_git_repository,
split_scheme, strip_host,
};
/// Version and version specifiers used in requirements (reexport).
// https://github.com/konstin/pep508_rs/issues/19
pub use uv_pep440;
use uv_pep440::{VersionSpecifier, VersionSpecifiers};
mod cursor;
pub mod marker;
mod origin;
#[cfg(feature = "non-pep508-extensions")]
mod unnamed;
mod verbatim_url;
/// Error with a span attached. Not that those aren't `String` but `Vec<char>` indices.
#[derive(Debug)]
pub struct Pep508Error<T: Pep508Url = VerbatimUrl> {
/// Either we have an error string from our parser or an upstream error from `url`
pub message: Pep508ErrorSource<T>,
/// Span start index
pub start: usize,
/// Span length
pub len: usize,
/// The input string so we can print it underlined
pub input: String,
}
/// Either we have an error string from our parser or an upstream error from `url`
#[derive(Debug, Error)]
pub enum Pep508ErrorSource<T: Pep508Url = VerbatimUrl> {
/// An error from our parser.
#[error("{0}")]
String(String),
/// A URL parsing error.
#[error(transparent)]
UrlError(T::Err),
/// The version requirement is not supported.
#[error("{0}")]
UnsupportedRequirement(String),
}
impl<T: Pep508Url> Display for Pep508Error<T> {
/// Pretty formatting with underline.
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// We can use char indices here since it's a Vec<char>
let start_offset = self.input[..self.start]
.chars()
.filter_map(unicode_width::UnicodeWidthChar::width)
.sum::<usize>();
let underline_len = if self.start == self.input.len() {
// We also allow 0 here for convenience
assert!(
self.len <= 1,
"Can only go one past the input not {}",
self.len
);
1
} else {
self.input[self.start..self.start + self.len]
.chars()
.filter_map(unicode_width::UnicodeWidthChar::width)
.sum::<usize>()
};
write!(
f,
"{}\n{}\n{}{}",
self.message,
self.input,
" ".repeat(start_offset),
"^".repeat(underline_len)
)
}
}
/// We need this to allow anyhow's `.context()` and `AsDynError`.
impl<E: Error + Debug, T: Pep508Url<Err = E>> std::error::Error for Pep508Error<T> {}
/// A PEP 508 dependency specifier.
#[derive(Hash, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Requirement<T: Pep508Url = VerbatimUrl> {
/// The distribution name such as `requests` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
pub name: PackageName,
/// The list of extras such as `security`, `tests` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
pub extras: Box<[ExtraName]>,
/// The version specifier such as `>= 2.8.1`, `== 2.8.*` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
/// or a URL.
pub version_or_url: Option<VersionOrUrl<T>>,
/// The markers such as `python_version > "3.8"` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
/// Those are a nested and/or tree.
pub marker: MarkerTree,
/// The source file containing the requirement.
pub origin: Option<RequirementOrigin>,
}
impl<T: Pep508Url> Requirement<T> {
/// Removes the URL specifier from this requirement.
pub fn clear_url(&mut self) {
if matches!(self.version_or_url, Some(VersionOrUrl::Url(_))) {
self.version_or_url = None;
}
}
/// Returns a [`Display`] implementation that doesn't mask credentials.
pub fn displayable_with_credentials(&self) -> impl Display {
RequirementDisplay {
requirement: self,
display_credentials: true,
}
}
}
impl<T: Pep508Url + Display> Display for Requirement<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
RequirementDisplay {
requirement: self,
display_credentials: false,
}
.fmt(f)
}
}
struct RequirementDisplay<'a, T>
where
T: Pep508Url + Display,
{
requirement: &'a Requirement<T>,
display_credentials: bool,
}
impl<T: Pep508Url + Display> Display for RequirementDisplay<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.requirement.name)?;
if !self.requirement.extras.is_empty() {
write!(
f,
"[{}]",
self.requirement
.extras
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",")
)?;
}
if let Some(version_or_url) = &self.requirement.version_or_url {
match version_or_url {
VersionOrUrl::VersionSpecifier(version_specifier) => {
let version_specifier: Vec<String> =
version_specifier.iter().map(ToString::to_string).collect();
write!(f, "{}", version_specifier.join(","))?;
}
VersionOrUrl::Url(url) => {
let url_string = if self.display_credentials {
url.displayable_with_credentials().to_string()
} else {
url.to_string()
};
// We add the space for markers later if necessary
write!(f, " @ {url_string}")?;
}
}
}
if let Some(marker) = self.requirement.marker.contents() {
write!(f, " ; {marker}")?;
}
Ok(())
}
}
/// <https://github.com/serde-rs/serde/issues/908#issuecomment-298027413>
impl<'de, T: Pep508Url> Deserialize<'de> for Requirement<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct RequirementVisitor<T>(std::marker::PhantomData<T>);
impl<T: Pep508Url> serde::de::Visitor<'_> for RequirementVisitor<T> {
type Value = Requirement<T>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string containing a PEP 508 requirement")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
FromStr::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(RequirementVisitor(std::marker::PhantomData))
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl<T: Pep508Url> Serialize for Requirement<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl<T: Pep508Url> CacheKey for Requirement<T> {
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.name.as_str().cache_key(state);
self.extras.len().cache_key(state);
for extra in &self.extras {
extra.as_str().cache_key(state);
}
// TODO(zanieb): We inline cache key handling for the child types here, but we could
// move the implementations to the children. The intent here was to limit the scope of
// types exposing the `CacheKey` trait for now.
if let Some(version_or_url) = &self.version_or_url {
1u8.cache_key(state);
match version_or_url {
VersionOrUrl::VersionSpecifier(spec) => {
0u8.cache_key(state);
spec.len().cache_key(state);
for specifier in spec.iter() {
specifier.operator().as_str().cache_key(state);
specifier.version().cache_key(state);
}
}
VersionOrUrl::Url(url) => {
1u8.cache_key(state);
url.cache_key(state);
}
}
} else {
0u8.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);
}
// `origin` is intentionally omitted
}
}
impl<T: Pep508Url> Requirement<T> {
/// Returns whether the markers apply for the given environment
pub fn evaluate_markers(&self, env: &MarkerEnvironment, extras: &[ExtraName]) -> bool {
self.marker.evaluate(env, extras)
}
/// Return the requirement with an additional marker added, to require the given extra.
///
/// For example, given `flask >= 2.0.2`, calling `with_extra_marker("dotenv")` would return
/// `flask >= 2.0.2 ; extra == "dotenv"`.
#[must_use]
pub fn with_extra_marker(mut self, extra: &ExtraName) -> Self {
self.marker
.and(MarkerTree::expression(MarkerExpression::Extra {
operator: ExtraOperator::Equal,
name: MarkerValueExtra::Extra(extra.clone()),
}));
self
}
/// Set the source file containing the requirement.
#[must_use]
pub fn with_origin(self, origin: RequirementOrigin) -> Self {
Self {
origin: Some(origin),
..self
}
}
}
/// Type to parse URLs from `name @ <url>` into. Defaults to [`Url`].
pub trait Pep508Url: Display + Debug + Sized + CacheKey {
/// String to URL parsing error
type Err: Error + Debug;
/// Parse a url from `name @ <url>`. Defaults to [`Url::parse_url`].
fn parse_url(url: &str, working_dir: Option<&Path>) -> Result<Self, Self::Err>;
/// Returns a [`Display`] implementation that doesn't mask credentials.
fn displayable_with_credentials(&self) -> impl Display;
}
impl Pep508Url for Url {
type Err = url::ParseError;
fn parse_url(url: &str, _working_dir: Option<&Path>) -> Result<Self, Self::Err> {
Self::parse(url)
}
fn displayable_with_credentials(&self) -> impl Display {
self
}
}
/// A reporter for warnings that occur during marker parsing or evaluation.
pub trait Reporter {
/// Report a warning.
fn report(&mut self, kind: MarkerWarningKind, warning: String);
}
impl<F> Reporter for F
where
F: FnMut(MarkerWarningKind, String),
{
fn report(&mut self, kind: MarkerWarningKind, warning: String) {
(self)(kind, warning);
}
}
/// A simple [`Reporter`] that logs to tracing when the `tracing` feature is enabled.
pub struct TracingReporter;
impl Reporter for TracingReporter {
#[allow(unused_variables)]
fn report(&mut self, _kind: MarkerWarningKind, message: String) {
#[cfg(feature = "tracing")]
{
tracing::warn!("{message}");
}
}
}
#[cfg(feature = "schemars")]
impl<T: Pep508Url> schemars::JsonSchema for Requirement<T> {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("Requirement")
}
fn json_schema(_gen: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"description": "A PEP 508 dependency specifier, e.g., `ruff >= 0.6.0`"
})
}
}
impl<T: Pep508Url> FromStr for Requirement<T> {
type Err = Pep508Error<T>;
/// Parse a [Dependency Specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/).
fn from_str(input: &str) -> Result<Self, Self::Err> {
parse_pep508_requirement::<T>(&mut Cursor::new(input), None, &mut TracingReporter)
}
}
impl<T: Pep508Url> Requirement<T> {
/// Parse a [Dependency Specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/).
pub fn parse(input: &str, working_dir: impl AsRef<Path>) -> Result<Self, Pep508Error<T>> {
parse_pep508_requirement(
&mut Cursor::new(input),
Some(working_dir.as_ref()),
&mut TracingReporter,
)
}
/// Parse a [Dependency Specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/)
/// with the given reporter for warnings.
pub fn parse_reporter(
input: &str,
working_dir: impl AsRef<Path>,
reporter: &mut impl Reporter,
) -> Result<Self, Pep508Error<T>> {
parse_pep508_requirement(
&mut Cursor::new(input),
Some(working_dir.as_ref()),
reporter,
)
}
}
/// A list of [`ExtraName`] that can be attached to a [`Requirement`].
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct Extras(Vec<ExtraName>);
impl Extras {
/// Parse a list of extras.
pub fn parse<T: Pep508Url>(input: &str) -> Result<Self, Pep508Error<T>> {
Ok(Self(parse_extras_cursor(&mut Cursor::new(input))?))
}
}
/// The actual version specifier or URL to install.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum VersionOrUrl<T: Pep508Url = VerbatimUrl> {
/// A PEP 440 version specifier set
VersionSpecifier(VersionSpecifiers),
/// A installable URL
Url(T),
}
impl<T: Pep508Url> Display for VersionOrUrl<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::VersionSpecifier(version_specifier) => Display::fmt(version_specifier, f),
Self::Url(url) => Display::fmt(url, f),
}
}
}
/// Unowned version specifier or URL to install.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum VersionOrUrlRef<'a, T: Pep508Url = VerbatimUrl> {
/// A PEP 440 version specifier set
VersionSpecifier(&'a VersionSpecifiers),
/// A installable URL
Url(&'a T),
}
impl<T: Pep508Url> Display for VersionOrUrlRef<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::VersionSpecifier(version_specifier) => Display::fmt(version_specifier, f),
Self::Url(url) => Display::fmt(url, f),
}
}
}
impl<'a> From<&'a VersionOrUrl> for VersionOrUrlRef<'a> {
fn from(value: &'a VersionOrUrl) -> Self {
match value {
VersionOrUrl::VersionSpecifier(version_specifier) => {
VersionOrUrlRef::VersionSpecifier(version_specifier)
}
VersionOrUrl::Url(url) => VersionOrUrlRef::Url(url),
}
}
}
fn parse_name<T: Pep508Url>(cursor: &mut Cursor) -> Result<PackageName, Pep508Error<T>> {
// https://peps.python.org/pep-0508/#names
// ^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$ with re.IGNORECASE
let start = cursor.pos();
if let Some((index, char)) = cursor.next() {
if !matches!(char, 'A'..='Z' | 'a'..='z' | '0'..='9') {
// Check if the user added a filesystem path without a package name. pip supports this
// in `requirements.txt`, but it doesn't adhere to the PEP 508 grammar.
let mut clone = cursor.clone().at(start);
return if looks_like_unnamed_requirement(&mut clone) {
Err(Pep508Error {
message: Pep508ErrorSource::UnsupportedRequirement("URL requirement must be preceded by a package name. Add the name of the package before the URL (e.g., `package_name @ /path/to/file`).".to_string()),
start,
len: clone.pos() - start,
input: clone.to_string(),
})
} else {
Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected package name starting with an alphanumeric character, found `{char}`"
)),
start: index,
len: char.len_utf8(),
input: cursor.to_string(),
})
};
}
} else {
return Err(Pep508Error {
message: Pep508ErrorSource::String("Empty field is not allowed for PEP508".to_string()),
start: 0,
len: 1,
input: cursor.to_string(),
});
}
cursor.take_while(|char| matches!(char, 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_'));
let len = cursor.pos() - start;
// Unwrap-safety: The block above ensures that there is at least one char in the buffer.
let last = cursor.slice(start, len).chars().last().unwrap();
// [.-_] can't be the final character
if !matches!(last, 'A'..='Z' | 'a'..='z' | '0'..='9') {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Package name must end with an alphanumeric character, not `{last}`"
)),
start: cursor.pos() - last.len_utf8(),
len: last.len_utf8(),
input: cursor.to_string(),
});
}
Ok(PackageName::from_str(cursor.slice(start, len)).unwrap())
}
/// Parse a potential URL from the [`Cursor`], advancing the [`Cursor`] to the end of the URL.
///
/// Returns `true` if the URL appears to be a viable unnamed requirement, and `false` otherwise.
fn looks_like_unnamed_requirement(cursor: &mut Cursor) -> bool {
// Read the entire path.
let (start, len) = cursor.take_while(|char| !char.is_whitespace());
let url = cursor.slice(start, len);
// Expand any environment variables in the path.
let expanded = expand_env_vars(url);
// Strip extras.
let url = split_extras(&expanded)
.map(|(url, _)| url)
.unwrap_or(&expanded);
// Analyze the path.
let mut chars = url.chars();
let Some(first_char) = chars.next() else {
return false;
};
// Ex) `/bin/ls`
if first_char == '\\' || first_char == '/' || first_char == '.' {
return true;
}
// Ex) `https://` or `C:`
if split_scheme(url).is_some() {
return true;
}
// Ex) `foo/bar`
if url.contains('/') || url.contains('\\') {
return true;
}
// Ex) `foo.tar.gz`
if looks_like_archive(url) {
return true;
}
false
}
/// Returns `true` if a file looks like an archive.
///
/// See <https://github.com/pypa/pip/blob/111eed14b6e9fba7c78a5ec2b7594812d17b5d2b/src/pip/_internal/utils/filetypes.py#L8>
/// for the list of supported archive extensions.
fn looks_like_archive(file: impl AsRef<Path>) -> bool {
let file = file.as_ref();
// E.g., `gz` in `foo.tar.gz`
let Some(extension) = file.extension().and_then(|ext| ext.to_str()) else {
return false;
};
// E.g., `tar` in `foo.tar.gz`
let pre_extension = file
.file_stem()
.and_then(|stem| Path::new(stem).extension().and_then(|ext| ext.to_str()));
matches!(
(pre_extension, extension),
(_, "whl" | "tbz" | "txz" | "tlz" | "zip" | "tgz" | "tar")
| (Some("tar"), "bz2" | "xz" | "lz" | "lzma" | "gz")
)
}
/// parses extras in the `[extra1,extra2] format`
fn parse_extras_cursor<T: Pep508Url>(
cursor: &mut Cursor,
) -> Result<Vec<ExtraName>, Pep508Error<T>> {
let Some(bracket_pos) = cursor.eat_char('[') else {
return Ok(vec![]);
};
cursor.eat_whitespace();
let mut extras = Vec::new();
let mut is_first_iteration = true;
loop {
// End of the extras section. (Empty extras are allowed.)
if let Some(']') = cursor.peek_char() {
cursor.next();
break;
}
// Comma separator
match (cursor.peek(), is_first_iteration) {
// For the first iteration, we don't expect a comma.
(Some((pos, ',')), true) => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(
"Expected either alphanumerical character (starting the extra name) or `]` (ending the extras section), found `,`".to_string()
),
start: pos,
len: 1,
input: cursor.to_string(),
});
}
// For the other iterations, the comma is required.
(Some((_, ',')), false) => {
cursor.next();
}
(Some((pos, other)), false) => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected either `,` (separating extras) or `]` (ending the extras section), found `{other}`"
)),
start: pos,
len: 1,
input: cursor.to_string(),
});
}
_ => {}
}
// wsp* before the identifier
cursor.eat_whitespace();
let mut buffer = String::new();
let early_eof_error = Pep508Error {
message: Pep508ErrorSource::String(
"Missing closing bracket (expected ']', found end of dependency specification)"
.to_string(),
),
start: bracket_pos,
len: 1,
input: cursor.to_string(),
};
// First char of the identifier.
match cursor.next() {
// letterOrDigit
Some((_, alphanumeric @ ('a'..='z' | 'A'..='Z' | '0'..='9'))) => {
buffer.push(alphanumeric);
}
Some((pos, other)) => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected an alphanumeric character starting the extra name, found `{other}`"
)),
start: pos,
len: other.len_utf8(),
input: cursor.to_string(),
});
}
None => return Err(early_eof_error),
}
// Parse from the second char of the identifier
// We handle the illegal character case below
// identifier_end = letterOrDigit | (('-' | '_' | '.' )* letterOrDigit)
// identifier_end*
let (start, len) = cursor
.take_while(|char| matches!(char, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.'));
buffer.push_str(cursor.slice(start, len));
match cursor.peek() {
Some((pos, char)) if char != ',' && char != ']' && !char.is_whitespace() => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Invalid character in extras name, expected an alphanumeric character, `-`, `_`, `.`, `,` or `]`, found `{char}`"
)),
start: pos,
len: char.len_utf8(),
input: cursor.to_string(),
});
}
_ => {}
}
// wsp* after the identifier
cursor.eat_whitespace();
// Add the parsed extra
extras.push(
ExtraName::from_str(&buffer)
.expect("`ExtraName` validation should match PEP 508 parsing"),
);
is_first_iteration = false;
}
Ok(extras)
}
/// Parse a raw string for a URL requirement, which could be either a URL or a local path, and which
/// could contain unexpanded environment variables.
///
/// When parsing, we eat characters until we see any of the following:
/// - A newline.
/// - A semicolon (marker) or hash (comment), _preceded_ by a space. We parse the URL until the last
/// non-whitespace character (inclusive).
/// - A semicolon (marker) or hash (comment) _followed_ by a space. We treat this as an error, since
/// the end of the URL is ambiguous.
///
/// For example:
/// - `https://pypi.org/project/requests/...`
/// - `file:///home/ferris/project/scripts/...`
/// - `file:../editable/`
/// - `../editable/`
/// - `../path to editable/`
/// - `https://download.pytorch.org/whl/torch_stable.html`
fn parse_url<T: Pep508Url>(
cursor: &mut Cursor,
working_dir: Option<&Path>,
) -> Result<T, Pep508Error<T>> {
// wsp*
cursor.eat_whitespace();
// <URI_reference>
let (start, len) = {
let start = cursor.pos();
let mut len = 0;
while let Some((_, c)) = cursor.next() {
// If we see a line break, we're done.
if matches!(c, '\r' | '\n') {
break;
}
// If we see top-level whitespace, check if it's followed by a semicolon or hash. If so,
// end the URL at the last non-whitespace character.
if c.is_whitespace() {
let mut cursor = cursor.clone();
cursor.eat_whitespace();
if matches!(cursor.peek_char(), None | Some(';' | '#')) {
break;
}
}
len += c.len_utf8();
// If we see a top-level semicolon or hash followed by whitespace, we're done.
if cursor.peek_char().is_some_and(|c| matches!(c, ';' | '#')) {
let mut cursor = cursor.clone();
cursor.next();
if cursor.peek_char().is_some_and(char::is_whitespace) {
break;
}
}
}
(start, len)
};
let url = cursor.slice(start, len);
if url.is_empty() {
return Err(Pep508Error {
message: Pep508ErrorSource::String("Expected URL".to_string()),
start,
len,
input: cursor.to_string(),
});
}
let url = T::parse_url(url, working_dir).map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?;
Ok(url)
}
/// Identify the extras in a relative URL (e.g., `../editable[dev]`).
///
/// Pip uses `m = re.match(r'^(.+)(\[[^]]+])$', path)`. Our strategy is:
/// - If the string ends with a closing bracket (`]`)...
/// - Iterate backwards until you find the open bracket (`[`)...
/// - But abort if you find another closing bracket (`]`) first.
pub fn split_extras(given: &str) -> Option<(&str, &str)> {
let mut chars = given.char_indices().rev();
// If the string ends with a closing bracket (`]`)...
if !matches!(chars.next(), Some((_, ']'))) {
return None;
}
// Iterate backwards until you find the open bracket (`[`)...
let (index, _) = chars
.take_while(|(_, c)| *c != ']')
.find(|(_, c)| *c == '[')?;
Some(given.split_at(index))
}
/// PEP 440 wrapper
fn parse_specifier<T: Pep508Url>(
cursor: &mut Cursor,
buffer: &str,
start: usize,
end: usize,
) -> Result<VersionSpecifier, Pep508Error<T>> {
VersionSpecifier::from_str(buffer).map_err(|err| Pep508Error {
message: Pep508ErrorSource::String(err.to_string()),
start,
len: end - start,
input: cursor.to_string(),
})
}
/// Such as `>=1.19,<2.0`, either delimited by the end of the specifier or a `;` for the marker part
///
/// ```text
/// version_one (wsp* ',' version_one)*
/// ```
fn parse_version_specifier<T: Pep508Url>(
cursor: &mut Cursor,
) -> Result<Option<VersionOrUrl<T>>, Pep508Error<T>> {
let mut start = cursor.pos();
let mut specifiers = Vec::new();
let mut buffer = String::new();
let requirement_kind = loop {
match cursor.peek() {
Some((end, ',')) => {
let specifier = parse_specifier(cursor, &buffer, start, end)?;
specifiers.push(specifier);
buffer.clear();
cursor.next();
start = end + 1;
}
Some((_, ';')) | None => {
let end = cursor.pos();
let specifier = parse_specifier(cursor, &buffer, start, end)?;
specifiers.push(specifier);
break Some(VersionOrUrl::VersionSpecifier(
specifiers.into_iter().collect(),
));
}
Some((_, char)) => {
buffer.push(char);
cursor.next();
}
}
};
Ok(requirement_kind)
}
/// Such as `(>=1.19,<2.0)`
///
/// ```text
/// '(' version_one (wsp* ',' version_one)* ')'
/// ```
fn parse_version_specifier_parentheses<T: Pep508Url>(
cursor: &mut Cursor,
) -> Result<Option<VersionOrUrl<T>>, Pep508Error<T>> {
let brace_pos = cursor.pos();
cursor.next();
// Makes for slightly better error underline
cursor.eat_whitespace();
let mut start = cursor.pos();
let mut specifiers = Vec::new();
let mut buffer = String::new();
let requirement_kind = loop {
match cursor.next() {
Some((end, ',')) => {
let specifier =
parse_specifier(cursor, &buffer, start, end)?;
specifiers.push(specifier);
buffer.clear();
start = end + 1;
}
Some((end, ')')) => {
let specifier = parse_specifier(cursor, &buffer, start, end)?;
specifiers.push(specifier);
break Some(VersionOrUrl::VersionSpecifier(specifiers.into_iter().collect()));
}
Some((_, char)) => buffer.push(char),
None => return Err(Pep508Error {
message: Pep508ErrorSource::String("Missing closing parenthesis (expected ')', found end of dependency specification)".to_string()),
start: brace_pos,
len: 1,
input: cursor.to_string(),
}),
}
};
Ok(requirement_kind)
}
/// Parse a PEP 508-compliant [dependency specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers).
fn parse_pep508_requirement<T: Pep508Url>(
cursor: &mut Cursor,
working_dir: Option<&Path>,
reporter: &mut impl Reporter,
) -> Result<Requirement<T>, Pep508Error<T>> {
let start = cursor.pos();
// Technically, the grammar is:
// ```text
// name_req = name wsp* extras? wsp* versionspec? wsp* quoted_marker?
// url_req = name wsp* extras? wsp* urlspec wsp+ quoted_marker?
// specification = wsp* ( url_req | name_req ) wsp*
// ```
// So we can merge this into:
// ```text
// specification = wsp* name wsp* extras? wsp* (('@' wsp* url_req) | ('(' versionspec ')') | (versionspec)) wsp* (';' wsp* marker)? wsp*
// ```
// Where the extras start with '[' if any, then we have '@', '(' or one of the version comparison
// operators. Markers start with ';' if any
// wsp*
cursor.eat_whitespace();
// name
let name_start = cursor.pos();
| 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-pep508/src/origin.rs | crates/uv-pep508/src/origin.rs | use std::path::{Path, PathBuf};
use uv_normalize::{GroupName, PackageName};
/// The origin of a dependency, e.g., a `-r requirements.txt` file.
#[derive(
Hash, Debug, Clone, Eq, PartialEq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum RequirementOrigin {
/// The requirement was provided via a standalone file (e.g., a `requirements.txt` file).
File(PathBuf),
/// The requirement was provided via a local project (e.g., a `pyproject.toml` file).
Project(PathBuf, PackageName),
/// The requirement was provided via a local project's group (e.g., a `pyproject.toml` file).
Group(PathBuf, Option<PackageName>, GroupName),
/// The requirement was provided via a workspace.
Workspace,
}
impl RequirementOrigin {
/// Returns the path of the requirement origin.
pub fn path(&self) -> &Path {
match self {
Self::File(path) => path.as_path(),
Self::Project(path, _) => path.as_path(),
Self::Group(path, _, _) => path.as_path(),
// Multiple toml are merged and difficult to track files where Requirement is defined. Returns a dummy path instead.
Self::Workspace => Path::new("(workspace)"),
}
}
}
| 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-pep508/src/unnamed.rs | crates/uv-pep508/src/unnamed.rs | use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
use std::path::Path;
use std::str::FromStr;
use uv_fs::normalize_url_path;
use uv_normalize::ExtraName;
use crate::marker::parse;
use crate::{
Cursor, MarkerEnvironment, MarkerTree, Pep508Error, Pep508ErrorSource, Pep508Url, Reporter,
RequirementOrigin, Scheme, TracingReporter, VerbatimUrl, VerbatimUrlError, expand_env_vars,
parse_extras_cursor, split_extras, split_scheme, strip_host,
};
/// An extension over [`Pep508Url`] that also supports parsing unnamed requirements, namely paths.
///
/// The error type is fixed to the same as the [`Pep508Url`] impl error.
pub trait UnnamedRequirementUrl: Pep508Url {
/// Parse a URL from a relative or absolute path.
fn parse_path(path: impl AsRef<Path>, working_dir: impl AsRef<Path>)
-> Result<Self, Self::Err>;
/// Parse a URL from an absolute path.
fn parse_absolute_path(path: impl AsRef<Path>) -> Result<Self, Self::Err>;
/// Parse a URL from a string.
fn parse_unnamed_url(given: impl AsRef<str>) -> Result<Self, Self::Err>;
/// Set the verbatim representation of the URL.
#[must_use]
fn with_given(self, given: impl AsRef<str>) -> Self;
/// Return the original string as given by the user, if available.
fn given(&self) -> Option<&str>;
}
impl UnnamedRequirementUrl for VerbatimUrl {
fn parse_path(
path: impl AsRef<Path>,
working_dir: impl AsRef<Path>,
) -> Result<Self, VerbatimUrlError> {
Self::from_path(path, working_dir)
}
fn parse_absolute_path(path: impl AsRef<Path>) -> Result<Self, Self::Err> {
Self::from_absolute_path(path)
}
fn parse_unnamed_url(given: impl AsRef<str>) -> Result<Self, Self::Err> {
Self::parse_url(given)
}
fn with_given(self, given: impl AsRef<str>) -> Self {
self.with_given(given)
}
fn given(&self) -> Option<&str> {
self.given()
}
}
/// A PEP 508-like, direct URL dependency specifier without a package name.
///
/// In a `requirements.txt` file, the name of the package is optional for direct URL
/// dependencies. This isn't compliant with PEP 508, but is common in `requirements.txt`, which
/// is implementation-defined.
#[derive(Hash, Debug, Clone, Eq, PartialEq)]
pub struct UnnamedRequirement<ReqUrl: UnnamedRequirementUrl = VerbatimUrl> {
/// The direct URL that defines the version specifier.
pub url: ReqUrl,
/// The list of extras such as `security`, `tests` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
pub extras: Box<[ExtraName]>,
/// The markers such as `python_version > "3.8"` in
/// `requests [security,tests] >= 2.8.1, == 2.8.* ; python_version > "3.8"`.
/// Those are a nested and/or tree.
pub marker: MarkerTree,
/// The source file containing the requirement.
pub origin: Option<RequirementOrigin>,
}
impl<Url: UnnamedRequirementUrl> UnnamedRequirement<Url> {
/// Returns whether the markers apply for the given environment
pub fn evaluate_markers(&self, env: &MarkerEnvironment, extras: &[ExtraName]) -> bool {
self.evaluate_optional_environment(Some(env), extras)
}
/// Returns whether the markers apply for the given environment
pub fn evaluate_optional_environment(
&self,
env: Option<&MarkerEnvironment>,
extras: &[ExtraName],
) -> bool {
self.marker.evaluate_optional_environment(env, extras)
}
/// Set the source file containing the requirement.
#[must_use]
pub fn with_origin(self, origin: RequirementOrigin) -> Self {
Self {
origin: Some(origin),
..self
}
}
/// Parse a PEP 508-like direct URL requirement without a package name.
pub fn parse(
input: &str,
working_dir: impl AsRef<Path>,
reporter: &mut impl Reporter,
) -> Result<Self, Pep508Error<Url>> {
parse_unnamed_requirement(
&mut Cursor::new(input),
Some(working_dir.as_ref()),
reporter,
)
}
}
impl<Url: UnnamedRequirementUrl> Display for UnnamedRequirement<Url> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.url)?;
if !self.extras.is_empty() {
write!(
f,
"[{}]",
self.extras
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",")
)?;
}
if let Some(marker) = self.marker.contents() {
write!(f, " ; {marker}")?;
}
Ok(())
}
}
impl<Url: UnnamedRequirementUrl> FromStr for UnnamedRequirement<Url> {
type Err = Pep508Error<Url>;
/// Parse a PEP 508-like direct URL requirement without a package name.
fn from_str(input: &str) -> Result<Self, Self::Err> {
parse_unnamed_requirement(&mut Cursor::new(input), None, &mut TracingReporter)
}
}
/// Parse a PEP 508-like direct URL specifier without a package name.
///
/// Unlike pip, we allow extras on URLs and paths.
fn parse_unnamed_requirement<Url: UnnamedRequirementUrl>(
cursor: &mut Cursor,
working_dir: Option<&Path>,
reporter: &mut impl Reporter,
) -> Result<UnnamedRequirement<Url>, Pep508Error<Url>> {
cursor.eat_whitespace();
// Parse the URL itself, along with any extras.
let (url, extras) = parse_unnamed_url::<Url>(cursor, working_dir)?;
// wsp*
cursor.eat_whitespace();
// quoted_marker?
let marker = if cursor.peek_char() == Some(';') {
// Skip past the semicolon
cursor.next();
parse::parse_markers_cursor(cursor, reporter)?
} else {
None
};
// wsp*
cursor.eat_whitespace();
if let Some((pos, char)) = cursor.next() {
let message = if char == '#' {
format!(
r"Expected end of input or `;`, found `{char}`; comments must be preceded by a leading space"
)
} else if marker.is_none() {
format!(r"Expected end of input or `;`, found `{char}`")
} else {
format!(r"Expected end of input, found `{char}`")
};
return Err(Pep508Error {
message: Pep508ErrorSource::String(message),
start: pos,
len: char.len_utf8(),
input: cursor.to_string(),
});
}
Ok(UnnamedRequirement {
url,
extras: extras.into_boxed_slice(),
marker: marker.unwrap_or_default(),
origin: None,
})
}
/// Create a `VerbatimUrl` to represent the requirement, and extracts any extras at the end of the
/// URL, to comply with the non-PEP 508 extensions.
///
/// For example:
/// - `file:///home/ferris/project/scripts/...`
/// - `file:../editable/`
/// - `../editable/`
/// - `https://download.pytorch.org/whl/torch_stable.html`
fn preprocess_unnamed_url<Url: UnnamedRequirementUrl>(
url: &str,
#[cfg_attr(not(feature = "non-pep508-extensions"), allow(unused))] working_dir: Option<&Path>,
cursor: &Cursor,
start: usize,
len: usize,
) -> Result<(Url, Vec<ExtraName>), Pep508Error<Url>> {
// Split extras _before_ expanding the URL. We assume that the extras are not environment
// variables. If we parsed the extras after expanding the URL, then the verbatim representation
// of the URL itself would be ambiguous, since it would consist of the environment variable,
// which would expand to _more_ than the URL.
let (url, extras) = if let Some((url, extras)) = split_extras(url) {
(url, Some(extras))
} else {
(url, None)
};
// Parse the extras, if provided.
let extras = if let Some(extras) = extras {
parse_extras_cursor(&mut Cursor::new(extras)).map_err(|err| Pep508Error {
message: err.message,
start: start + url.len() + err.start,
len: err.len,
input: cursor.to_string(),
})?
} else {
vec![]
};
// Expand environment variables in the URL.
let expanded = expand_env_vars(url);
if let Some((scheme, path)) = split_scheme(&expanded) {
match Scheme::parse(scheme) {
// Ex) `file:///home/ferris/project/scripts/...`, `file://localhost/home/ferris/project/scripts/...`, or `file:../ferris/`
Some(Scheme::File) => {
// Strip the leading slashes, along with the `localhost` host, if present.
let path = strip_host(path);
// Transform, e.g., `/C:/Users/ferris/wheel-0.42.0.tar.gz` to `C:\Users\ferris\wheel-0.42.0.tar.gz`.
let path = normalize_url_path(path);
#[cfg(feature = "non-pep508-extensions")]
if let Some(working_dir) = working_dir {
let url = Url::parse_path(path.as_ref(), working_dir)
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
return Ok((url, extras));
}
let url = Url::parse_absolute_path(path.as_ref())
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
Ok((url, extras))
}
// Ex) `https://download.pytorch.org/whl/torch_stable.html`
Some(_) => {
// Ex) `https://download.pytorch.org/whl/torch_stable.html`
let url = Url::parse_unnamed_url(expanded.as_ref())
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
Ok((url, extras))
}
// Ex) `C:\Users\ferris\wheel-0.42.0.tar.gz`
_ => {
if let Some(working_dir) = working_dir {
let url = Url::parse_path(expanded.as_ref(), working_dir)
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
return Ok((url, extras));
}
let url = Url::parse_absolute_path(expanded.as_ref())
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
Ok((url, extras))
}
}
} else {
// Ex) `../editable/`
if let Some(working_dir) = working_dir {
let url = Url::parse_path(expanded.as_ref(), working_dir)
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
return Ok((url, extras));
}
let url = Url::parse_absolute_path(expanded.as_ref())
.map_err(|err| Pep508Error {
message: Pep508ErrorSource::UrlError(err),
start,
len,
input: cursor.to_string(),
})?
.with_given(url);
Ok((url, extras))
}
}
/// Like [`crate::parse_url`], but allows for extras to be present at the end of the URL, to comply
/// with the non-PEP 508 extensions.
///
/// When parsing, we eat characters until we see any of the following:
/// - A newline.
/// - A semicolon (marker) or hash (comment), _preceded_ by a space. We parse the URL until the last
/// non-whitespace character (inclusive).
/// - A semicolon (marker) or hash (comment) _followed_ by a space. We treat this as an error, since
/// the end of the URL is ambiguous.
///
/// URLs can include extras at the end, enclosed in square brackets.
///
/// For example:
/// - `https://download.pytorch.org/whl/torch_stable.html[dev]`
/// - `../editable[dev]`
/// - `https://download.pytorch.org/whl/torch_stable.html ; python_version > "3.8"`
/// - `https://download.pytorch.org/whl/torch_stable.html # this is a comment`
fn parse_unnamed_url<Url: UnnamedRequirementUrl>(
cursor: &mut Cursor,
working_dir: Option<&Path>,
) -> Result<(Url, Vec<ExtraName>), Pep508Error<Url>> {
// wsp*
cursor.eat_whitespace();
// <URI_reference>
let (start, len) = {
let start = cursor.pos();
let mut len = 0;
let mut depth = 0u32;
while let Some((_, c)) = cursor.next() {
// If we see a line break, we're done.
if matches!(c, '\r' | '\n') {
break;
}
// Track the depth of brackets.
if c == '[' {
depth = depth.saturating_add(1);
} else if c == ']' {
depth = depth.saturating_sub(1);
}
// If we see top-level whitespace, check if it's followed by a semicolon or hash. If so,
// end the URL at the last non-whitespace character.
if depth == 0 && c.is_whitespace() {
let mut cursor = cursor.clone();
cursor.eat_whitespace();
if matches!(cursor.peek_char(), None | Some(';' | '#')) {
break;
}
}
len += c.len_utf8();
// If we see a top-level semicolon or hash followed by whitespace, we're done.
if depth == 0 && cursor.peek_char().is_some_and(|c| matches!(c, ';' | '#')) {
let mut cursor = cursor.clone();
cursor.next();
if cursor.peek_char().is_some_and(char::is_whitespace) {
break;
}
}
}
(start, len)
};
let url = cursor.slice(start, len);
if url.is_empty() {
return Err(Pep508Error {
message: Pep508ErrorSource::String("Expected URL".to_string()),
start,
len,
input: cursor.to_string(),
});
}
let url = preprocess_unnamed_url(url, working_dir, cursor, start, len)?;
Ok(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-pep508/src/marker/environment.rs | crates/uv-pep508/src/marker/environment.rs | use std::sync::Arc;
use uv_pep440::{Version, VersionParseError};
use crate::{CanonicalMarkerValueString, CanonicalMarkerValueVersion, StringVersion};
/// The marker values for a python interpreter, normally the current one
///
/// <https://packaging.python.org/en/latest/specifications/dependency-specifiers/#environment-markers>
#[allow(missing_docs, clippy::unsafe_derive_deserialize)]
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct MarkerEnvironment {
#[serde(flatten)]
inner: Arc<MarkerEnvironmentInner>,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
struct MarkerEnvironmentInner {
implementation_name: String,
implementation_version: StringVersion,
os_name: String,
platform_machine: String,
platform_python_implementation: String,
platform_release: String,
platform_system: String,
platform_version: String,
python_full_version: StringVersion,
python_version: StringVersion,
sys_platform: String,
}
impl MarkerEnvironment {
/// Returns of the PEP 440 version typed value of the key in the current environment
pub fn get_version(&self, key: CanonicalMarkerValueVersion) -> &Version {
match key {
CanonicalMarkerValueVersion::ImplementationVersion => {
&self.implementation_version().version
}
CanonicalMarkerValueVersion::PythonFullVersion => &self.python_full_version().version,
}
}
/// Returns of the stringly typed value of the key in the current environment
pub fn get_string(&self, key: CanonicalMarkerValueString) -> &str {
match key {
CanonicalMarkerValueString::ImplementationName => self.implementation_name(),
CanonicalMarkerValueString::OsName => self.os_name(),
CanonicalMarkerValueString::PlatformMachine => self.platform_machine(),
CanonicalMarkerValueString::PlatformPythonImplementation => {
self.platform_python_implementation()
}
CanonicalMarkerValueString::PlatformRelease => self.platform_release(),
CanonicalMarkerValueString::PlatformSystem => self.platform_system(),
CanonicalMarkerValueString::PlatformVersion => self.platform_version(),
CanonicalMarkerValueString::SysPlatform => self.sys_platform(),
}
}
}
/// APIs for retrieving specific parts of a marker environment.
impl MarkerEnvironment {
/// Returns the name of the Python implementation for this environment.
///
/// This is equivalent to `sys.implementation.name`.
///
/// Some example values are: `cpython`.
#[inline]
pub fn implementation_name(&self) -> &str {
&self.inner.implementation_name
}
/// Returns the Python implementation version for this environment.
///
/// This value is derived from `sys.implementation.version`. See [PEP 508
/// environment markers] for full details.
///
/// This is equivalent to `sys.implementation.name`.
///
/// Some example values are: `3.4.0`, `3.5.0b1`.
///
/// [PEP 508 environment markers]: https://peps.python.org/pep-0508/#environment-markers
#[inline]
pub fn implementation_version(&self) -> &StringVersion {
&self.inner.implementation_version
}
/// Returns the name of the operating system for this environment.
///
/// This is equivalent to `os.name`.
///
/// Some example values are: `posix`, `java`.
#[inline]
pub fn os_name(&self) -> &str {
&self.inner.os_name
}
/// Returns the name of the machine for this environment's platform.
///
/// This is equivalent to `platform.machine()`.
///
/// Some example values are: `x86_64`.
#[inline]
pub fn platform_machine(&self) -> &str {
&self.inner.platform_machine
}
/// Returns the name of the Python implementation for this environment's
/// platform.
///
/// This is equivalent to `platform.python_implementation()`.
///
/// Some example values are: `CPython`, `Jython`.
#[inline]
pub fn platform_python_implementation(&self) -> &str {
&self.inner.platform_python_implementation
}
/// Returns the release for this environment's platform.
///
/// This is equivalent to `platform.release()`.
///
/// Some example values are: `3.14.1-x86_64-linode39`, `14.5.0`, `1.8.0_51`.
#[inline]
pub fn platform_release(&self) -> &str {
&self.inner.platform_release
}
/// Returns the system for this environment's platform.
///
/// This is equivalent to `platform.system()`.
///
/// Some example values are: `Linux`, `Windows`, `Java`.
#[inline]
pub fn platform_system(&self) -> &str {
&self.inner.platform_system
}
/// Returns the version for this environment's platform.
///
/// This is equivalent to `platform.version()`.
///
/// Some example values are: `#1 SMP Fri Apr 25 13:07:35 EDT 2014`,
/// `Java HotSpot(TM) 64-Bit Server VM, 25.51-b03, Oracle Corporation`,
/// `Darwin Kernel Version 14.5.0: Wed Jul 29 02:18:53 PDT 2015;
/// root:xnu-2782.40.9~2/RELEASE_X86_64`.
#[inline]
pub fn platform_version(&self) -> &str {
&self.inner.platform_version
}
/// Returns the full version of Python for this environment.
///
/// This is equivalent to `platform.python_version()`.
///
/// Some example values are: `3.4.0`, `3.5.0b1`.
#[inline]
pub fn python_full_version(&self) -> &StringVersion {
&self.inner.python_full_version
}
/// Returns the version of Python for this environment.
///
/// This is equivalent to `'.'.join(platform.python_version_tuple()[:2])`.
///
/// Some example values are: `3.4`, `2.7`.
#[inline]
pub fn python_version(&self) -> &StringVersion {
&self.inner.python_version
}
/// Returns the name of the system platform for this environment.
///
/// This is equivalent to `sys.platform`.
///
/// Some example values are: `linux`, `linux2`, `darwin`, `java1.8.0_51`
/// (note that `linux` is from Python3 and `linux2` from Python2).
#[inline]
pub fn sys_platform(&self) -> &str {
&self.inner.sys_platform
}
}
/// APIs for setting specific parts of a marker environment.
impl MarkerEnvironment {
/// Set the name of the Python implementation for this environment.
///
/// See also [`MarkerEnvironment::implementation_name`].
#[inline]
#[must_use]
pub fn with_implementation_name(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).implementation_name = value.into();
self
}
/// Set the Python implementation version for this environment.
///
/// See also [`MarkerEnvironment::implementation_version`].
#[inline]
#[must_use]
pub fn with_implementation_version(mut self, value: impl Into<StringVersion>) -> Self {
Arc::make_mut(&mut self.inner).implementation_version = value.into();
self
}
/// Set the name of the operating system for this environment.
///
/// See also [`MarkerEnvironment::os_name`].
#[inline]
#[must_use]
pub fn with_os_name(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).os_name = value.into();
self
}
/// Set the name of the machine for this environment's platform.
///
/// See also [`MarkerEnvironment::platform_machine`].
#[inline]
#[must_use]
pub fn with_platform_machine(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).platform_machine = value.into();
self
}
/// Set the name of the Python implementation for this environment's
/// platform.
///
/// See also [`MarkerEnvironment::platform_python_implementation`].
#[inline]
#[must_use]
pub fn with_platform_python_implementation(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).platform_python_implementation = value.into();
self
}
/// Set the release for this environment's platform.
///
/// See also [`MarkerEnvironment::platform_release`].
#[inline]
#[must_use]
pub fn with_platform_release(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).platform_release = value.into();
self
}
/// Set the system for this environment's platform.
///
/// See also [`MarkerEnvironment::platform_system`].
#[inline]
#[must_use]
pub fn with_platform_system(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).platform_system = value.into();
self
}
/// Set the version for this environment's platform.
///
/// See also [`MarkerEnvironment::platform_version`].
#[inline]
#[must_use]
pub fn with_platform_version(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).platform_version = value.into();
self
}
/// Set the full version of Python for this environment.
///
/// See also [`MarkerEnvironment::python_full_version`].
#[inline]
#[must_use]
pub fn with_python_full_version(mut self, value: impl Into<StringVersion>) -> Self {
Arc::make_mut(&mut self.inner).python_full_version = value.into();
self
}
/// Set the version of Python for this environment.
///
/// See also [`MarkerEnvironment::python_full_version`].
#[inline]
#[must_use]
pub fn with_python_version(mut self, value: impl Into<StringVersion>) -> Self {
Arc::make_mut(&mut self.inner).python_version = value.into();
self
}
/// Set the name of the system platform for this environment.
///
/// See also [`MarkerEnvironment::sys_platform`].
#[inline]
#[must_use]
pub fn with_sys_platform(mut self, value: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).sys_platform = value.into();
self
}
}
/// A builder for constructing a marker environment.
///
/// A value of this type can be fallibly converted to a full
/// [`MarkerEnvironment`] via [`MarkerEnvironment::try_from`]. This can fail when
/// the version strings given aren't valid.
///
/// The main utility of this type is for constructing dummy or test environment
/// values.
#[allow(missing_docs)]
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct MarkerEnvironmentBuilder<'a> {
pub implementation_name: &'a str,
pub implementation_version: &'a str,
pub os_name: &'a str,
pub platform_machine: &'a str,
pub platform_python_implementation: &'a str,
pub platform_release: &'a str,
pub platform_system: &'a str,
pub platform_version: &'a str,
pub python_full_version: &'a str,
pub python_version: &'a str,
pub sys_platform: &'a str,
}
impl<'a> TryFrom<MarkerEnvironmentBuilder<'a>> for MarkerEnvironment {
type Error = VersionParseError;
fn try_from(builder: MarkerEnvironmentBuilder<'a>) -> Result<Self, Self::Error> {
Ok(Self {
inner: Arc::new(MarkerEnvironmentInner {
implementation_name: builder.implementation_name.to_string(),
implementation_version: builder.implementation_version.parse()?,
os_name: builder.os_name.to_string(),
platform_machine: builder.platform_machine.to_string(),
platform_python_implementation: builder.platform_python_implementation.to_string(),
platform_release: builder.platform_release.to_string(),
platform_system: builder.platform_system.to_string(),
platform_version: builder.platform_version.to_string(),
python_full_version: builder.python_full_version.parse()?,
python_version: builder.python_version.parse()?,
sys_platform: builder.sys_platform.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-pep508/src/marker/parse.rs | crates/uv-pep508/src/marker/parse.rs | use arcstr::ArcStr;
use std::str::FromStr;
use uv_normalize::{ExtraName, GroupName};
use uv_pep440::{Version, VersionPattern, VersionSpecifier};
use crate::cursor::Cursor;
use crate::marker::MarkerValueExtra;
use crate::marker::lowering::CanonicalMarkerListPair;
use crate::marker::tree::{ContainerOperator, MarkerValueList};
use crate::{
ExtraOperator, MarkerExpression, MarkerOperator, MarkerTree, MarkerValue, MarkerValueString,
MarkerValueVersion, MarkerWarningKind, Pep508Error, Pep508ErrorSource, Pep508Url, Reporter,
};
/// ```text
/// version_cmp = wsp* <'<=' | '<' | '!=' | '==' | '>=' | '>' | '~=' | '==='>
/// marker_op = version_cmp | (wsp* 'in') | (wsp* 'not' wsp+ 'in')
/// ```
/// The `wsp*` has already been consumed by the caller.
fn parse_marker_operator<T: Pep508Url>(
cursor: &mut Cursor,
) -> Result<MarkerOperator, Pep508Error<T>> {
let (start, len) = if cursor.peek_char().is_some_and(char::is_alphabetic) {
// "in" or "not"
cursor.take_while(|char| !char.is_whitespace() && char != '\'' && char != '"')
} else {
// A mathematical operator
cursor.take_while(|char| matches!(char, '<' | '=' | '>' | '~' | '!'))
};
let operator = cursor.slice(start, len);
if operator == "not" {
// 'not' wsp+ 'in'
match cursor.next() {
None => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(
"Expected whitespace after 'not', found end of input".to_string(),
),
start: cursor.pos(),
len: 1,
input: cursor.to_string(),
});
}
Some((_, whitespace)) if whitespace.is_whitespace() => {}
Some((pos, other)) => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected whitespace after `not`, found `{other}`"
)),
start: pos,
len: other.len_utf8(),
input: cursor.to_string(),
});
}
}
cursor.eat_whitespace();
cursor.next_expect_char('i', cursor.pos())?;
cursor.next_expect_char('n', cursor.pos())?;
return Ok(MarkerOperator::NotIn);
}
MarkerOperator::from_str(operator).map_err(|_| Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected a valid marker operator (such as `>=` or `not in`), found `{operator}`"
)),
start,
len,
input: cursor.to_string(),
})
}
/// Either a single or double quoted string or one of '`python_version`', '`python_full_version`',
/// '`os_name`', '`sys_platform`', '`platform_release`', '`platform_system`', '`platform_version`',
/// '`platform_machine`', '`platform_python_implementation`', '`implementation_name`',
/// '`implementation_version`', 'extra'
pub(crate) fn parse_marker_value<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<MarkerValue, Pep508Error<T>> {
// > User supplied constants are always encoded as strings with either ' or " quote marks. Note
// > that backslash escapes are not defined, but existing implementations do support them. They
// > are not included in this specification because they add complexity and there is no observable
// > need for them today. Similarly we do not define non-ASCII character support: all the runtime
// > variables we are referencing are expected to be ASCII-only.
match cursor.peek() {
None => Err(Pep508Error {
message: Pep508ErrorSource::String(
"Expected marker value, found end of dependency specification".to_string(),
),
start: cursor.pos(),
len: 1,
input: cursor.to_string(),
}),
// It can be a string ...
Some((start_pos, quotation_mark @ ('"' | '\''))) => {
cursor.next();
let (start, len) = cursor.take_while(|c| c != quotation_mark);
let value = ArcStr::from(cursor.slice(start, len));
cursor.next_expect_char(quotation_mark, start_pos)?;
Ok(MarkerValue::QuotedString(value))
}
// ... or it can be a keyword
Some(_) => {
let (start, len) = cursor.take_while(|char| {
!char.is_whitespace() && !matches!(char, '>' | '=' | '<' | '!' | '~' | ')')
});
let key = cursor.slice(start, len);
MarkerValue::from_str(key)
.map_err(|_| Pep508Error {
message: Pep508ErrorSource::String(format!(
"Expected a quoted string or a valid marker name, found `{key}`"
)),
start,
len,
input: cursor.to_string(),
})
.inspect(|value| match value {
MarkerValue::MarkerEnvString(MarkerValueString::OsNameDeprecated) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"os.name is deprecated in favor of os_name".to_string(),
);
}
MarkerValue::MarkerEnvString(MarkerValueString::PlatformMachineDeprecated) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"platform.machine is deprecated in favor of platform_machine".to_string(),
);
}
MarkerValue::MarkerEnvString(
MarkerValueString::PlatformPythonImplementationDeprecated,
) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"platform.python_implementation is deprecated in favor of platform_python_implementation".to_string(),
);
}
MarkerValue::MarkerEnvString(
MarkerValueString::PythonImplementationDeprecated,
) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"python_implementation is deprecated in favor of platform_python_implementation"
.to_string(),
);
}
MarkerValue::MarkerEnvString(MarkerValueString::PlatformVersionDeprecated) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"platform.version is deprecated in favor of platform_version"
.to_string(),
);
}
MarkerValue::MarkerEnvString(MarkerValueString::SysPlatformDeprecated) => {
reporter.report(
MarkerWarningKind::DeprecatedMarkerName,
"sys.platform is deprecated in favor of sys_platform".to_string(),
);
}
_ => {}
})
}
}
}
/// ```text
/// marker_var:l marker_op:o marker_var:r
/// ```
pub(crate) fn parse_marker_key_op_value<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<Option<MarkerExpression>, Pep508Error<T>> {
cursor.eat_whitespace();
let start = cursor.pos();
let l_value = parse_marker_value(cursor, reporter)?;
cursor.eat_whitespace();
// "not in" and "in" must be preceded by whitespace. We must already have matched a whitespace
// when we're here because other `parse_marker_key` would have pulled the characters in and
// errored
let operator = parse_marker_operator(cursor)?;
cursor.eat_whitespace();
let r_value = parse_marker_value(cursor, reporter)?;
let len = cursor.pos() - start;
// Convert a `<marker_value> <marker_op> <marker_value>` expression into its
// typed equivalent.
let expr = match l_value {
// Either:
// - `<version key> <version op> <quoted PEP 440 version>`
// - `<version key> in <list of quoted PEP 440 versions>` and ("not in")
MarkerValue::MarkerEnvVersion(key) => {
let MarkerValue::QuotedString(value) = r_value else {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected double quoted PEP 440 version to compare with {key},
found {r_value}, will be ignored"
),
);
return Ok(None);
};
// Check for `in` and `not in` expressions
if let Some(expr) = parse_version_in_expr(key, operator, &value, reporter) {
return Ok(Some(expr));
}
// Otherwise, it's a normal version expression
parse_version_expr(key, operator, &value, reporter)
}
// The only sound choice for this is `<env key> <op> <string>`
MarkerValue::MarkerEnvString(key) => {
let value = match r_value {
MarkerValue::Extra
| MarkerValue::MarkerEnvVersion(_)
| MarkerValue::MarkerEnvString(_)
| MarkerValue::MarkerEnvList(_) => {
reporter.report(
MarkerWarningKind::MarkerMarkerComparison,
"Comparing two markers with each other doesn't make any sense,
will be ignored"
.to_string(),
);
return Ok(None);
}
MarkerValue::QuotedString(r_string) => r_string,
};
if operator == MarkerOperator::TildeEqual {
reporter.report(
MarkerWarningKind::LexicographicComparison,
"Can't compare strings with `~=`, will be ignored".to_string(),
);
return Ok(None);
}
Some(MarkerExpression::String {
key,
operator,
value,
})
}
// `extras in "test"` or `dependency_groups not in "dev"` are invalid.
MarkerValue::MarkerEnvList(key) => {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"The marker {key} must be on the right hand side of the expression"
)),
start,
len,
input: cursor.to_string(),
});
}
// `extra == '...'`
MarkerValue::Extra => {
let value = match r_value {
MarkerValue::MarkerEnvVersion(_)
| MarkerValue::MarkerEnvString(_)
| MarkerValue::MarkerEnvList(_)
| MarkerValue::Extra => {
reporter.report(
MarkerWarningKind::ExtraInvalidComparison,
"Comparing extra with something other than a quoted string is wrong,
will be ignored"
.to_string(),
);
return Ok(None);
}
MarkerValue::QuotedString(value) => value,
};
parse_extra_expr(operator, &value, reporter)
}
// This is either MarkerEnvVersion, MarkerEnvString, Extra (inverted), or Extras
MarkerValue::QuotedString(l_string) => {
match r_value {
// The only sound choice for this is `<quoted PEP 440 version> <version op>` <version key>
MarkerValue::MarkerEnvVersion(key) => {
parse_inverted_version_expr(&l_string, operator, key, reporter)
}
// '...' == <env key>
MarkerValue::MarkerEnvString(key) => Some(MarkerExpression::String {
key,
// Invert the operator to normalize the expression order.
operator: operator.invert(),
value: l_string,
}),
// `"test" in extras` or `"dev" in dependency_groups`
MarkerValue::MarkerEnvList(key) => {
let operator =
ContainerOperator::from_marker_operator(operator).ok_or_else(|| {
Pep508Error {
message: Pep508ErrorSource::String(format!(
"The operator {operator} is not supported with the marker {key}, only the `in` and `not in` operators are supported"
)),
start,
len,
input: cursor.to_string(),
}
})?;
let pair = match key {
// `'...' in extras`
MarkerValueList::Extras => match ExtraName::from_str(&l_string) {
Ok(name) => CanonicalMarkerListPair::Extras(name),
Err(err) => {
reporter.report(
MarkerWarningKind::ExtrasInvalidComparison,
format!("Expected extra name (found `{l_string}`): {err}"),
);
CanonicalMarkerListPair::Arbitrary {
key,
value: l_string.to_string(),
}
}
},
// `'...' in dependency_groups`
MarkerValueList::DependencyGroups => {
match GroupName::from_str(&l_string) {
Ok(name) => CanonicalMarkerListPair::DependencyGroup(name),
Err(err) => {
reporter.report(
MarkerWarningKind::ExtrasInvalidComparison,
format!("Expected dependency group name (found `{l_string}`): {err}"),
);
CanonicalMarkerListPair::Arbitrary {
key,
value: l_string.to_string(),
}
}
}
}
};
Some(MarkerExpression::List { pair, operator })
}
// `'...' == extra`
MarkerValue::Extra => parse_extra_expr(operator, &l_string, reporter),
// `'...' == '...'`, doesn't make much sense
MarkerValue::QuotedString(_) => {
// Not even pypa/packaging 22.0 supports this
// https://github.com/pypa/packaging/issues/632
reporter.report(
MarkerWarningKind::StringStringComparison,
format!(
"Comparing two quoted strings with each other doesn't make sense:
'{l_string}' {operator} {r_value}, will be ignored"
),
);
None
}
}
}
};
Ok(expr)
}
/// Creates an instance of [`MarkerExpression::VersionIn`] with the given values.
///
/// Some important caveats apply here.
///
/// While the specification defines this operation as a substring search, for versions, we use a
/// version-aware match so we can perform algebra on the expressions. This means that some markers
/// will not be evaluated according to the specification, but these marker expressions are
/// relatively rare so the trade-off is acceptable.
///
/// The following limited expression is supported:
///
/// ```text
/// [not] in '<version> [additional versions]'
/// ```
///
/// where the version is PEP 440 compliant. Arbitrary whitespace is allowed between versions.
///
/// Returns `None` if the [`MarkerOperator`] is not relevant.
/// Reports a warning if an invalid version is encountered, and returns `None`.
fn parse_version_in_expr(
key: MarkerValueVersion,
operator: MarkerOperator,
value: &str,
reporter: &mut impl Reporter,
) -> Option<MarkerExpression> {
let operator = ContainerOperator::from_marker_operator(operator)?;
let mut cursor = Cursor::new(value);
let mut versions = Vec::new();
// Parse all of the values in the list as versions
loop {
// Allow arbitrary whitespace between versions
cursor.eat_whitespace();
let (start, len) = cursor.take_while(|c| !c.is_whitespace());
if len == 0 {
break;
}
let version = match Version::from_str(cursor.slice(start, len)) {
Ok(version) => version,
Err(err) => {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected PEP 440 versions to compare with {key}, found {value},
will be ignored: {err}"
),
);
return None;
}
};
versions.push(version);
}
Some(MarkerExpression::VersionIn {
key,
versions,
operator,
})
}
/// Creates an instance of [`MarkerExpression::Version`] with the given values.
///
/// Reports a warning on failure, and returns `None`.
fn parse_version_expr(
key: MarkerValueVersion,
marker_operator: MarkerOperator,
value: &str,
reporter: &mut impl Reporter,
) -> Option<MarkerExpression> {
let pattern = match value.parse::<VersionPattern>() {
Ok(pattern) => pattern,
Err(err) => {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected PEP 440 version to compare with {key}, found {value},
will be ignored: {err}"
),
);
return None;
}
};
let Some(operator) = marker_operator.to_pep440_operator() else {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected PEP 440 version operator to compare {key} with `{version}`,
found `{marker_operator}`, will be ignored",
version = pattern.version()
),
);
return None;
};
let specifier = match VersionSpecifier::from_pattern(operator, pattern) {
Ok(specifier) => specifier,
Err(err) => {
reporter.report(
MarkerWarningKind::Pep440Error,
format!("Invalid operator/version combination: {err}"),
);
return None;
}
};
Some(MarkerExpression::Version { key, specifier })
}
/// Creates an instance of [`MarkerExpression::Version`] from an inverted expression.
///
/// Reports a warning on failure, and returns `None`.
fn parse_inverted_version_expr(
value: &str,
marker_operator: MarkerOperator,
key: MarkerValueVersion,
reporter: &mut impl Reporter,
) -> Option<MarkerExpression> {
// Invert the operator to normalize the expression order.
let marker_operator = marker_operator.invert();
// Not star allowed here, `'3.*' == python_version` is not a valid PEP 440 comparison.
let version = match value.parse::<Version>() {
Ok(version) => version,
Err(err) => {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected PEP 440 version to compare with {key}, found {value},
will be ignored: {err}"
),
);
return None;
}
};
let Some(operator) = marker_operator.to_pep440_operator() else {
reporter.report(
MarkerWarningKind::Pep440Error,
format!(
"Expected PEP 440 version operator to compare {key} with `{version}`,
found `{marker_operator}`, will be ignored"
),
);
return None;
};
let specifier = match VersionSpecifier::from_version(operator, version) {
Ok(specifier) => specifier,
Err(err) => {
reporter.report(
MarkerWarningKind::Pep440Error,
format!("Invalid operator/version combination: {err}"),
);
return None;
}
};
Some(MarkerExpression::Version { key, specifier })
}
/// Creates an instance of [`MarkerExpression::Extra`] with the given values, falling back to
/// [`MarkerExpression::Arbitrary`] on failure.
fn parse_extra_expr(
operator: MarkerOperator,
value: &str,
reporter: &mut impl Reporter,
) -> Option<MarkerExpression> {
let name = match ExtraName::from_str(value) {
Ok(name) => MarkerValueExtra::Extra(name),
Err(err) => {
reporter.report(
MarkerWarningKind::ExtraInvalidComparison,
format!("Expected extra name (found `{value}`): {err}"),
);
MarkerValueExtra::Arbitrary(value.to_string())
}
};
if let Some(operator) = ExtraOperator::from_marker_operator(operator) {
return Some(MarkerExpression::Extra { operator, name });
}
reporter.report(
MarkerWarningKind::ExtraInvalidComparison,
"Comparing `extra` with any operator other than `==` or `!=` is wrong and will be ignored"
.to_string(),
);
None
}
/// ```text
/// marker_expr = marker_var:l marker_op:o marker_var:r -> (o, l, r)
/// | wsp* '(' marker:m wsp* ')' -> m
/// ```
fn parse_marker_expr<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<Option<MarkerTree>, Pep508Error<T>> {
cursor.eat_whitespace();
if let Some(start_pos) = cursor.eat_char('(') {
let marker = parse_marker_or(cursor, reporter)?;
cursor.next_expect_char(')', start_pos)?;
Ok(marker)
} else {
Ok(parse_marker_key_op_value(cursor, reporter)?.map(MarkerTree::expression))
}
}
/// ```text
/// marker_and = marker_expr:l wsp* 'and' marker_expr:r -> ('and', l, r)
/// | marker_expr:m -> m
/// ```
fn parse_marker_and<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<Option<MarkerTree>, Pep508Error<T>> {
parse_marker_op(cursor, "and", MarkerTree::and, parse_marker_expr, reporter)
}
/// ```text
/// marker_or = marker_and:l wsp* 'or' marker_and:r -> ('or', l, r)
/// | marker_and:m -> m
/// ```
fn parse_marker_or<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<Option<MarkerTree>, Pep508Error<T>> {
parse_marker_op(
cursor,
"or",
MarkerTree::or,
|cursor, reporter| parse_marker_and(cursor, reporter),
reporter,
)
}
/// Parses both `marker_and` and `marker_or`
#[allow(clippy::type_complexity)]
fn parse_marker_op<T: Pep508Url, R: Reporter>(
cursor: &mut Cursor,
op: &str,
apply: fn(&mut MarkerTree, MarkerTree),
parse_inner: fn(&mut Cursor, &mut R) -> Result<Option<MarkerTree>, Pep508Error<T>>,
reporter: &mut R,
) -> Result<Option<MarkerTree>, Pep508Error<T>> {
let mut tree = None;
// marker_and or marker_expr
let first_element = parse_inner(cursor, reporter)?;
if let Some(expression) = first_element {
match tree {
Some(ref mut tree) => apply(tree, expression),
None => tree = Some(expression),
}
}
loop {
// wsp*
cursor.eat_whitespace();
// ('or' marker_and) or ('and' marker_or)
let (start, len) = cursor.peek_while(|c| !c.is_whitespace());
match cursor.slice(start, len) {
value if value == op => {
cursor.take_while(|c| !c.is_whitespace());
if let Some(expression) = parse_inner(cursor, reporter)? {
match tree {
Some(ref mut tree) => apply(tree, expression),
None => tree = Some(expression),
}
}
}
_ => return Ok(tree),
}
}
}
/// ```text
/// marker = marker_or^
/// ```
pub(crate) fn parse_markers_cursor<T: Pep508Url>(
cursor: &mut Cursor,
reporter: &mut impl Reporter,
) -> Result<Option<MarkerTree>, Pep508Error<T>> {
let marker = parse_marker_or(cursor, reporter)?;
cursor.eat_whitespace();
if let Some((pos, unexpected)) = cursor.next() {
// If we're here, both parse_marker_or and parse_marker_and returned because the next
// character was neither "and" nor "or"
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Unexpected character '{unexpected}', expected 'and', 'or' or end of input"
)),
start: pos,
len: cursor.remaining(),
input: cursor.to_string(),
});
}
Ok(marker)
}
/// Parses markers such as `python_version < '3.8'` or
/// `python_version == "3.10" and (sys_platform == "win32" or (os_name == "linux" and implementation_name == 'cpython'))`
pub(crate) fn parse_markers<T: Pep508Url>(
markers: &str,
reporter: &mut impl Reporter,
) -> Result<MarkerTree, Pep508Error<T>> {
let mut chars = Cursor::new(markers);
// If the tree consisted entirely of arbitrary expressions
// that were ignored, it evaluates to true.
parse_markers_cursor(&mut chars, reporter).map(|result| result.unwrap_or(MarkerTree::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-pep508/src/marker/algebra.rs | crates/uv-pep508/src/marker/algebra.rs | //! This module implements marker tree operations using Algebraic Decision Diagrams (ADD).
//!
//! An ADD is a tree of decision nodes as well as two terminal nodes, `true` and `false`. Marker
//! variables are represented as decision nodes. The edge from a decision node to it's child
//! represents a particular assignment of a value to that variable. Depending on the type of
//! variable, an edge can be represented by binary values or a disjoint set of ranges, as opposed
//! to a traditional Binary Decision Diagram.
//!
//! For example, the marker `python_version > '3.7' and os_name == 'Linux'` creates the following
//! marker tree:
//!
//! ```text
//! python_version:
//! (> '3.7') -> os_name:
//! (> 'Linux') -> FALSE
//! (== 'Linux') -> TRUE
//! (< 'Linux') -> FALSE
//! (<= '3.7') -> FALSE
//! ```
//!
//! Specifically, a marker tree is represented as a Reduced Ordered ADD. An ADD is ordered if
//! different variables appear in the same order on all paths from the root. Additionally, an ADD
//! is reduced if:
//! - Isomorphic nodes are merged.
//! - Nodes with isomorphic children are eliminated.
//!
//! These two rules provide an important guarantee for marker trees: marker trees are canonical for
//! a given marker function and variable ordering. Because variable ordering is defined at compile-time,
//! this means any functionally equivalent marker trees are normalized upon construction. Importantly,
//! this means that we can identify trivially true marker trees, as well as unsatisfiable marker trees.
//! This provides important information to the resolver when forking.
//!
//! ADDs provide polynomial time operations such as conjunction and negation, which is important as marker
//! trees are combined during universal resolution. Because ADDs solve the SAT problem, constructing an
//! arbitrary ADD can theoretically take exponential time in the worst case. However, in practice, marker trees
//! have a limited number of variables and user-provided marker trees are typically very simple.
//!
//! Additionally, the implementation in this module uses complemented edges, meaning a marker tree and
//! it's complement are represented by the same node internally. This allows cheap constant-time marker
//! tree negation. It also allows us to only implement a single operation for both `AND` and `OR`, implementing
//! the other in terms of its De Morgan Complement.
//!
//! ADDs are created and managed through the global [`Interner`]. A given ADD is referenced through
//! a [`NodeId`], which represents a potentially complemented reference to a [`Node`] in the interner,
//! or a terminal `true`/`false` node. Interning allows the reduction rule that isomorphic nodes are
//! merged to be applied globally.
use std::cmp::Ordering;
use std::fmt;
use std::ops::Bound;
use std::sync::{LazyLock, Mutex, MutexGuard};
use arcstr::ArcStr;
use itertools::{Either, Itertools};
use rustc_hash::FxHashMap;
use version_ranges::Ranges;
use uv_pep440::{Operator, Version, VersionSpecifier, release_specifier_to_range};
use crate::marker::MarkerValueExtra;
use crate::marker::lowering::{
CanonicalMarkerListPair, CanonicalMarkerValueExtra, CanonicalMarkerValueString,
CanonicalMarkerValueVersion,
};
use crate::marker::tree::ContainerOperator;
use crate::{
ExtraOperator, MarkerExpression, MarkerOperator, MarkerValueString, MarkerValueVersion,
};
/// The global node interner.
pub(crate) static INTERNER: LazyLock<Interner> = LazyLock::new(Interner::default);
/// An interner for decision nodes.
///
/// Interning decision nodes allows isomorphic nodes to be automatically merged.
/// It also allows nodes to cheaply compared.
#[derive(Default)]
pub(crate) struct Interner {
pub(crate) shared: InternerShared,
state: Mutex<InternerState>,
}
/// The shared part of an [`Interner`], which can be accessed without a lock.
#[derive(Default)]
pub(crate) struct InternerShared {
/// A list of unique [`Node`]s.
nodes: boxcar::Vec<Node>,
}
/// The mutable [`Interner`] state, stored behind a lock.
#[derive(Default)]
struct InternerState {
/// A map from a [`Node`] to a unique [`NodeId`], representing an index
/// into [`InternerShared`].
unique: FxHashMap<Node, NodeId>,
/// A cache for `AND` operations between two nodes.
/// Note that `OR` is implemented in terms of `AND`.
cache: FxHashMap<(NodeId, NodeId), NodeId>,
/// The [`NodeId`] for the disjunction of known, mutually incompatible markers.
exclusions: Option<NodeId>,
}
impl InternerShared {
/// Returns the node for the given [`NodeId`].
pub(crate) fn node(&self, id: NodeId) -> &Node {
&self.nodes[id.index()]
}
}
impl Interner {
/// Locks the interner state, returning a guard that can be used to perform marker
/// operations.
pub(crate) fn lock(&self) -> InternerGuard<'_> {
InternerGuard {
state: self.state.lock().unwrap(),
shared: &self.shared,
}
}
}
/// A lock of [`InternerState`].
pub(crate) struct InternerGuard<'a> {
state: MutexGuard<'a, InternerState>,
shared: &'a InternerShared,
}
impl InternerGuard<'_> {
/// Creates a decision node with the given variable and children.
fn create_node(&mut self, var: Variable, children: Edges) -> NodeId {
let mut node = Node { var, children };
let mut first = node.children.nodes().next().unwrap();
// With a complemented edge representation, there are two ways to represent the same node:
// complementing the root and all children edges results in the same node. To ensure markers
// are canonical, the first child edge is never complemented.
let mut flipped = false;
if first.is_complement() {
node = node.not();
first = first.not();
flipped = true;
}
// Reduction: If all children refer to the same node, we eliminate the parent node
// and just return the child.
if node.children.nodes().all(|node| node == first) {
return if flipped { first.not() } else { first };
}
// Insert the node.
let id = self
.state
.unique
.entry(node.clone())
.or_insert_with(|| NodeId::new(self.shared.nodes.push(node), false));
if flipped { id.not() } else { *id }
}
/// Returns a decision node for a single marker expression.
pub(crate) fn expression(&mut self, expr: MarkerExpression) -> NodeId {
let (var, children) = match expr {
// A variable representing the output of a version key. Edges correspond
// to disjoint version ranges.
MarkerExpression::Version { key, specifier } => match key {
MarkerValueVersion::ImplementationVersion => (
Variable::Version(CanonicalMarkerValueVersion::ImplementationVersion),
Edges::from_specifier(specifier),
),
MarkerValueVersion::PythonFullVersion => (
Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
Edges::from_specifier(specifier),
),
// Normalize `python_version` markers to `python_full_version` nodes.
MarkerValueVersion::PythonVersion => {
match python_version_to_full_version(specifier.only_release()) {
Ok(specifier) => (
Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
Edges::from_specifier(specifier),
),
Err(node) => return node,
}
}
},
// A variable representing the output of a version key. Edges correspond
// to disjoint version ranges.
MarkerExpression::VersionIn {
key,
versions,
operator,
} => match key {
MarkerValueVersion::ImplementationVersion => (
Variable::Version(CanonicalMarkerValueVersion::ImplementationVersion),
Edges::from_versions(&versions, operator),
),
MarkerValueVersion::PythonFullVersion => (
Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
Edges::from_versions(&versions, operator),
),
// Normalize `python_version` markers to `python_full_version` nodes.
MarkerValueVersion::PythonVersion => {
match Edges::from_python_versions(versions, operator) {
Ok(edges) => (
Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
edges,
),
Err(node) => return node,
}
}
},
// The `in` and `contains` operators are a bit different than other operators.
// In particular, they do not represent a particular value for the corresponding
// variable, and can overlap. For example, `'nux' in os_name` and `os_name == 'Linux'`
// can both be `true` in the same marker environment, and so cannot be represented by
// the same variable. Because of this, we represent `in` and `contains`, as well as
// their negations, as distinct variables, unrelated to the range of a given key.
//
// Note that in the presence of the `in` operator, we may not be able to simplify
// some marker trees to a constant `true` or `false`. For example, it is not trivial to
// detect that `os_name > 'z' and os_name in 'Linux'` is unsatisfiable.
MarkerExpression::String {
key,
operator: MarkerOperator::In,
value,
} => (
Variable::In {
key: key.into(),
value,
},
Edges::from_bool(true),
),
MarkerExpression::String {
key,
operator: MarkerOperator::NotIn,
value,
} => (
Variable::In {
key: key.into(),
value,
},
Edges::from_bool(false),
),
MarkerExpression::String {
key,
operator: MarkerOperator::Contains,
value,
} => (
Variable::Contains {
key: key.into(),
value,
},
Edges::from_bool(true),
),
MarkerExpression::String {
key,
operator: MarkerOperator::NotContains,
value,
} => (
Variable::Contains {
key: key.into(),
value,
},
Edges::from_bool(false),
),
// A variable representing the output of a string key. Edges correspond
// to disjoint string ranges.
MarkerExpression::String {
key,
operator,
value,
} => {
// Normalize `platform_system` markers to `sys_platform` nodes.
//
// The `platform` module is "primarily intended for diagnostic information to be
// read by humans."
//
// We only normalize when we can confidently guarantee that the values are
// exactly equivalent. For example, we normalize `platform_system == 'Windows'`
// to `sys_platform == 'win32'`, but we do not normalize `platform_system == 'FreeBSD'`
// to `sys_platform == 'freebsd'`, since FreeBSD typically includes a major version
// in its `sys.platform` output.
//
// For cases that aren't normalized, we do our best to encode known-incompatible
// values in `exclusions`.
//
// See: https://discuss.python.org/t/clarify-usage-of-platform-system/70900
let (key, value) = match (key, value.as_ref()) {
(MarkerValueString::PlatformSystem, "Windows") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("win32"),
),
(MarkerValueString::PlatformSystem, "Darwin") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("darwin"),
),
(MarkerValueString::PlatformSystem, "Linux") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("linux"),
),
(MarkerValueString::PlatformSystem, "AIX") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("aix"),
),
(MarkerValueString::PlatformSystem, "Emscripten") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("emscripten"),
),
// See: https://peps.python.org/pep-0738/#sys
(MarkerValueString::PlatformSystem, "Android") => (
CanonicalMarkerValueString::SysPlatform,
arcstr::literal!("android"),
),
_ => (key.into(), value),
};
(Variable::String(key), Edges::from_string(operator, value))
}
MarkerExpression::List { pair, operator } => (
Variable::List(pair),
Edges::from_bool(operator == ContainerOperator::In),
),
// A variable representing the existence or absence of a particular extra.
MarkerExpression::Extra {
name: MarkerValueExtra::Extra(extra),
operator: ExtraOperator::Equal,
} => (
Variable::Extra(CanonicalMarkerValueExtra::Extra(extra)),
Edges::from_bool(true),
),
MarkerExpression::Extra {
name: MarkerValueExtra::Extra(extra),
operator: ExtraOperator::NotEqual,
} => (
Variable::Extra(CanonicalMarkerValueExtra::Extra(extra)),
Edges::from_bool(false),
),
// Invalid `extra` names are always `false`.
MarkerExpression::Extra {
name: MarkerValueExtra::Arbitrary(_),
..
} => return NodeId::FALSE,
};
self.create_node(var, children)
}
/// Returns a decision node representing the disjunction of two nodes.
pub(crate) fn or(&mut self, xi: NodeId, yi: NodeId) -> NodeId {
// We take advantage of cheap negation here and implement OR in terms
// of it's De Morgan complement.
self.and(xi.not(), yi.not()).not()
}
/// Returns a decision node representing the conjunction of two nodes.
pub(crate) fn and(&mut self, xi: NodeId, yi: NodeId) -> NodeId {
if xi.is_true() {
return yi;
}
if yi.is_true() {
return xi;
}
if xi == yi {
return xi;
}
if xi.is_false() || yi.is_false() {
return NodeId::FALSE;
}
// `X and not X` is `false` by definition.
if xi.not() == yi {
return NodeId::FALSE;
}
// The operation was memoized.
if let Some(result) = self.state.cache.get(&(xi, yi)) {
return *result;
}
let (x, y) = (self.shared.node(xi), self.shared.node(yi));
// Determine whether the conjunction _could_ contain a conflict.
//
// As an optimization, we only have to perform this check at the top-level, since these
// variables are given higher priority in the tree. In other words, if they're present, they
// _must_ be at the top; and if they're not at the top, we know they aren't present in any
// children.
let conflicts = x.var.is_conflicting_variable() && y.var.is_conflicting_variable();
// Perform Shannon Expansion of the higher order variable.
let (func, children) = match x.var.cmp(&y.var) {
// X is higher order than Y, apply Y to every child of X.
Ordering::Less => {
let children = x.children.map(xi, |node| self.and(node, yi));
(x.var.clone(), children)
}
// Y is higher order than X, apply X to every child of Y.
Ordering::Greater => {
let children = y.children.map(yi, |node| self.and(node, xi));
(y.var.clone(), children)
}
// X and Y represent the same variable, merge their children.
Ordering::Equal => {
let children = x.children.apply(xi, &y.children, yi, |x, y| self.and(x, y));
(x.var.clone(), children)
}
};
// Create the output node.
let node = self.create_node(func, children);
// If the node includes known incompatibilities, map it to `false`.
let node = if conflicts {
let exclusions = self.exclusions();
if self.disjointness(node, exclusions.not()) {
NodeId::FALSE
} else {
node
}
} else {
node
};
// Memoize the result of this operation.
//
// ADDs often contain duplicated subgraphs in distinct branches due to the restricted
// variable ordering. Memoizing allows ADD operations to remain polynomial time.
self.state.cache.insert((xi, yi), node);
node
}
/// Returns `true` if there is no environment in which both marker trees can apply,
/// i.e. their conjunction is always `false`.
pub(crate) fn is_disjoint(&mut self, xi: NodeId, yi: NodeId) -> bool {
// `false` is disjoint with any marker.
if xi.is_false() || yi.is_false() {
return true;
}
// `true` is not disjoint with any marker except `false`.
if xi.is_true() || yi.is_true() {
return false;
}
// `X` and `X` are not disjoint.
if xi == yi {
return false;
}
// `X` and `not X` are disjoint by definition.
if xi.not() == yi {
return true;
}
let (x, y) = (self.shared.node(xi), self.shared.node(yi));
// Determine whether the conjunction _could_ contain a conflict.
//
// As an optimization, we only have to perform this check at the top-level, since these
// variables are given higher priority in the tree. In other words, if they're present, they
// _must_ be at the top; and if they're not at the top, we know they aren't present in any
// children.
if x.var.is_conflicting_variable() && y.var.is_conflicting_variable() {
return self.and(xi, yi).is_false();
}
// Perform Shannon Expansion of the higher order variable.
match x.var.cmp(&y.var) {
// X is higher order than Y, Y must be disjoint with every child of X.
Ordering::Less => x
.children
.nodes()
.all(|x| self.disjointness(x.negate(xi), yi)),
// Y is higher order than X, X must be disjoint with every child of Y.
Ordering::Greater => y
.children
.nodes()
.all(|y| self.disjointness(y.negate(yi), xi)),
// X and Y represent the same variable, their merged edges must be unsatisfiable.
Ordering::Equal => x.children.is_disjoint(xi, &y.children, yi, self),
}
}
/// Returns `true` if there is no environment in which both marker trees can apply,
/// i.e., their conjunction is always `false`.
fn disjointness(&mut self, xi: NodeId, yi: NodeId) -> bool {
// NOTE(charlie): This is equivalent to `is_disjoint`, with the exception that it doesn't
// perform the mutually-incompatible marker check. If it did, we'd create an infinite loop,
// since `is_disjoint` calls `and` (when relevant variables are present) which then calls
// `disjointness`.
// `false` is disjoint with any marker.
if xi.is_false() || yi.is_false() {
return true;
}
// `true` is not disjoint with any marker except `false`.
if xi.is_true() || yi.is_true() {
return false;
}
// `X` and `X` are not disjoint.
if xi == yi {
return false;
}
// `X` and `not X` are disjoint by definition.
if xi.not() == yi {
return true;
}
let (x, y) = (self.shared.node(xi), self.shared.node(yi));
// Perform Shannon Expansion of the higher order variable.
match x.var.cmp(&y.var) {
// X is higher order than Y, Y must be disjoint with every child of X.
Ordering::Less => x
.children
.nodes()
.all(|x| self.disjointness(x.negate(xi), yi)),
// Y is higher order than X, X must be disjoint with every child of Y.
Ordering::Greater => y
.children
.nodes()
.all(|y| self.disjointness(y.negate(yi), xi)),
// X and Y represent the same variable, their merged edges must be unsatisfiable.
Ordering::Equal => x.children.is_disjoint(xi, &y.children, yi, self),
}
}
// Restrict the output of a given boolean variable in the tree.
//
// If the provided function `f` returns a `Some` boolean value, the tree will be simplified
// with the assumption that the given variable is restricted to that value. If the function
// returns `None`, the variable will not be affected.
pub(crate) fn restrict(&mut self, i: NodeId, f: &impl Fn(&Variable) -> Option<bool>) -> NodeId {
if matches!(i, NodeId::TRUE | NodeId::FALSE) {
return i;
}
let node = self.shared.node(i);
if let Edges::Boolean { high, low } = node.children {
if let Some(value) = f(&node.var) {
// Restrict this variable to the given output by merging it
// with the relevant child.
let node = if value { high } else { low };
return self.restrict(node.negate(i), f);
}
}
// Restrict all nodes recursively.
let children = node.children.map(i, |node| self.restrict(node, f));
self.create_node(node.var.clone(), children)
}
/// Returns a new tree where the only nodes remaining are non-`extra`
/// nodes.
///
/// If there are only `extra` nodes, then this returns a tree that is
/// always true.
///
/// This works by assuming all `extra` nodes are always true.
///
/// For example, given a marker like
/// `((os_name == ... and extra == foo) or (sys_platform == ... and extra != foo))`,
/// this would return a marker
/// `os_name == ... or sys_platform == ...`.
pub(crate) fn without_extras(&mut self, mut i: NodeId) -> NodeId {
if matches!(i, NodeId::TRUE | NodeId::FALSE) {
return i;
}
let parent = i;
let node = self.shared.node(i);
if matches!(node.var, Variable::Extra(_)) {
i = NodeId::FALSE;
for child in node.children.nodes() {
i = self.or(i, child.negate(parent));
}
if i.is_true() {
return NodeId::TRUE;
}
self.without_extras(i)
} else {
// Restrict all nodes recursively.
let children = node.children.map(i, |node| self.without_extras(node));
self.create_node(node.var.clone(), children)
}
}
/// Returns a new tree where the only nodes remaining are `extra` nodes.
///
/// If there are no extra nodes, then this returns a tree that is always
/// true.
///
/// This works by assuming all non-`extra` nodes are always true.
pub(crate) fn only_extras(&mut self, mut i: NodeId) -> NodeId {
if matches!(i, NodeId::TRUE | NodeId::FALSE) {
return i;
}
let parent = i;
let node = self.shared.node(i);
if !matches!(node.var, Variable::Extra(_)) {
i = NodeId::FALSE;
for child in node.children.nodes() {
i = self.or(i, child.negate(parent));
}
if i.is_true() {
return NodeId::TRUE;
}
self.only_extras(i)
} else {
// Restrict all nodes recursively.
let children = node.children.map(i, |node| self.only_extras(node));
self.create_node(node.var.clone(), children)
}
}
/// Simplify this tree by *assuming* that the Python version range provided
/// is true and that the complement of it is false.
///
/// For example, with `requires-python = '>=3.8'` and a marker tree of
/// `python_full_version >= '3.8' and python_full_version <= '3.10'`, this
/// would result in a marker of `python_full_version <= '3.10'`.
pub(crate) fn simplify_python_versions(
&mut self,
i: NodeId,
py_lower: Bound<&Version>,
py_upper: Bound<&Version>,
) -> NodeId {
if matches!(i, NodeId::TRUE | NodeId::FALSE)
|| matches!((py_lower, py_upper), (Bound::Unbounded, Bound::Unbounded))
{
return i;
}
let node = self.shared.node(i);
// Look for a `python_full_version` expression, otherwise
// we recursively simplify.
let Node {
var: Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
children: Edges::Version { edges },
} = node
else {
// Simplify all nodes recursively.
let children = node.children.map(i, |node_id| {
self.simplify_python_versions(node_id, py_lower, py_upper)
});
return self.create_node(node.var.clone(), children);
};
let py_range = Ranges::from_range_bounds((py_lower.cloned(), py_upper.cloned()));
if py_range.is_empty() {
// Oops, the bounds imply there is nothing that can match,
// so we always evaluate to false.
return NodeId::FALSE;
}
let mut new = SmallVec::new();
for &(ref range, node) in edges {
let overlap = range.intersection(&py_range);
if overlap.is_empty() {
continue;
}
new.push((overlap.clone(), node));
}
// Now that we know the only ranges left are those that
// intersect with our lower/upper Python version bounds, we
// can "extend" out the lower/upper bounds here all the way to
// negative and positive infinity, respectively.
//
// This has the effect of producing a marker that is only
// applicable in a context where the Python lower/upper bounds
// are known to be satisfied.
let &(ref first_range, first_node_id) = new.first().unwrap();
let first_upper = first_range.bounding_range().unwrap().1;
let clipped = Ranges::from_range_bounds((Bound::Unbounded, first_upper.cloned()));
*new.first_mut().unwrap() = (clipped, first_node_id);
let &(ref last_range, last_node_id) = new.last().unwrap();
let last_lower = last_range.bounding_range().unwrap().0;
let clipped = Ranges::from_range_bounds((last_lower.cloned(), Bound::Unbounded));
*new.last_mut().unwrap() = (clipped, last_node_id);
self.create_node(node.var.clone(), Edges::Version { edges: new })
.negate(i)
}
/// Complexify this tree by requiring the given Python version
/// range to be true in order for this marker tree to evaluate to
/// true in all circumstances.
///
/// For example, with `requires-python = '>=3.8'` and a marker tree of
/// `python_full_version <= '3.10'`, this would result in a marker of
/// `python_full_version >= '3.8' and python_full_version <= '3.10'`.
pub(crate) fn complexify_python_versions(
&mut self,
i: NodeId,
py_lower: Bound<&Version>,
py_upper: Bound<&Version>,
) -> NodeId {
if matches!(i, NodeId::FALSE)
|| matches!((py_lower, py_upper), (Bound::Unbounded, Bound::Unbounded))
{
return i;
}
let py_range = Ranges::from_range_bounds((py_lower.cloned(), py_upper.cloned()));
if py_range.is_empty() {
// Oops, the bounds imply there is nothing that can match,
// so we always evaluate to false.
return NodeId::FALSE;
}
if matches!(i, NodeId::TRUE) {
let var = Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion);
let edges = Edges::Version {
edges: Edges::from_range(&py_range),
};
return self.create_node(var, edges).negate(i);
}
let node = self.shared.node(i);
let Node {
var: Variable::Version(CanonicalMarkerValueVersion::PythonFullVersion),
children: Edges::Version { edges },
} = node
else {
// Complexify all nodes recursively.
let children = node.children.map(i, |node_id| {
self.complexify_python_versions(node_id, py_lower, py_upper)
});
return self.create_node(node.var.clone(), children);
};
// The approach we take here is to filter out any range that
// has no intersection with our Python lower/upper bounds.
// These ranges will now always be false, so we can dismiss
// them entirely.
//
// Then, depending on whether we have finite lower/upper bound,
// we "fix up" the edges by clipping the existing ranges and
// adding an additional range that covers the Python versions
// outside of our bounds by always mapping them to false.
let mut new: SmallVec<_> = edges
.iter()
.filter(|(range, _)| !py_range.intersection(range).is_empty())
.cloned()
.collect();
// Below, we assume `new` has at least one element. It's
// subtle, but since 1) edges is a disjoint covering of the
// universe and 2) our `py_range` is non-empty at this point,
// it must intersect with at least one range.
assert!(
!new.is_empty(),
"expected at least one non-empty intersection"
);
// This is the NodeId we map to anything that should
// always be false. We have to "negate" it in case the
// parent is negated.
let exclude_node_id = NodeId::FALSE.negate(i);
if !matches!(py_lower, Bound::Unbounded) {
let &(ref first_range, first_node_id) = new.first().unwrap();
let first_upper = first_range.bounding_range().unwrap().1;
// When the first range is always false, then we can just
// "expand" it out to negative infinity to reflect that
// anything less than our lower bound should evaluate to
// false. If we don't do this, then we could have two
// adjacent ranges map to the same node, which would not be
// a canonical representation.
if exclude_node_id == first_node_id {
let clipped = Ranges::from_range_bounds((Bound::Unbounded, first_upper.cloned()));
*new.first_mut().unwrap() = (clipped, first_node_id);
} else {
let clipped = Ranges::from_range_bounds((py_lower.cloned(), first_upper.cloned()));
*new.first_mut().unwrap() = (clipped, first_node_id);
let py_range_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-pep508/src/marker/simplify.rs | crates/uv-pep508/src/marker/simplify.rs | use std::fmt;
use std::ops::Bound;
use arcstr::ArcStr;
use indexmap::IndexMap;
use itertools::Itertools;
use rustc_hash::FxBuildHasher;
use version_ranges::Ranges;
use uv_pep440::{Version, VersionSpecifier};
use crate::marker::tree::ContainerOperator;
use crate::{ExtraOperator, MarkerExpression, MarkerOperator, MarkerTree, MarkerTreeKind};
/// Returns a simplified DNF expression for a given marker tree.
///
/// Marker trees are represented as decision diagrams that cannot be directly serialized to.
/// a boolean expression. Instead, you must traverse and collect all possible solutions to the
/// diagram, which can be used to create a DNF expression, or all non-solutions to the diagram,
/// which can be used to create a CNF expression.
///
/// We choose DNF as it is easier to simplify for user-facing output.
pub(crate) fn to_dnf(tree: MarkerTree) -> Vec<Vec<MarkerExpression>> {
let mut dnf = Vec::new();
collect_dnf(tree, &mut dnf, &mut Vec::new());
simplify(&mut dnf);
sort(&mut dnf);
dnf
}
/// Walk a [`MarkerTree`] recursively and construct a DNF expression.
///
/// A decision diagram can be converted to DNF form by performing a depth-first traversal of
/// the tree and collecting all paths to a `true` terminal node.
///
/// `path` is the list of marker expressions traversed on the current path.
fn collect_dnf(
tree: MarkerTree,
dnf: &mut Vec<Vec<MarkerExpression>>,
path: &mut Vec<MarkerExpression>,
) {
match tree.kind() {
// Reached a `false` node, meaning the conjunction is irrelevant for DNF.
MarkerTreeKind::False => {}
// Reached a solution, store the conjunction.
MarkerTreeKind::True => {
if !path.is_empty() {
dnf.push(path.clone());
}
}
MarkerTreeKind::Version(marker) => {
for (tree, range) in collect_edges(marker.edges()) {
// Detect whether the range for this edge can be simplified as an inequality.
if let Some(excluded) = range_inequality(&range) {
let current = path.len();
for version in excluded {
path.push(MarkerExpression::Version {
key: marker.key().into(),
specifier: VersionSpecifier::not_equals_version(version.clone()),
});
}
collect_dnf(tree, dnf, path);
path.truncate(current);
continue;
}
// Detect whether the range for this edge can be simplified as a star specifier.
if let Some(specifier) = star_range_specifier(&range) {
path.push(MarkerExpression::Version {
key: marker.key().into(),
specifier,
});
collect_dnf(tree, dnf, path);
path.pop();
continue;
}
for bounds in range.iter() {
let current = path.len();
for specifier in VersionSpecifier::from_release_only_bounds(bounds) {
path.push(MarkerExpression::Version {
key: marker.key().into(),
specifier,
});
}
collect_dnf(tree, dnf, path);
path.truncate(current);
}
}
}
MarkerTreeKind::String(marker) => {
for (tree, range) in collect_edges(marker.children()) {
// Detect whether the range for this edge can be simplified as an inequality.
if let Some(excluded) = range_inequality(&range) {
let current = path.len();
for value in excluded {
path.push(MarkerExpression::String {
key: marker.key().into(),
operator: MarkerOperator::NotEqual,
value: value.clone(),
});
}
collect_dnf(tree, dnf, path);
path.truncate(current);
continue;
}
for bounds in range.iter() {
let current = path.len();
for (operator, value) in MarkerOperator::from_bounds(bounds) {
path.push(MarkerExpression::String {
key: marker.key().into(),
operator,
value: value.clone(),
});
}
collect_dnf(tree, dnf, path);
path.truncate(current);
}
}
}
MarkerTreeKind::In(marker) => {
for (value, tree) in marker.children() {
let operator = if value {
MarkerOperator::In
} else {
MarkerOperator::NotIn
};
let expr = MarkerExpression::String {
key: marker.key().into(),
value: ArcStr::from(marker.value()),
operator,
};
path.push(expr);
collect_dnf(tree, dnf, path);
path.pop();
}
}
MarkerTreeKind::Contains(marker) => {
for (value, tree) in marker.children() {
let operator = if value {
MarkerOperator::Contains
} else {
MarkerOperator::NotContains
};
let expr = MarkerExpression::String {
key: marker.key().into(),
value: ArcStr::from(marker.value()),
operator,
};
path.push(expr);
collect_dnf(tree, dnf, path);
path.pop();
}
}
MarkerTreeKind::List(marker) => {
for (is_high, tree) in marker.children() {
let expr = MarkerExpression::List {
pair: marker.pair().clone(),
operator: if is_high {
ContainerOperator::In
} else {
ContainerOperator::NotIn
},
};
path.push(expr);
collect_dnf(tree, dnf, path);
path.pop();
}
}
MarkerTreeKind::Extra(marker) => {
for (value, tree) in marker.children() {
let operator = if value {
ExtraOperator::Equal
} else {
ExtraOperator::NotEqual
};
let expr = MarkerExpression::Extra {
name: marker.name().clone().into(),
operator,
};
path.push(expr);
collect_dnf(tree, dnf, path);
path.pop();
}
}
}
}
/// Simplifies a DNF expression.
///
/// A decision diagram is canonical, but only for a given variable order. Depending on the
/// pre-defined order, the DNF expression produced by a decision tree can still be further
/// simplified.
///
/// For example, the decision diagram for the expression `A or B` will be represented as
/// `A or (not A and B)` or `B or (not B and A)`, depending on the variable order. In both
/// cases, the negation in the second clause is redundant.
///
/// Completely simplifying a DNF expression is NP-hard and amounts to the set cover problem.
/// Additionally, marker expressions can contain complex expressions involving version ranges
/// that are not trivial to simplify. Instead, we choose to simplify at the boolean variable
/// level without any truth table expansion. Combined with the normalization applied by decision
/// trees, this seems to be sufficient in practice.
///
/// Note: This function has quadratic time complexity. However, it is not applied on every marker
/// operation, only to user facing output, which are typically very simple.
fn simplify(dnf: &mut Vec<Vec<MarkerExpression>>) {
for i in 0..dnf.len() {
let clause = &dnf[i];
// Find redundant terms in this clause.
let mut redundant_terms = Vec::new();
'term: for (skipped, skipped_term) in clause.iter().enumerate() {
for (j, other_clause) in dnf.iter().enumerate() {
if i == j {
continue;
}
// Let X be this clause with a given term A set to it's negation.
// If there exists another clause that is a subset of X, the term A is
// redundant in this clause.
//
// For example, `A or (not A and B)` can be simplified to `A or B`,
// eliminating the `not A` term.
if other_clause.iter().all(|term| {
// For the term to be redundant in this clause, the other clause can
// contain the negation of the term but not the term itself.
if term == skipped_term {
return false;
}
if is_negation(term, skipped_term) {
return true;
}
// TODO(ibraheem): if we intern variables we could reduce this
// from a linear search to an integer `HashSet` lookup
clause
.iter()
.position(|x| x == term)
// If the term was already removed from this one, we cannot
// depend on it for further simplification.
.is_some_and(|i| !redundant_terms.contains(&i))
}) {
redundant_terms.push(skipped);
continue 'term;
}
}
}
// Eliminate any redundant terms.
redundant_terms.sort_by(|a, b| b.cmp(a));
for term in redundant_terms {
dnf[i].remove(term);
}
}
// Once we have eliminated redundant terms, there may also be redundant clauses.
// For example, `(A and B) or (not A and B)` would have been simplified above to
// `(A and B) or B` and can now be further simplified to just `B`.
let mut redundant_clauses = Vec::new();
'clause: for i in 0..dnf.len() {
let clause = &dnf[i];
for (j, other_clause) in dnf.iter().enumerate() {
// Ignore clauses that are going to be eliminated.
if i == j || redundant_clauses.contains(&j) {
continue;
}
// There is another clause that is a subset of this one, thus this clause is redundant.
if other_clause.iter().all(|term| {
// TODO(ibraheem): if we intern variables we could reduce this
// from a linear search to an integer `HashSet` lookup
clause.contains(term)
}) {
redundant_clauses.push(i);
continue 'clause;
}
}
}
// Eliminate any redundant clauses.
for i in redundant_clauses.into_iter().rev() {
dnf.remove(i);
}
}
/// Sort the clauses in a DNF expression, for backwards compatibility. The goal is to avoid
/// unnecessary churn in the display output of the marker expressions, e.g., when modifying the
/// internal representations used in the marker algebra.
fn sort(dnf: &mut [Vec<MarkerExpression>]) {
// Sort each clause.
for clause in dnf.iter_mut() {
clause.sort_by_key(MarkerExpression::kind);
}
// Sort the clauses.
dnf.sort_by(|a, b| {
a.iter()
.map(MarkerExpression::kind)
.cmp(b.iter().map(MarkerExpression::kind))
});
}
/// Merge any edges that lead to identical subtrees into a single range.
pub(crate) fn collect_edges<'a, T>(
map: impl ExactSizeIterator<Item = (&'a Ranges<T>, MarkerTree)>,
) -> IndexMap<MarkerTree, Ranges<T>, FxBuildHasher>
where
T: Ord + Clone + 'a,
{
let mut paths: IndexMap<_, Ranges<_>, FxBuildHasher> = IndexMap::default();
for (range, tree) in map {
// OK because all ranges are guaranteed to be non-empty.
let (start, end) = range.bounding_range().unwrap();
// Combine the ranges.
let range = Ranges::from_range_bounds((start.cloned(), end.cloned()));
paths
.entry(tree)
.and_modify(|union| *union = union.union(&range))
.or_insert_with(|| range.clone());
}
paths
}
/// Returns `Some` if the expression can be simplified as an inequality consisting
/// of the given values.
///
/// For example, `os_name < 'Linux' or os_name > 'Linux'` can be simplified to
/// `os_name != 'Linux'`.
fn range_inequality<T>(range: &Ranges<T>) -> Option<Vec<&T>>
where
T: Ord + Clone + fmt::Debug,
{
if range.is_empty() || range.bounding_range() != Some((Bound::Unbounded, Bound::Unbounded)) {
return None;
}
let mut excluded = Vec::new();
for ((_, end), (start, _)) in range.iter().tuple_windows() {
match (end, start) {
(Bound::Excluded(v1), Bound::Excluded(v2)) if v1 == v2 => excluded.push(v1),
_ => return None,
}
}
Some(excluded)
}
/// Returns `Some` if the version range can be simplified as a star specifier.
///
/// Only for the two bounds case not covered by [`VersionSpecifier::from_release_only_bounds`].
///
/// For negative ranges like `python_full_version < '3.8' or python_full_version >= '3.9'`,
/// returns `!= '3.8.*'`.
fn star_range_specifier(range: &Ranges<Version>) -> Option<VersionSpecifier> {
if range.iter().count() != 2 {
return None;
}
// Check for negative star range: two segments [(Unbounded, Excluded(v1)), (Included(v2), Unbounded)]
let (b1, b2) = range.iter().collect_tuple()?;
if let ((Bound::Unbounded, Bound::Excluded(v1)), (Bound::Included(v2), Bound::Unbounded)) =
(b1, b2)
{
match *v1.only_release_trimmed().release() {
[major] if *v2.release() == [major, 1] => {
Some(VersionSpecifier::not_equals_star_version(Version::new([
major, 0,
])))
}
[major, minor] if *v2.release() == [major, minor + 1] => {
Some(VersionSpecifier::not_equals_star_version(v1.clone()))
}
_ => None,
}
} else {
None
}
}
/// Returns `true` if the LHS is the negation of the RHS, or vice versa.
fn is_negation(left: &MarkerExpression, right: &MarkerExpression) -> bool {
match left {
MarkerExpression::Version { key, specifier } => {
let MarkerExpression::Version {
key: key2,
specifier: specifier2,
} = right
else {
return false;
};
key == key2
&& specifier.version() == specifier2.version()
&& specifier
.operator()
.negate()
.is_some_and(|negated| negated == *specifier2.operator())
}
MarkerExpression::VersionIn {
key,
versions,
operator,
} => {
let MarkerExpression::VersionIn {
key: key2,
versions: versions2,
operator: operator2,
} = right
else {
return false;
};
key == key2 && versions == versions2 && operator != operator2
}
MarkerExpression::String {
key,
operator,
value,
} => {
let MarkerExpression::String {
key: key2,
operator: operator2,
value: value2,
} = right
else {
return false;
};
key == key2
&& value == value2
&& operator
.negate()
.is_some_and(|negated| negated == *operator2)
}
MarkerExpression::Extra { operator, name } => {
let MarkerExpression::Extra {
name: name2,
operator: operator2,
} = right
else {
return false;
};
name == name2 && operator.negate() == *operator2
}
MarkerExpression::List { pair, operator } => {
let MarkerExpression::List {
pair: pair2,
operator: operator2,
} = right
else {
return false;
};
pair == pair2 && operator != operator2
}
}
}
| 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-pep508/src/marker/tree.rs | crates/uv-pep508/src/marker/tree.rs | use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt::{self, Display, Formatter};
use std::ops::{Bound, Deref};
use std::str::FromStr;
use arcstr::ArcStr;
use itertools::Itertools;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use version_ranges::Ranges;
use uv_normalize::{ExtraName, GroupName};
use uv_pep440::{Version, VersionParseError, VersionSpecifier};
use super::algebra::{Edges, INTERNER, NodeId, Variable};
use super::simplify;
use crate::cursor::Cursor;
use crate::marker::lowering::{
CanonicalMarkerListPair, CanonicalMarkerValueString, CanonicalMarkerValueVersion,
};
use crate::marker::parse;
use crate::{
CanonicalMarkerValueExtra, MarkerEnvironment, Pep508Error, Pep508ErrorSource, Pep508Url,
Reporter, TracingReporter,
};
/// Ways in which marker evaluation can fail
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerWarningKind {
/// Using an old name from PEP 345 instead of the modern equivalent
/// <https://peps.python.org/pep-0345/#environment-markers>
DeprecatedMarkerName,
/// Doing an operation other than `==` and `!=` on a quoted string with `extra`, such as
/// `extra > "perf"` or `extra == os_name`
ExtraInvalidComparison,
/// Doing an operation other than `in` and `not in` on a quoted string with `extra`, such as
/// `extras > "perf"` or `extras == os_name`
ExtrasInvalidComparison,
/// Doing an operation other than `in` and `not in` on a quoted string with `dependency_groups`,
/// such as `dependency_groups > "perf"` or `dependency_groups == os_name`
DependencyGroupsInvalidComparison,
/// Comparing a string valued marker and a string lexicographically, such as `"3.9" > "3.10"`
LexicographicComparison,
/// Comparing two markers, such as `os_name != sys_implementation`
MarkerMarkerComparison,
/// Failed to parse a PEP 440 version or version specifier, e.g. `>=1<2`
Pep440Error,
/// Comparing two strings, such as `"3.9" > "3.10"`
StringStringComparison,
}
/// Those environment markers with a PEP 440 version as value such as `python_version`
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[allow(clippy::enum_variant_names)]
pub enum MarkerValueVersion {
/// `implementation_version`
ImplementationVersion,
/// `python_full_version`
PythonFullVersion,
/// `python_version`
PythonVersion,
}
impl Display for MarkerValueVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ImplementationVersion => f.write_str("implementation_version"),
Self::PythonFullVersion => f.write_str("python_full_version"),
Self::PythonVersion => f.write_str("python_version"),
}
}
}
/// Those environment markers with an arbitrary string as value such as `sys_platform`
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerValueString {
/// `implementation_name`
ImplementationName,
/// `os_name`
OsName,
/// Deprecated `os.name` from <https://peps.python.org/pep-0345/#environment-markers>
OsNameDeprecated,
/// `platform_machine`
PlatformMachine,
/// Deprecated `platform.machine` from <https://peps.python.org/pep-0345/#environment-markers>
PlatformMachineDeprecated,
/// `platform_python_implementation`
PlatformPythonImplementation,
/// Deprecated `platform.python_implementation` from <https://peps.python.org/pep-0345/#environment-markers>
PlatformPythonImplementationDeprecated,
/// Deprecated `python_implementation` from <https://github.com/pypa/packaging/issues/72>
PythonImplementationDeprecated,
/// `platform_release`
PlatformRelease,
/// `platform_system`
PlatformSystem,
/// `platform_version`
PlatformVersion,
/// Deprecated `platform.version` from <https://peps.python.org/pep-0345/#environment-markers>
PlatformVersionDeprecated,
/// `sys_platform`
SysPlatform,
/// Deprecated `sys.platform` from <https://peps.python.org/pep-0345/#environment-markers>
SysPlatformDeprecated,
}
impl Display for MarkerValueString {
/// Normalizes deprecated names to the proper ones
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ImplementationName => f.write_str("implementation_name"),
Self::OsName | Self::OsNameDeprecated => f.write_str("os_name"),
Self::PlatformMachine | Self::PlatformMachineDeprecated => {
f.write_str("platform_machine")
}
Self::PlatformPythonImplementation
| Self::PlatformPythonImplementationDeprecated
| Self::PythonImplementationDeprecated => f.write_str("platform_python_implementation"),
Self::PlatformRelease => f.write_str("platform_release"),
Self::PlatformSystem => f.write_str("platform_system"),
Self::PlatformVersion | Self::PlatformVersionDeprecated => {
f.write_str("platform_version")
}
Self::SysPlatform | Self::SysPlatformDeprecated => f.write_str("sys_platform"),
}
}
}
/// Those markers with exclusively `in` and `not in` operators.
///
/// Contains PEP 751 lockfile markers.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerValueList {
/// `extras`. This one is special because it's a list, and user-provided
Extras,
/// `dependency_groups`. This one is special because it's a list, and user-provided
DependencyGroups,
}
impl Display for MarkerValueList {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Extras => f.write_str("extras"),
Self::DependencyGroups => f.write_str("dependency_groups"),
}
}
}
/// One of the predefined environment values
///
/// <https://packaging.python.org/en/latest/specifications/dependency-specifiers/#environment-markers>
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerValue {
/// Those environment markers with a PEP 440 version as value such as `python_version`
MarkerEnvVersion(MarkerValueVersion),
/// Those environment markers with an arbitrary string as value such as `sys_platform`
MarkerEnvString(MarkerValueString),
/// Those markers with exclusively `in` and `not in` operators
MarkerEnvList(MarkerValueList),
/// `extra`. This one is special because it's a list, and user-provided
Extra,
/// Not a constant, but a user given quoted string with a value inside such as '3.8' or "windows"
QuotedString(ArcStr),
}
impl FromStr for MarkerValue {
type Err = String;
/// This is specifically for the reserved values
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = match s {
"implementation_name" => Self::MarkerEnvString(MarkerValueString::ImplementationName),
"implementation_version" => {
Self::MarkerEnvVersion(MarkerValueVersion::ImplementationVersion)
}
"os_name" => Self::MarkerEnvString(MarkerValueString::OsName),
"os.name" => Self::MarkerEnvString(MarkerValueString::OsNameDeprecated),
"platform_machine" => Self::MarkerEnvString(MarkerValueString::PlatformMachine),
"platform.machine" => {
Self::MarkerEnvString(MarkerValueString::PlatformMachineDeprecated)
}
"platform_python_implementation" => {
Self::MarkerEnvString(MarkerValueString::PlatformPythonImplementation)
}
"platform.python_implementation" => {
Self::MarkerEnvString(MarkerValueString::PlatformPythonImplementationDeprecated)
}
"python_implementation" => {
Self::MarkerEnvString(MarkerValueString::PythonImplementationDeprecated)
}
"platform_release" => Self::MarkerEnvString(MarkerValueString::PlatformRelease),
"platform_system" => Self::MarkerEnvString(MarkerValueString::PlatformSystem),
"platform_version" => Self::MarkerEnvString(MarkerValueString::PlatformVersion),
"platform.version" => {
Self::MarkerEnvString(MarkerValueString::PlatformVersionDeprecated)
}
"python_full_version" => Self::MarkerEnvVersion(MarkerValueVersion::PythonFullVersion),
"python_version" => Self::MarkerEnvVersion(MarkerValueVersion::PythonVersion),
"sys_platform" => Self::MarkerEnvString(MarkerValueString::SysPlatform),
"sys.platform" => Self::MarkerEnvString(MarkerValueString::SysPlatformDeprecated),
"extras" => Self::MarkerEnvList(MarkerValueList::Extras),
"dependency_groups" => Self::MarkerEnvList(MarkerValueList::DependencyGroups),
"extra" => Self::Extra,
_ => return Err(format!("Invalid key: {s}")),
};
Ok(value)
}
}
impl Display for MarkerValue {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::MarkerEnvVersion(marker_value_version) => marker_value_version.fmt(f),
Self::MarkerEnvString(marker_value_string) => marker_value_string.fmt(f),
Self::MarkerEnvList(marker_value_contains) => marker_value_contains.fmt(f),
Self::Extra => f.write_str("extra"),
Self::QuotedString(value) => write!(f, "'{value}'"),
}
}
}
/// How to compare key and value, such as by `==`, `>` or `not in`
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerOperator {
/// `==`
Equal,
/// `!=`
NotEqual,
/// `>`
GreaterThan,
/// `>=`
GreaterEqual,
/// `<`
LessThan,
/// `<=`
LessEqual,
/// `~=`
TildeEqual,
/// `in`
In,
/// `not in`
NotIn,
/// The inverse of the `in` operator.
///
/// This is not a valid operator when parsing but is used for normalizing
/// marker trees.
Contains,
/// The inverse of the `not in` operator.
///
/// This is not a valid operator when parsing but is used for normalizing
/// marker trees.
NotContains,
}
impl MarkerOperator {
/// Compare two versions, returning `None` for `in` and `not in`.
pub(crate) fn to_pep440_operator(self) -> Option<uv_pep440::Operator> {
match self {
Self::Equal => Some(uv_pep440::Operator::Equal),
Self::NotEqual => Some(uv_pep440::Operator::NotEqual),
Self::GreaterThan => Some(uv_pep440::Operator::GreaterThan),
Self::GreaterEqual => Some(uv_pep440::Operator::GreaterThanEqual),
Self::LessThan => Some(uv_pep440::Operator::LessThan),
Self::LessEqual => Some(uv_pep440::Operator::LessThanEqual),
Self::TildeEqual => Some(uv_pep440::Operator::TildeEqual),
_ => None,
}
}
/// Inverts this marker operator.
pub(crate) fn invert(self) -> Self {
match self {
Self::LessThan => Self::GreaterThan,
Self::LessEqual => Self::GreaterEqual,
Self::GreaterThan => Self::LessThan,
Self::GreaterEqual => Self::LessEqual,
Self::Equal => Self::Equal,
Self::NotEqual => Self::NotEqual,
Self::TildeEqual => Self::TildeEqual,
Self::In => Self::Contains,
Self::NotIn => Self::NotContains,
Self::Contains => Self::In,
Self::NotContains => Self::NotIn,
}
}
/// Negates this marker operator.
///
/// If a negation doesn't exist, which is only the case for ~=, then this
/// returns `None`.
pub(crate) fn negate(self) -> Option<Self> {
Some(match self {
Self::Equal => Self::NotEqual,
Self::NotEqual => Self::Equal,
Self::TildeEqual => return None,
Self::LessThan => Self::GreaterEqual,
Self::LessEqual => Self::GreaterThan,
Self::GreaterThan => Self::LessEqual,
Self::GreaterEqual => Self::LessThan,
Self::In => Self::NotIn,
Self::NotIn => Self::In,
Self::Contains => Self::NotContains,
Self::NotContains => Self::Contains,
})
}
/// Returns the marker operator and value whose union represents the given range.
pub fn from_bounds(
bounds: (&Bound<ArcStr>, &Bound<ArcStr>),
) -> impl Iterator<Item = (Self, ArcStr)> {
let (b1, b2) = match bounds {
(Bound::Included(v1), Bound::Included(v2)) if v1 == v2 => {
(Some((Self::Equal, v1.clone())), None)
}
(Bound::Excluded(v1), Bound::Excluded(v2)) if v1 == v2 => {
(Some((Self::NotEqual, v1.clone())), None)
}
(lower, upper) => (Self::from_lower_bound(lower), Self::from_upper_bound(upper)),
};
b1.into_iter().chain(b2)
}
/// Returns a value specifier representing the given lower bound.
pub fn from_lower_bound(bound: &Bound<ArcStr>) -> Option<(Self, ArcStr)> {
match bound {
Bound::Included(value) => Some((Self::GreaterEqual, value.clone())),
Bound::Excluded(value) => Some((Self::GreaterThan, value.clone())),
Bound::Unbounded => None,
}
}
/// Returns a value specifier representing the given upper bound.
pub fn from_upper_bound(bound: &Bound<ArcStr>) -> Option<(Self, ArcStr)> {
match bound {
Bound::Included(value) => Some((Self::LessEqual, value.clone())),
Bound::Excluded(value) => Some((Self::LessThan, value.clone())),
Bound::Unbounded => None,
}
}
}
impl FromStr for MarkerOperator {
type Err = String;
/// PEP 508 allows arbitrary whitespace between "not" and "in", and so do we
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = match s {
"==" => Self::Equal,
"!=" => Self::NotEqual,
">" => Self::GreaterThan,
">=" => Self::GreaterEqual,
"<" => Self::LessThan,
"<=" => Self::LessEqual,
"~=" => Self::TildeEqual,
"in" => Self::In,
not_space_in
if not_space_in
// start with not
.strip_prefix("not")
// ends with in
.and_then(|space_in| space_in.strip_suffix("in"))
// and has only whitespace in between
.is_some_and(|space| !space.is_empty() && space.trim().is_empty()) =>
{
Self::NotIn
}
other => return Err(format!("Invalid comparator: {other}")),
};
Ok(value)
}
}
impl Display for MarkerOperator {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Equal => "==",
Self::NotEqual => "!=",
Self::GreaterThan => ">",
Self::GreaterEqual => ">=",
Self::LessThan => "<",
Self::LessEqual => "<=",
Self::TildeEqual => "~=",
Self::In | Self::Contains => "in",
Self::NotIn | Self::NotContains => "not in",
})
}
}
/// Helper type with a [Version] and its original text
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct StringVersion {
/// Original unchanged string
pub string: String,
/// Parsed version
pub version: Version,
}
impl From<Version> for StringVersion {
fn from(version: Version) -> Self {
Self {
string: version.to_string(),
version,
}
}
}
impl FromStr for StringVersion {
type Err = VersionParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
string: s.to_string(),
version: Version::from_str(s)?,
})
}
}
impl Display for StringVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.string.fmt(f)
}
}
impl Serialize for StringVersion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.string)
}
}
impl<'de> Deserialize<'de> for StringVersion {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = StringVersion;
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
StringVersion::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Deref for StringVersion {
type Target = Version;
fn deref(&self) -> &Self::Target {
&self.version
}
}
/// The [`ExtraName`] value used in `extra` and `extras` markers.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum MarkerValueExtra {
/// A valid [`ExtraName`].
Extra(ExtraName),
/// An invalid name, preserved as an arbitrary string.
Arbitrary(String),
}
impl MarkerValueExtra {
/// Returns the [`ExtraName`] for this value, if it is a valid extra.
pub fn as_extra(&self) -> Option<&ExtraName> {
match self {
Self::Extra(extra) => Some(extra),
Self::Arbitrary(_) => None,
}
}
/// Convert the [`MarkerValueExtra`] to an [`ExtraName`], if possible.
fn into_extra(self) -> Option<ExtraName> {
match self {
Self::Extra(extra) => Some(extra),
Self::Arbitrary(_) => None,
}
}
}
impl Display for MarkerValueExtra {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Extra(extra) => extra.fmt(f),
Self::Arbitrary(string) => string.fmt(f),
}
}
}
/// Represents one clause such as `python_version > "3.8"`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[allow(missing_docs)]
pub enum MarkerExpression {
/// A version expression, e.g. `<version key> <version op> <quoted PEP 440 version>`.
///
/// Inverted version expressions, such as `<version> <version op> <version key>`, are also
/// normalized to this form.
Version {
key: MarkerValueVersion,
specifier: VersionSpecifier,
},
/// A version in list expression, e.g. `<version key> in <quoted list of PEP 440 versions>`.
///
/// A special case of [`MarkerExpression::String`] with the [`MarkerOperator::In`] operator for
/// [`MarkerValueVersion`] values.
///
/// See [`parse::parse_version_in_expr`] for details on the supported syntax.
///
/// Negated expressions, using "not in" are represented using `negated = true`.
VersionIn {
key: MarkerValueVersion,
versions: Vec<Version>,
operator: ContainerOperator,
},
/// An string marker comparison, e.g. `sys_platform == '...'`.
///
/// Inverted string expressions, e.g `'...' == sys_platform`, are also normalized to this form.
String {
key: MarkerValueString,
operator: MarkerOperator,
value: ArcStr,
},
/// `'...' in <key>`, a PEP 751 expression.
List {
pair: CanonicalMarkerListPair,
operator: ContainerOperator,
},
/// `extra <extra op> '...'` or `'...' <extra op> extra`.
Extra {
name: MarkerValueExtra,
operator: ExtraOperator,
},
}
/// The kind of a [`MarkerExpression`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub(crate) enum MarkerExpressionKind {
/// A version expression, e.g. `<version key> <version op> <quoted PEP 440 version>`.
Version(MarkerValueVersion),
/// A version `in` expression, e.g. `<version key> in <quoted list of PEP 440 versions>`.
VersionIn(MarkerValueVersion),
/// A string marker comparison, e.g. `sys_platform == '...'`.
String(MarkerValueString),
/// A list `in` or `not in` expression, e.g. `'...' in dependency_groups`.
List(MarkerValueList),
/// An extra expression, e.g. `extra == '...'`.
Extra,
}
/// The operator for an extra expression, either '==' or '!='.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum ExtraOperator {
/// `==`
Equal,
/// `!=`
NotEqual,
}
impl ExtraOperator {
/// Creates a [`ExtraOperator`] from an equivalent [`MarkerOperator`].
///
/// Returns `None` if the operator is not supported for extras.
pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option<Self> {
match operator {
MarkerOperator::Equal => Some(Self::Equal),
MarkerOperator::NotEqual => Some(Self::NotEqual),
_ => None,
}
}
/// Negates this operator.
pub(crate) fn negate(&self) -> Self {
match self {
Self::Equal => Self::NotEqual,
Self::NotEqual => Self::Equal,
}
}
}
impl Display for ExtraOperator {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Equal => "==",
Self::NotEqual => "!=",
})
}
}
/// The operator for a container expression, either 'in' or 'not in'.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum ContainerOperator {
/// `in`
In,
/// `not in`
NotIn,
}
impl ContainerOperator {
/// Creates a [`ContainerOperator`] from an equivalent [`MarkerOperator`].
///
/// Returns `None` if the operator is not supported for containers.
pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option<Self> {
match operator {
MarkerOperator::In => Some(Self::In),
MarkerOperator::NotIn => Some(Self::NotIn),
_ => None,
}
}
}
impl Display for ContainerOperator {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::In => "in",
Self::NotIn => "not in",
})
}
}
impl MarkerExpression {
/// Parse a [`MarkerExpression`] from a string with the given reporter.
pub fn parse_reporter(
s: &str,
reporter: &mut impl Reporter,
) -> Result<Option<Self>, Pep508Error> {
let mut chars = Cursor::new(s);
let expression = parse::parse_marker_key_op_value(&mut chars, reporter)?;
chars.eat_whitespace();
if let Some((pos, unexpected)) = chars.next() {
return Err(Pep508Error {
message: Pep508ErrorSource::String(format!(
"Unexpected character '{unexpected}', expected end of input"
)),
start: pos,
len: chars.remaining(),
input: chars.to_string(),
});
}
Ok(expression)
}
/// Parse a [`MarkerExpression`] from a string.
///
/// Returns `None` if the expression consists entirely of meaningless expressions
/// that are ignored, such as `os_name ~= 'foo'`.
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Result<Option<Self>, Pep508Error> {
Self::parse_reporter(s, &mut TracingReporter)
}
/// Return the kind of this marker expression.
pub(crate) fn kind(&self) -> MarkerExpressionKind {
match self {
Self::Version { key, .. } => MarkerExpressionKind::Version(*key),
Self::VersionIn { key, .. } => MarkerExpressionKind::VersionIn(*key),
Self::String { key, .. } => MarkerExpressionKind::String(*key),
Self::List { pair, .. } => MarkerExpressionKind::List(pair.key()),
Self::Extra { .. } => MarkerExpressionKind::Extra,
}
}
}
impl Display for MarkerExpression {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Version { key, specifier } => {
let (op, version) = (specifier.operator(), specifier.version());
if op == &uv_pep440::Operator::EqualStar || op == &uv_pep440::Operator::NotEqualStar
{
return write!(f, "{key} {op} '{version}.*'");
}
write!(f, "{key} {op} '{version}'")
}
Self::VersionIn {
key,
versions,
operator,
} => {
let versions = versions.iter().map(ToString::to_string).join(" ");
write!(f, "{key} {operator} '{versions}'")
}
Self::String {
key,
operator,
value,
} => {
if matches!(
operator,
MarkerOperator::Contains | MarkerOperator::NotContains
) {
return write!(f, "'{value}' {} {key}", operator.invert());
}
write!(f, "{key} {operator} '{value}'")
}
Self::List { pair, operator } => {
write!(f, "'{}' {} {}", pair.value(), operator, pair.key())
}
Self::Extra { operator, name } => {
write!(f, "extra {operator} '{name}'")
}
}
}
}
/// The extra and dependency group names to use when evaluating a marker tree.
#[derive(Debug, Copy, Clone)]
enum ExtrasEnvironment<'a> {
/// E.g., `extra == '...'`
Extras(&'a [ExtraName]),
/// E.g., `'...' in extras` or `'...' in dependency_groups`
Pep751(&'a [ExtraName], &'a [GroupName]),
}
impl<'a> ExtrasEnvironment<'a> {
/// Creates a new [`ExtrasEnvironment`] for the given `extra` names.
fn from_extras(extras: &'a [ExtraName]) -> Self {
Self::Extras(extras)
}
/// Creates a new [`ExtrasEnvironment`] for the given PEP 751 `extras` and `dependency_groups`.
fn from_pep751(extras: &'a [ExtraName], dependency_groups: &'a [GroupName]) -> Self {
Self::Pep751(extras, dependency_groups)
}
/// Returns the `extra` names in this environment.
fn extra(&self) -> &[ExtraName] {
match self {
Self::Extras(extra) => extra,
Self::Pep751(..) => &[],
}
}
/// Returns the `extras` names in this environment, as in a PEP 751 lockfile.
fn extras(&self) -> &[ExtraName] {
match self {
Self::Extras(..) => &[],
Self::Pep751(extras, ..) => extras,
}
}
/// Returns the `dependency_group` group names in this environment, as in a PEP 751 lockfile.
fn dependency_groups(&self) -> &[GroupName] {
match self {
Self::Extras(..) => &[],
Self::Pep751(.., groups) => groups,
}
}
}
/// Represents one or more nested marker expressions with and/or/parentheses.
///
/// Marker trees are canonical, meaning any two functionally equivalent markers
/// will compare equally. Markers also support efficient polynomial-time operations,
/// such as conjunction and disjunction.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct MarkerTree(NodeId);
impl Default for MarkerTree {
fn default() -> Self {
Self::TRUE
}
}
impl<'de> Deserialize<'de> for MarkerTree {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = MarkerTree;
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
MarkerTree::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl FromStr for MarkerTree {
type Err = Pep508Error;
fn from_str(markers: &str) -> Result<Self, Self::Err> {
parse::parse_markers(markers, &mut TracingReporter)
}
}
impl MarkerTree {
/// Like [`FromStr::from_str`], but the caller chooses the return type generic.
pub fn parse_str<T: Pep508Url>(markers: &str) -> Result<Self, Pep508Error<T>> {
parse::parse_markers(markers, &mut TracingReporter)
}
/// Parse a [`MarkerTree`] from a string with the given reporter.
pub fn parse_reporter(
markers: &str,
reporter: &mut impl Reporter,
) -> Result<Self, Pep508Error> {
parse::parse_markers(markers, reporter)
}
/// An empty marker that always evaluates to `true`.
pub const TRUE: Self = Self(NodeId::TRUE);
/// An unsatisfiable marker that always evaluates to `false`.
pub const FALSE: Self = Self(NodeId::FALSE);
/// Returns a marker tree for a single expression.
pub fn expression(expr: MarkerExpression) -> Self {
Self(INTERNER.lock().expression(expr))
}
/// Whether the marker always evaluates to `true`.
///
/// If this method returns `true`, it is definitively known that the marker will
/// evaluate to `true` in any environment. However, this method may return false
/// negatives, i.e. it may not be able to detect that a marker is always true for
/// complex expressions.
pub fn is_true(self) -> bool {
self.0.is_true()
}
/// Whether the marker always evaluates to `false`, i.e. the expression is not
/// satisfiable in any environment.
///
/// If this method returns `true`, it is definitively known that the marker will
/// evaluate to `false` in any environment. However, this method may return false
/// negatives, i.e. it may not be able to detect that a marker is unsatisfiable
/// for complex expressions.
pub fn is_false(self) -> bool {
self.0.is_false()
}
/// Returns a new marker tree that is the negation of this one.
#[must_use]
pub fn negate(self) -> Self {
Self(self.0.not())
}
/// Combine this marker tree with the one given via a conjunction.
pub fn and(&mut self, tree: Self) {
self.0 = INTERNER.lock().and(self.0, tree.0);
}
/// Combine this marker tree with the one given via a disjunction.
pub fn or(&mut self, tree: Self) {
self.0 = INTERNER.lock().or(self.0, tree.0);
}
/// Sets this to a marker equivalent to the implication of this one and the
/// given consequent.
///
/// If the marker set is always `true`, then it can be said that `self`
/// implies `consequent`.
pub fn implies(&mut self, consequent: Self) {
// This could probably be optimized, but is clearly
// correct, since logical implication is `-P or Q`.
*self = self.negate();
self.or(consequent);
}
/// Returns `true` if there is no environment in which both marker trees can apply,
/// i.e. their conjunction is always `false`.
///
/// If this method returns `true`, it is definitively known that the two markers can
/// never both evaluate to `true` in a given environment. However, this method may return
/// false negatives, i.e. it may not be able to detect that two markers are disjoint for
/// complex expressions.
pub fn is_disjoint(self, other: Self) -> bool {
INTERNER.lock().is_disjoint(self.0, other.0)
}
/// Returns the contents of this marker tree, if it contains at least one expression.
///
/// If the marker is `true`, this method will return `None`.
/// If the marker is `false`, the marker is represented as the normalized expression, `python_version < '0'`.
///
/// The returned type implements [`Display`] and [`serde::Serialize`].
pub fn contents(self) -> Option<MarkerTreeContents> {
if self.is_true() {
return None;
}
Some(MarkerTreeContents(self))
}
/// Returns a simplified string representation of this marker, if it contains at least one
/// expression.
///
/// If the marker is `true`, this method will return `None`.
/// If the marker is `false`, the marker is represented as the normalized expression, `python_version < '0'`.
pub fn try_to_string(self) -> Option<String> {
self.contents().map(|contents| contents.to_string())
}
/// Returns the underlying [`MarkerTreeKind`] of the root node.
pub fn kind(self) -> MarkerTreeKind<'static> {
if self.is_true() {
return MarkerTreeKind::True;
| 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-pep508/src/marker/mod.rs | crates/uv-pep508/src/marker/mod.rs | //! PEP 508 markers implementations with validation and warnings
//!
//! Markers allow you to install dependencies only in specific environments (python version,
//! operating system, architecture, etc.) or when a specific feature is activated. E.g. you can
//! say `importlib-metadata ; python_version < "3.8"` or
//! `itsdangerous (>=1.1.0) ; extra == 'security'`. Unfortunately, the marker grammar has some
//! oversights (e.g. <https://github.com/pypa/packaging.python.org/pull/1181>) and
//! the design of comparisons (PEP 440 comparisons with lexicographic fallback) leads to confusing
//! outcomes. This implementation tries to carefully validate everything and emit warnings whenever
//! bogus comparisons with unintended semantics are made.
mod algebra;
mod environment;
mod lowering;
pub(crate) mod parse;
mod simplify;
mod tree;
pub use environment::{MarkerEnvironment, MarkerEnvironmentBuilder};
pub use lowering::{
CanonicalMarkerValueExtra, CanonicalMarkerValueString, CanonicalMarkerValueVersion,
};
pub use tree::{
ContainsMarkerTree, ExtraMarkerTree, ExtraOperator, InMarkerTree, MarkerExpression,
MarkerOperator, MarkerTree, MarkerTreeContents, MarkerTreeDebugGraph, MarkerTreeKind,
MarkerValue, MarkerValueExtra, MarkerValueList, MarkerValueString, MarkerValueVersion,
MarkerWarningKind, StringMarkerTree, StringVersion, VersionMarkerTree,
};
/// `serde` helpers for [`MarkerTree`].
pub mod ser {
use super::MarkerTree;
use serde::Serialize;
/// A helper for `serde(skip_serializing_if)`.
pub fn is_empty(marker: &MarkerTree) -> bool {
marker.contents().is_none()
}
/// A helper for `serde(serialize_with)`.
///
/// Note this will panic if `marker.contents()` is `None`, and so should be paired with `is_empty`.
pub fn serialize<S>(marker: &MarkerTree, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
marker.contents().unwrap().serialize(s)
}
}
| 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-pep508/src/marker/lowering.rs | crates/uv-pep508/src/marker/lowering.rs | use std::fmt::{Display, Formatter};
use uv_normalize::{ExtraName, GroupName};
use crate::marker::tree::MarkerValueList;
use crate::{MarkerValueExtra, MarkerValueString, MarkerValueVersion};
/// Those environment markers with a PEP 440 version as value such as `python_version`
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[allow(clippy::enum_variant_names)]
pub enum CanonicalMarkerValueVersion {
/// `implementation_version`
ImplementationVersion,
/// `python_full_version`
PythonFullVersion,
}
impl Display for CanonicalMarkerValueVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::ImplementationVersion => f.write_str("implementation_version"),
Self::PythonFullVersion => f.write_str("python_full_version"),
}
}
}
impl From<CanonicalMarkerValueVersion> for MarkerValueVersion {
fn from(value: CanonicalMarkerValueVersion) -> Self {
match value {
CanonicalMarkerValueVersion::ImplementationVersion => Self::ImplementationVersion,
CanonicalMarkerValueVersion::PythonFullVersion => Self::PythonFullVersion,
}
}
}
/// Those environment markers with an arbitrary string as value such as `sys_platform`.
///
/// As in [`crate::marker::algebra::Variable`], this `enum` also defines the variable ordering for
/// all ADDs, which is in turn used when translating the ADD to DNF. As such, modifying the ordering
/// will modify the output of marker expressions.
///
/// Critically, any variants that could be involved in a known-incompatible marker pair should
/// be at the top of the ordering, i.e., given the maximum priority.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum CanonicalMarkerValueString {
/// `os_name`
OsName,
/// `sys_platform`
SysPlatform,
/// `platform_system`
PlatformSystem,
/// `platform_machine`
PlatformMachine,
/// Deprecated `platform.machine` from <https://peps.python.org/pep-0345/#environment-markers>
/// `platform_python_implementation`
PlatformPythonImplementation,
/// `platform_release`
PlatformRelease,
/// `platform_version`
PlatformVersion,
/// `implementation_name`
ImplementationName,
}
impl CanonicalMarkerValueString {
/// Returns `true` if the marker is known to be involved in _at least_ one conflicting
/// marker pair.
///
/// For example, `sys_platform == 'win32'` and `platform_system == 'Darwin'` are known to
/// never be true at the same time.
pub(crate) fn is_conflicting(self) -> bool {
self <= Self::PlatformSystem
}
}
impl From<MarkerValueString> for CanonicalMarkerValueString {
fn from(value: MarkerValueString) -> Self {
match value {
MarkerValueString::ImplementationName => Self::ImplementationName,
MarkerValueString::OsName => Self::OsName,
MarkerValueString::OsNameDeprecated => Self::OsName,
MarkerValueString::PlatformMachine => Self::PlatformMachine,
MarkerValueString::PlatformMachineDeprecated => Self::PlatformMachine,
MarkerValueString::PlatformPythonImplementation => Self::PlatformPythonImplementation,
MarkerValueString::PlatformPythonImplementationDeprecated => {
Self::PlatformPythonImplementation
}
MarkerValueString::PythonImplementationDeprecated => Self::PlatformPythonImplementation,
MarkerValueString::PlatformRelease => Self::PlatformRelease,
MarkerValueString::PlatformSystem => Self::PlatformSystem,
MarkerValueString::PlatformVersion => Self::PlatformVersion,
MarkerValueString::PlatformVersionDeprecated => Self::PlatformVersion,
MarkerValueString::SysPlatform => Self::SysPlatform,
MarkerValueString::SysPlatformDeprecated => Self::SysPlatform,
}
}
}
impl From<CanonicalMarkerValueString> for MarkerValueString {
fn from(value: CanonicalMarkerValueString) -> Self {
match value {
CanonicalMarkerValueString::ImplementationName => Self::ImplementationName,
CanonicalMarkerValueString::OsName => Self::OsName,
CanonicalMarkerValueString::PlatformMachine => Self::PlatformMachine,
CanonicalMarkerValueString::PlatformPythonImplementation => {
Self::PlatformPythonImplementation
}
CanonicalMarkerValueString::PlatformRelease => Self::PlatformRelease,
CanonicalMarkerValueString::PlatformSystem => Self::PlatformSystem,
CanonicalMarkerValueString::PlatformVersion => Self::PlatformVersion,
CanonicalMarkerValueString::SysPlatform => Self::SysPlatform,
}
}
}
impl Display for CanonicalMarkerValueString {
/// Normalizes deprecated names to the proper ones
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::ImplementationName => f.write_str("implementation_name"),
Self::OsName => f.write_str("os_name"),
Self::PlatformMachine => f.write_str("platform_machine"),
Self::PlatformPythonImplementation => f.write_str("platform_python_implementation"),
Self::PlatformRelease => f.write_str("platform_release"),
Self::PlatformSystem => f.write_str("platform_system"),
Self::PlatformVersion => f.write_str("platform_version"),
Self::SysPlatform => f.write_str("sys_platform"),
}
}
}
/// The [`ExtraName`] value used in `extra` and `extras` markers.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum CanonicalMarkerValueExtra {
/// A valid [`ExtraName`].
Extra(ExtraName),
}
impl CanonicalMarkerValueExtra {
/// Returns the [`ExtraName`] value.
pub fn extra(&self) -> &ExtraName {
match self {
Self::Extra(extra) => extra,
}
}
}
impl From<CanonicalMarkerValueExtra> for MarkerValueExtra {
fn from(value: CanonicalMarkerValueExtra) -> Self {
match value {
CanonicalMarkerValueExtra::Extra(extra) => Self::Extra(extra),
}
}
}
impl Display for CanonicalMarkerValueExtra {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Extra(extra) => extra.fmt(f),
}
}
}
/// A key-value pair for `<value> in <key>` or `<value> not in <key>`, where the key is a list.
///
/// Used for PEP 751 markers.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum CanonicalMarkerListPair {
/// A valid [`ExtraName`].
Extras(ExtraName),
/// A valid [`GroupName`].
DependencyGroup(GroupName),
/// For leniency, preserve invalid values.
Arbitrary { key: MarkerValueList, value: String },
}
impl CanonicalMarkerListPair {
/// The key (RHS) of the marker expression.
pub(crate) fn key(&self) -> MarkerValueList {
match self {
Self::Extras(_) => MarkerValueList::Extras,
Self::DependencyGroup(_) => MarkerValueList::DependencyGroups,
Self::Arbitrary { key, .. } => *key,
}
}
/// The value (LHS) of the marker expression.
pub(crate) fn value(&self) -> String {
match self {
Self::Extras(extra) => extra.to_string(),
Self::DependencyGroup(group) => group.to_string(),
Self::Arbitrary { value, .. } => 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-platform-tags/src/abi_tag.rs | crates/uv-platform-tags/src/abi_tag.rs | use std::fmt::Formatter;
use std::str::FromStr;
/// A tag to represent the ABI compatibility of a Python distribution.
///
/// This is the second segment in the wheel filename, following the language tag. For example,
/// in `cp39-none-manylinux_2_24_x86_64.whl`, the ABI tag is `none`.
#[derive(
Debug,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum AbiTag {
/// Ex) `none`
None,
/// Ex) `abi3`
Abi3,
/// Ex) `cp39m`, `cp310t`
CPython {
gil_disabled: bool,
python_version: (u8, u8),
},
/// Ex) `pypy39_pp73`
PyPy {
python_version: Option<(u8, u8)>,
implementation_version: (u8, u8),
},
/// Ex) `graalpy240_310_native`
GraalPy {
python_version: (u8, u8),
implementation_version: (u8, u8),
},
/// Ex) `pyston_23_x86_64_linux_gnu`
Pyston { implementation_version: (u8, u8) },
}
impl AbiTag {
/// Return a pretty string representation of the ABI tag.
pub fn pretty(self) -> Option<String> {
match self {
Self::None => None,
Self::Abi3 => None,
Self::CPython { python_version, .. } => {
Some(format!("CPython {}.{}", python_version.0, python_version.1))
}
Self::PyPy {
implementation_version,
..
} => Some(format!(
"PyPy {}.{}",
implementation_version.0, implementation_version.1
)),
Self::GraalPy {
implementation_version,
..
} => Some(format!(
"GraalPy {}.{}",
implementation_version.0, implementation_version.1
)),
Self::Pyston { .. } => Some("Pyston".to_string()),
}
}
}
impl std::fmt::Display for AbiTag {
/// Format an [`AbiTag`] as a string.
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::None => write!(f, "none"),
Self::Abi3 => write!(f, "abi3"),
Self::CPython {
gil_disabled,
python_version: (major, minor),
} => {
if *minor <= 7 {
write!(f, "cp{major}{minor}m")
} else if *gil_disabled {
// https://peps.python.org/pep-0703/#build-configuration-changes
// Python 3.13+ only, but it makes more sense to just rely on the sysconfig var.
write!(f, "cp{major}{minor}t")
} else {
write!(f, "cp{major}{minor}")
}
}
Self::PyPy {
python_version: Some((py_major, py_minor)),
implementation_version: (impl_major, impl_minor),
} => {
write!(f, "pypy{py_major}{py_minor}_pp{impl_major}{impl_minor}")
}
Self::PyPy {
python_version: None,
implementation_version: (impl_major, impl_minor),
} => {
write!(f, "pypy_{impl_major}{impl_minor}")
}
Self::GraalPy {
python_version: (py_major, py_minor),
implementation_version: (impl_major, impl_minor),
} => {
write!(
f,
"graalpy{impl_major}{impl_minor}_{py_major}{py_minor}_native"
)
}
Self::Pyston {
implementation_version: (impl_major, impl_minor),
} => {
write!(f, "pyston_{impl_major}{impl_minor}_x86_64_linux_gnu")
}
}
}
}
impl FromStr for AbiTag {
type Err = ParseAbiTagError;
/// Parse an [`AbiTag`] from a string.
#[allow(clippy::cast_possible_truncation)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
/// Parse a Python version from a string (e.g., convert `39` into `(3, 9)`).
fn parse_python_version(
version_str: &str,
implementation: &'static str,
full_tag: &str,
) -> Result<(u8, u8), ParseAbiTagError> {
let major = version_str
.as_bytes()
.first()
.ok_or_else(|| ParseAbiTagError::MissingMajorVersion {
implementation,
tag: full_tag.to_string(),
})?
.checked_sub(b'0')
.and_then(|d| if d < 10 { Some(d) } else { None })
.ok_or_else(|| ParseAbiTagError::InvalidMajorVersion {
implementation,
tag: full_tag.to_string(),
})?;
let minor = version_str
.get(1..)
.ok_or_else(|| ParseAbiTagError::MissingMinorVersion {
implementation,
tag: full_tag.to_string(),
})?
.parse::<u8>()
.map_err(|_| ParseAbiTagError::InvalidMinorVersion {
implementation,
tag: full_tag.to_string(),
})?;
Ok((major, minor))
}
/// Parse an implementation version from a string (e.g., convert `37` into `(3, 7)`).
fn parse_impl_version(
version_str: &str,
implementation: &'static str,
full_tag: &str,
) -> Result<(u8, u8), ParseAbiTagError> {
let major = version_str
.as_bytes()
.first()
.ok_or_else(|| ParseAbiTagError::MissingImplMajorVersion {
implementation,
tag: full_tag.to_string(),
})?
.checked_sub(b'0')
.and_then(|d| if d < 10 { Some(d) } else { None })
.ok_or_else(|| ParseAbiTagError::InvalidImplMajorVersion {
implementation,
tag: full_tag.to_string(),
})?;
let minor = version_str
.get(1..)
.ok_or_else(|| ParseAbiTagError::MissingImplMinorVersion {
implementation,
tag: full_tag.to_string(),
})?
.parse::<u8>()
.map_err(|_| ParseAbiTagError::InvalidImplMinorVersion {
implementation,
tag: full_tag.to_string(),
})?;
Ok((major, minor))
}
if s == "none" {
Ok(Self::None)
} else if s == "abi3" {
Ok(Self::Abi3)
} else if let Some(cp) = s.strip_prefix("cp") {
// Ex) `cp39m`, `cp310t`
let version_end = cp.find(|c: char| !c.is_ascii_digit()).unwrap_or(cp.len());
let version_str = &cp[..version_end];
let (major, minor) = parse_python_version(version_str, "CPython", s)?;
let gil_disabled = cp.ends_with('t');
Ok(Self::CPython {
gil_disabled,
python_version: (major, minor),
})
} else if let Some(rest) = s.strip_prefix("pypy") {
if let Some(rest) = rest.strip_prefix('_') {
// Ex) `pypy_73`
let (impl_major, impl_minor) = parse_impl_version(rest, "PyPy", s)?;
Ok(Self::PyPy {
python_version: None,
implementation_version: (impl_major, impl_minor),
})
} else {
// Ex) `pypy39_pp73`
let (version_str, rest) =
rest.split_once('_')
.ok_or_else(|| ParseAbiTagError::InvalidFormat {
implementation: "PyPy",
tag: s.to_string(),
})?;
let (major, minor) = parse_python_version(version_str, "PyPy", s)?;
let rest =
rest.strip_prefix("pp")
.ok_or_else(|| ParseAbiTagError::InvalidFormat {
implementation: "PyPy",
tag: s.to_string(),
})?;
let (impl_major, impl_minor) = parse_impl_version(rest, "PyPy", s)?;
Ok(Self::PyPy {
python_version: Some((major, minor)),
implementation_version: (impl_major, impl_minor),
})
}
} else if let Some(rest) = s.strip_prefix("graalpy") {
// Ex) `graalpy240_310_native`
let (impl_ver_str, rest) =
rest.split_once('_')
.ok_or_else(|| ParseAbiTagError::InvalidFormat {
implementation: "GraalPy",
tag: s.to_string(),
})?;
let (impl_major, impl_minor) = parse_impl_version(impl_ver_str, "GraalPy", s)?;
let (py_ver_str, _) =
rest.split_once('_')
.ok_or_else(|| ParseAbiTagError::InvalidFormat {
implementation: "GraalPy",
tag: s.to_string(),
})?;
let (major, minor) = parse_python_version(py_ver_str, "GraalPy", s)?;
Ok(Self::GraalPy {
python_version: (major, minor),
implementation_version: (impl_major, impl_minor),
})
} else if let Some(rest) = s.strip_prefix("pyston") {
// Ex) `pyston_23_x86_64_linux_gnu`
let rest = rest
.strip_prefix("_")
.ok_or_else(|| ParseAbiTagError::InvalidFormat {
implementation: "Pyston",
tag: s.to_string(),
})?;
let rest = rest.strip_suffix("_x86_64_linux_gnu").ok_or_else(|| {
ParseAbiTagError::InvalidFormat {
implementation: "Pyston",
tag: s.to_string(),
}
})?;
let (impl_major, impl_minor) = parse_impl_version(rest, "Pyston", s)?;
Ok(Self::Pyston {
implementation_version: (impl_major, impl_minor),
})
} else {
Err(ParseAbiTagError::UnknownFormat(s.to_string()))
}
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParseAbiTagError {
#[error("Unknown ABI tag format: {0}")]
UnknownFormat(String),
#[error("Missing major version in {implementation} ABI tag: {tag}")]
MissingMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid major version in {implementation} ABI tag: {tag}")]
InvalidMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Missing minor version in {implementation} ABI tag: {tag}")]
MissingMinorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid minor version in {implementation} ABI tag: {tag}")]
InvalidMinorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid {implementation} ABI tag format: {tag}")]
InvalidFormat {
implementation: &'static str,
tag: String,
},
#[error("Missing implementation major version in {implementation} ABI tag: {tag}")]
MissingImplMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid implementation major version in {implementation} ABI tag: {tag}")]
InvalidImplMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Missing implementation minor version in {implementation} ABI tag: {tag}")]
MissingImplMinorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid implementation minor version in {implementation} ABI tag: {tag}")]
InvalidImplMinorVersion {
implementation: &'static str,
tag: String,
},
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use crate::abi_tag::{AbiTag, ParseAbiTagError};
#[test]
fn none_abi() {
assert_eq!(AbiTag::from_str("none"), Ok(AbiTag::None));
assert_eq!(AbiTag::None.to_string(), "none");
}
#[test]
fn abi3() {
assert_eq!(AbiTag::from_str("abi3"), Ok(AbiTag::Abi3));
assert_eq!(AbiTag::Abi3.to_string(), "abi3");
}
#[test]
fn cpython_abi() {
let tag = AbiTag::CPython {
gil_disabled: false,
python_version: (3, 9),
};
assert_eq!(AbiTag::from_str("cp39"), Ok(tag));
assert_eq!(tag.to_string(), "cp39");
let tag = AbiTag::CPython {
gil_disabled: false,
python_version: (3, 7),
};
assert_eq!(AbiTag::from_str("cp37m"), Ok(tag));
assert_eq!(tag.to_string(), "cp37m");
let tag = AbiTag::CPython {
gil_disabled: true,
python_version: (3, 13),
};
assert_eq!(AbiTag::from_str("cp313t"), Ok(tag));
assert_eq!(tag.to_string(), "cp313t");
assert_eq!(
AbiTag::from_str("cpXY"),
Err(ParseAbiTagError::MissingMajorVersion {
implementation: "CPython",
tag: "cpXY".to_string()
})
);
}
#[test]
fn pypy_abi() {
let tag = AbiTag::PyPy {
python_version: Some((3, 9)),
implementation_version: (7, 3),
};
assert_eq!(AbiTag::from_str("pypy39_pp73"), Ok(tag));
assert_eq!(tag.to_string(), "pypy39_pp73");
let tag = AbiTag::PyPy {
python_version: None,
implementation_version: (7, 3),
};
assert_eq!(AbiTag::from_str("pypy_73").as_ref(), Ok(&tag));
assert_eq!(tag.to_string(), "pypy_73");
assert_eq!(
AbiTag::from_str("pypy39"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "PyPy",
tag: "pypy39".to_string()
})
);
assert_eq!(
AbiTag::from_str("pypy39_73"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "PyPy",
tag: "pypy39_73".to_string()
})
);
assert_eq!(
AbiTag::from_str("pypy39_ppXY"),
Err(ParseAbiTagError::InvalidImplMajorVersion {
implementation: "PyPy",
tag: "pypy39_ppXY".to_string()
})
);
}
#[test]
fn graalpy_abi() {
let tag = AbiTag::GraalPy {
python_version: (3, 10),
implementation_version: (2, 40),
};
assert_eq!(AbiTag::from_str("graalpy240_310_native"), Ok(tag));
assert_eq!(tag.to_string(), "graalpy240_310_native");
assert_eq!(
AbiTag::from_str("graalpy310"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "GraalPy",
tag: "graalpy310".to_string()
})
);
assert_eq!(
AbiTag::from_str("graalpy310_240"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "GraalPy",
tag: "graalpy310_240".to_string()
})
);
assert_eq!(
AbiTag::from_str("graalpy310_graalpyXY"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "GraalPy",
tag: "graalpy310_graalpyXY".to_string()
})
);
}
#[test]
fn pyston_abi() {
let tag = AbiTag::Pyston {
implementation_version: (2, 3),
};
assert_eq!(AbiTag::from_str("pyston_23_x86_64_linux_gnu"), Ok(tag));
assert_eq!(tag.to_string(), "pyston_23_x86_64_linux_gnu");
assert_eq!(
AbiTag::from_str("pyston23_x86_64_linux_gnu"),
Err(ParseAbiTagError::InvalidFormat {
implementation: "Pyston",
tag: "pyston23_x86_64_linux_gnu".to_string()
})
);
assert_eq!(
AbiTag::from_str("pyston_XY_x86_64_linux_gnu"),
Err(ParseAbiTagError::InvalidImplMajorVersion {
implementation: "Pyston",
tag: "pyston_XY_x86_64_linux_gnu".to_string()
})
);
}
#[test]
fn unknown_abi() {
assert_eq!(
AbiTag::from_str("unknown"),
Err(ParseAbiTagError::UnknownFormat("unknown".to_string()))
);
assert_eq!(
AbiTag::from_str(""),
Err(ParseAbiTagError::UnknownFormat(String::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-platform-tags/src/lib.rs | crates/uv-platform-tags/src/lib.rs | pub use abi_tag::{AbiTag, ParseAbiTagError};
pub use language_tag::{LanguageTag, ParseLanguageTagError};
pub use platform::{Arch, Os, Platform, PlatformError};
pub use platform_tag::{ParsePlatformTagError, PlatformTag};
pub use tags::{BinaryFormat, IncompatibleTag, TagCompatibility, TagPriority, Tags, TagsError};
mod abi_tag;
mod language_tag;
mod platform;
mod platform_tag;
mod tags;
| 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-platform-tags/src/platform.rs | crates/uv-platform-tags/src/platform.rs | //! Abstractions for understanding the current platform (operating system and architecture).
use std::str::FromStr;
use std::{fmt, io};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum PlatformError {
#[error(transparent)]
IOError(#[from] io::Error),
#[error("Failed to detect the operating system version: {0}")]
OsVersionDetectionError(String),
#[error("Failed to detect the arch: {0}")]
ArchDetectionError(String),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Platform {
os: Os,
arch: Arch,
}
impl Platform {
/// Create a new platform from the given operating system and architecture.
pub const fn new(os: Os, arch: Arch) -> Self {
Self { os, arch }
}
/// Return the platform's operating system.
pub fn os(&self) -> &Os {
&self.os
}
/// Return the platform's architecture.
pub fn arch(&self) -> Arch {
self.arch
}
}
/// All supported operating systems.
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(tag = "name", rename_all = "lowercase")]
pub enum Os {
Manylinux {
major: u16,
minor: u16,
},
Musllinux {
major: u16,
minor: u16,
},
Windows,
Pyodide {
major: u16,
minor: u16,
},
Macos {
major: u16,
minor: u16,
},
FreeBsd {
release: String,
},
NetBsd {
release: String,
},
OpenBsd {
release: String,
},
Dragonfly {
release: String,
},
Illumos {
release: String,
arch: String,
},
Haiku {
release: String,
},
Android {
api_level: u16,
},
Ios {
major: u16,
minor: u16,
simulator: bool,
},
}
impl fmt::Display for Os {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Manylinux { .. } => write!(f, "manylinux"),
Self::Musllinux { .. } => write!(f, "musllinux"),
Self::Windows => write!(f, "windows"),
Self::Macos { .. } => write!(f, "macos"),
Self::FreeBsd { .. } => write!(f, "freebsd"),
Self::NetBsd { .. } => write!(f, "netbsd"),
Self::OpenBsd { .. } => write!(f, "openbsd"),
Self::Dragonfly { .. } => write!(f, "dragonfly"),
Self::Illumos { .. } => write!(f, "illumos"),
Self::Haiku { .. } => write!(f, "haiku"),
Self::Android { .. } => write!(f, "android"),
Self::Pyodide { .. } => write!(f, "pyodide"),
Self::Ios { .. } => write!(f, "ios"),
}
}
}
/// All supported CPU architectures
#[derive(
Debug,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
serde::Deserialize,
serde::Serialize,
)]
#[rkyv(derive(Debug))]
#[serde(rename_all = "lowercase")]
pub enum Arch {
#[serde(alias = "arm64")]
Aarch64,
Armv5TEL,
Armv6L,
#[serde(alias = "armv8l")]
Armv7L,
#[serde(alias = "ppc64le")]
Powerpc64Le,
#[serde(alias = "ppc64")]
Powerpc64,
#[serde(alias = "ppc")]
Powerpc,
#[serde(alias = "i386", alias = "i686")]
X86,
#[serde(alias = "amd64")]
X86_64,
S390X,
LoongArch64,
Riscv64,
Wasm32,
}
impl fmt::Display for Arch {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl FromStr for Arch {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"aarch64" => Ok(Self::Aarch64),
"armv5tel" => Ok(Self::Armv5TEL),
"armv6l" => Ok(Self::Armv6L),
"armv7l" => Ok(Self::Armv7L),
"ppc64le" => Ok(Self::Powerpc64Le),
"ppc64" => Ok(Self::Powerpc64),
"ppc" => Ok(Self::Powerpc),
"i686" => Ok(Self::X86),
"x86_64" => Ok(Self::X86_64),
"s390x" => Ok(Self::S390X),
"loongarch64" => Ok(Self::LoongArch64),
"riscv64" => Ok(Self::Riscv64),
_ => Err(format!("Unknown architecture: {s}")),
}
}
}
impl Arch {
/// Returns the oldest possible `manylinux` tag for this architecture, if it supports
/// `manylinux`.
pub fn get_minimum_manylinux_minor(&self) -> Option<u16> {
match self {
// manylinux 2014
Self::Aarch64 | Self::Armv7L | Self::Powerpc64 | Self::Powerpc64Le | Self::S390X => {
Some(17)
}
// manylinux 1
Self::X86 | Self::X86_64 => Some(5),
// manylinux_2_31
Self::Riscv64 => Some(31),
// manylinux_2_36
Self::LoongArch64 => Some(36),
// unsupported
Self::Powerpc | Self::Armv5TEL | Self::Armv6L | Self::Wasm32 => None,
}
}
/// Returns the standard name of the architecture.
pub fn name(&self) -> &'static str {
match self {
Self::Aarch64 => "aarch64",
Self::Armv5TEL => "armv5tel",
Self::Armv6L => "armv6l",
Self::Armv7L => "armv7l",
Self::Powerpc64Le => "ppc64le",
Self::Powerpc64 => "ppc64",
Self::Powerpc => "ppc",
Self::X86 => "i686",
Self::X86_64 => "x86_64",
Self::S390X => "s390x",
Self::LoongArch64 => "loongarch64",
Self::Riscv64 => "riscv64",
Self::Wasm32 => "wasm32",
}
}
/// Represents the hardware platform.
///
/// This is the same as the native platform's `uname -m` output.
///
/// Based on: <https://github.com/PyO3/maturin/blob/8ab42219247277fee513eac753a3e90e76cd46b9/src/target/mod.rs#L131>
pub fn machine(&self) -> &'static str {
match self {
Self::Aarch64 => "arm64",
Self::Armv5TEL | Self::Armv6L | Self::Armv7L => "arm",
Self::Powerpc | Self::Powerpc64Le | Self::Powerpc64 => "powerpc",
Self::X86 => "i386",
Self::X86_64 => "amd64",
Self::Riscv64 => "riscv",
Self::Wasm32 => "wasm32",
Self::S390X => "s390x",
Self::LoongArch64 => "loongarch64",
}
}
}
| 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-platform-tags/src/platform_tag.rs | crates/uv-platform-tags/src/platform_tag.rs | use std::fmt::Formatter;
use std::str::FromStr;
use uv_small_str::SmallString;
use crate::tags::AndroidAbi;
use crate::tags::IosMultiarch;
use crate::{Arch, BinaryFormat};
/// A tag to represent the platform compatibility of a Python distribution.
///
/// This is the third segment in the wheel filename, following the language and ABI tags. For
/// example, in `cp39-none-manylinux_2_24_x86_64.whl`, the platform tag is `manylinux_2_24_x86_64`.
///
/// For simplicity (and to reduce struct size), the non-Linux, macOS, and Windows variants (like
/// FreeBSD) store an opaque suffix, which combines the release (like `3.14`) and architecture (like
/// `x86_64`) into a single string (like `3_14_x86_64`).
#[derive(
Debug,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum PlatformTag {
/// Ex) `any`
Any,
/// Ex) `manylinux_2_24_x86_64`
Manylinux { major: u16, minor: u16, arch: Arch },
/// Ex) `manylinux1_x86_64`
Manylinux1 { arch: Arch },
/// Ex) `manylinux2010_x86_64`
Manylinux2010 { arch: Arch },
/// Ex) `manylinux2014_x86_64`
Manylinux2014 { arch: Arch },
/// Ex) `linux_x86_64`
Linux { arch: Arch },
/// Ex) `musllinux_1_2_x86_64`
Musllinux { major: u16, minor: u16, arch: Arch },
/// Ex) `macosx_11_0_x86_64`
Macos {
major: u16,
minor: u16,
binary_format: BinaryFormat,
},
/// Ex) `win32`
Win32,
/// Ex) `win_amd64`
WinAmd64,
/// Ex) `win_arm64`
WinArm64,
/// Ex) `win_ia64`
WinIa64,
/// Ex) `android_21_x86_64`
Android { api_level: u16, abi: AndroidAbi },
/// Ex) `freebsd_12_x86_64`
FreeBsd { release_arch: SmallString },
/// Ex) `netbsd_9_x86_64`
NetBsd { release_arch: SmallString },
/// Ex) `openbsd_6_x86_64`
OpenBsd { release_arch: SmallString },
/// Ex) `dragonfly_6_x86_64`
Dragonfly { release_arch: SmallString },
/// Ex) `haiku_1_x86_64`
Haiku { release_arch: SmallString },
/// Ex) `illumos_5_11_x86_64`
Illumos { release_arch: SmallString },
/// Ex) `solaris_11_4_x86_64`
Solaris { release_arch: SmallString },
/// Ex) `pyodide_2024_0_wasm32`
Pyodide { major: u16, minor: u16 },
/// Ex) `ios_13_0_arm64_iphoneos` / `ios_13_0_arm64_iphonesimulator`
Ios {
major: u16,
minor: u16,
multiarch: IosMultiarch,
},
}
impl PlatformTag {
/// Return a pretty string representation of the language tag.
pub fn pretty(&self) -> Option<&'static str> {
match self {
Self::Any => None,
Self::Manylinux { .. } => Some("Linux"),
Self::Manylinux1 { .. } => Some("Linux"),
Self::Manylinux2010 { .. } => Some("Linux"),
Self::Manylinux2014 { .. } => Some("Linux"),
Self::Linux { .. } => Some("Linux"),
Self::Musllinux { .. } => Some("Linux"),
Self::Macos { .. } => Some("macOS"),
Self::Win32 => Some("Windows"),
Self::WinAmd64 => Some("Windows"),
Self::WinArm64 => Some("Windows"),
Self::WinIa64 => Some("Windows"),
Self::Android { .. } => Some("Android"),
Self::FreeBsd { .. } => Some("FreeBSD"),
Self::NetBsd { .. } => Some("NetBSD"),
Self::OpenBsd { .. } => Some("OpenBSD"),
Self::Dragonfly { .. } => Some("DragonFly"),
Self::Haiku { .. } => Some("Haiku"),
Self::Illumos { .. } => Some("Illumos"),
Self::Solaris { .. } => Some("Solaris"),
Self::Pyodide { .. } => Some("Pyodide"),
Self::Ios { .. } => Some("iOS"),
}
}
}
impl PlatformTag {
/// Returns `true` if the platform is "any" (i.e., not specific to a platform).
pub fn is_any(&self) -> bool {
matches!(self, Self::Any)
}
/// Returns `true` if the platform is manylinux-only.
pub fn is_manylinux(&self) -> bool {
matches!(
self,
Self::Manylinux { .. }
| Self::Manylinux1 { .. }
| Self::Manylinux2010 { .. }
| Self::Manylinux2014 { .. }
)
}
/// Returns `true` if the platform is Linux-only.
pub fn is_linux(&self) -> bool {
matches!(
self,
Self::Manylinux { .. }
| Self::Manylinux1 { .. }
| Self::Manylinux2010 { .. }
| Self::Manylinux2014 { .. }
| Self::Musllinux { .. }
| Self::Linux { .. }
)
}
/// Returns `true` if the platform is macOS-only.
pub fn is_macos(&self) -> bool {
matches!(self, Self::Macos { .. })
}
/// Returns `true` if the platform is Android-only.
pub fn is_android(&self) -> bool {
matches!(self, Self::Android { .. })
}
/// Returns `true` if the platform is Windows-only.
pub fn is_windows(&self) -> bool {
matches!(
self,
Self::Win32 | Self::WinAmd64 | Self::WinArm64 | Self::WinIa64
)
}
/// Returns `true` if the tag is only applicable on ARM platforms.
pub fn is_arm(&self) -> bool {
matches!(
self,
Self::Manylinux {
arch: Arch::Aarch64,
..
} | Self::Manylinux1 {
arch: Arch::Aarch64,
..
} | Self::Manylinux2010 {
arch: Arch::Aarch64,
..
} | Self::Manylinux2014 {
arch: Arch::Aarch64,
..
} | Self::Linux {
arch: Arch::Aarch64,
..
} | Self::Musllinux {
arch: Arch::Aarch64,
..
} | Self::Macos {
binary_format: BinaryFormat::Arm64,
..
} | Self::Ios {
multiarch: IosMultiarch::Arm64Device | IosMultiarch::Arm64Simulator,
..
} | Self::WinArm64
| Self::Android {
abi: AndroidAbi::Arm64V8a,
..
}
)
}
/// Returns `true` if the tag is only applicable on `x86_64` platforms.
pub fn is_x86_64(&self) -> bool {
matches!(
self,
Self::Manylinux {
arch: Arch::X86_64,
..
} | Self::Manylinux1 {
arch: Arch::X86_64,
..
} | Self::Manylinux2010 {
arch: Arch::X86_64,
..
} | Self::Manylinux2014 {
arch: Arch::X86_64,
..
} | Self::Linux {
arch: Arch::X86_64,
..
} | Self::Musllinux {
arch: Arch::X86_64,
..
} | Self::Macos {
binary_format: BinaryFormat::X86_64,
..
} | Self::Ios {
multiarch: IosMultiarch::X86_64Simulator,
..
} | Self::WinAmd64
)
}
/// Returns `true` if the tag is only applicable on x86 platforms.
pub fn is_x86(&self) -> bool {
matches!(
self,
Self::Manylinux {
arch: Arch::X86,
..
} | Self::Manylinux1 {
arch: Arch::X86,
..
} | Self::Manylinux2010 {
arch: Arch::X86,
..
} | Self::Manylinux2014 {
arch: Arch::X86,
..
} | Self::Linux {
arch: Arch::X86,
..
} | Self::Musllinux {
arch: Arch::X86,
..
} | Self::Macos {
binary_format: BinaryFormat::I386,
..
} | Self::Win32
)
}
}
impl std::fmt::Display for PlatformTag {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Any => write!(f, "any"),
Self::Manylinux { major, minor, arch } => {
write!(f, "manylinux_{major}_{minor}_{arch}")
}
Self::Manylinux1 { arch } => write!(f, "manylinux1_{arch}"),
Self::Manylinux2010 { arch } => write!(f, "manylinux2010_{arch}"),
Self::Manylinux2014 { arch } => write!(f, "manylinux2014_{arch}"),
Self::Linux { arch } => write!(f, "linux_{arch}"),
Self::Musllinux { major, minor, arch } => {
write!(f, "musllinux_{major}_{minor}_{arch}")
}
Self::Macos {
major,
minor,
binary_format: format,
} => write!(f, "macosx_{major}_{minor}_{format}"),
Self::Win32 => write!(f, "win32"),
Self::WinAmd64 => write!(f, "win_amd64"),
Self::WinArm64 => write!(f, "win_arm64"),
Self::WinIa64 => write!(f, "win_ia64"),
Self::Android { api_level, abi } => write!(f, "android_{api_level}_{abi}"),
Self::FreeBsd { release_arch } => write!(f, "freebsd_{release_arch}"),
Self::NetBsd { release_arch } => write!(f, "netbsd_{release_arch}"),
Self::OpenBsd { release_arch } => write!(f, "openbsd_{release_arch}"),
Self::Dragonfly { release_arch } => write!(f, "dragonfly_{release_arch}"),
Self::Haiku { release_arch } => write!(f, "haiku_{release_arch}"),
Self::Illumos { release_arch } => write!(f, "illumos_{release_arch}"),
Self::Solaris { release_arch } => write!(f, "solaris_{release_arch}_64bit"),
Self::Pyodide { major, minor } => write!(f, "pyodide_{major}_{minor}_wasm32"),
Self::Ios {
major,
minor,
multiarch,
} => write!(f, "ios_{major}_{minor}_{multiarch}"),
}
}
}
impl FromStr for PlatformTag {
type Err = ParsePlatformTagError;
/// Parse a [`PlatformTag`] from a string.
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Match against any static variants.
match s {
"any" => return Ok(Self::Any),
"win32" => return Ok(Self::Win32),
"win_amd64" => return Ok(Self::WinAmd64),
"win_arm64" => return Ok(Self::WinArm64),
"win_ia64" => return Ok(Self::WinIa64),
_ => {}
}
if let Some(rest) = s.strip_prefix("manylinux_") {
// Ex) manylinux_2_17_x86_64
let first_underscore = memchr::memchr(b'_', rest.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "manylinux",
tag: s.to_string(),
}
})?;
let second_underscore = memchr::memchr(b'_', &rest.as_bytes()[first_underscore + 1..])
.map(|i| i + first_underscore + 1)
.ok_or_else(|| ParsePlatformTagError::InvalidFormat {
platform: "manylinux",
tag: s.to_string(),
})?;
let major = rest[..first_underscore].parse().map_err(|_| {
ParsePlatformTagError::InvalidMajorVersion {
platform: "manylinux",
tag: s.to_string(),
}
})?;
let minor = rest[first_underscore + 1..second_underscore]
.parse()
.map_err(|_| ParsePlatformTagError::InvalidMinorVersion {
platform: "manylinux",
tag: s.to_string(),
})?;
let arch_str = &rest[second_underscore + 1..];
if arch_str.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "manylinux",
tag: s.to_string(),
});
}
let arch = arch_str
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "manylinux",
tag: s.to_string(),
})?;
return Ok(Self::Manylinux { major, minor, arch });
}
if let Some(rest) = s.strip_prefix("manylinux1_") {
// Ex) manylinux1_x86_64
let arch = rest
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "manylinux1",
tag: s.to_string(),
})?;
return Ok(Self::Manylinux1 { arch });
}
if let Some(rest) = s.strip_prefix("manylinux2010_") {
// Ex) manylinux2010_x86_64
let arch = rest
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "manylinux2010",
tag: s.to_string(),
})?;
return Ok(Self::Manylinux2010 { arch });
}
if let Some(rest) = s.strip_prefix("manylinux2014_") {
// Ex) manylinux2014_x86_64
let arch = rest
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "manylinux2014",
tag: s.to_string(),
})?;
return Ok(Self::Manylinux2014 { arch });
}
if let Some(rest) = s.strip_prefix("linux_") {
// Ex) linux_x86_64
let arch = rest
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "linux",
tag: s.to_string(),
})?;
return Ok(Self::Linux { arch });
}
if let Some(rest) = s.strip_prefix("musllinux_") {
// Ex) musllinux_1_1_x86_64
let first_underscore = memchr::memchr(b'_', rest.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "musllinux",
tag: s.to_string(),
}
})?;
let second_underscore = memchr::memchr(b'_', &rest.as_bytes()[first_underscore + 1..])
.map(|i| i + first_underscore + 1)
.ok_or_else(|| ParsePlatformTagError::InvalidFormat {
platform: "musllinux",
tag: s.to_string(),
})?;
let major = rest[..first_underscore].parse().map_err(|_| {
ParsePlatformTagError::InvalidMajorVersion {
platform: "musllinux",
tag: s.to_string(),
}
})?;
let minor = rest[first_underscore + 1..second_underscore]
.parse()
.map_err(|_| ParsePlatformTagError::InvalidMinorVersion {
platform: "musllinux",
tag: s.to_string(),
})?;
let arch_str = &rest[second_underscore + 1..];
if arch_str.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "musllinux",
tag: s.to_string(),
});
}
let arch = arch_str
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "musllinux",
tag: s.to_string(),
})?;
return Ok(Self::Musllinux { major, minor, arch });
}
if let Some(rest) = s.strip_prefix("macosx_") {
// Ex) macosx_11_0_arm64
let first_underscore = memchr::memchr(b'_', rest.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "macosx",
tag: s.to_string(),
}
})?;
let second_underscore = memchr::memchr(b'_', &rest.as_bytes()[first_underscore + 1..])
.map(|i| i + first_underscore + 1)
.ok_or_else(|| ParsePlatformTagError::InvalidFormat {
platform: "macosx",
tag: s.to_string(),
})?;
let major = rest[..first_underscore].parse().map_err(|_| {
ParsePlatformTagError::InvalidMajorVersion {
platform: "macosx",
tag: s.to_string(),
}
})?;
let minor = rest[first_underscore + 1..second_underscore]
.parse()
.map_err(|_| ParsePlatformTagError::InvalidMinorVersion {
platform: "macosx",
tag: s.to_string(),
})?;
let binary_format_str = &rest[second_underscore + 1..];
if binary_format_str.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "macosx",
tag: s.to_string(),
});
}
let binary_format =
binary_format_str
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "macosx",
tag: s.to_string(),
})?;
return Ok(Self::Macos {
major,
minor,
binary_format,
});
}
if let Some(rest) = s.strip_prefix("android_") {
// Ex) android_21_arm64_v8a
let underscore = memchr::memchr(b'_', rest.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "android",
tag: s.to_string(),
}
})?;
let api_level =
rest[..underscore]
.parse()
.map_err(|_| ParsePlatformTagError::InvalidApiLevel {
platform: "android",
tag: s.to_string(),
})?;
let abi_str = &rest[underscore + 1..];
if abi_str.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "android",
tag: s.to_string(),
});
}
let abi = abi_str
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "android",
tag: s.to_string(),
})?;
return Ok(Self::Android { api_level, abi });
}
if let Some(rest) = s.strip_prefix("freebsd_") {
// Ex) freebsd_13_x86_64 or freebsd_13_14_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "freebsd",
tag: s.to_string(),
});
}
return Ok(Self::FreeBsd {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("netbsd_") {
// Ex) netbsd_9_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "netbsd",
tag: s.to_string(),
});
}
return Ok(Self::NetBsd {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("openbsd_") {
// Ex) openbsd_7_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "openbsd",
tag: s.to_string(),
});
}
return Ok(Self::OpenBsd {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("dragonfly_") {
// Ex) dragonfly_6_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "dragonfly",
tag: s.to_string(),
});
}
return Ok(Self::Dragonfly {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("haiku_") {
// Ex) haiku_1_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "haiku",
tag: s.to_string(),
});
}
return Ok(Self::Haiku {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("illumos_") {
// Ex) illumos_5_11_x86_64
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "illumos",
tag: s.to_string(),
});
}
return Ok(Self::Illumos {
release_arch: SmallString::from(rest),
});
}
if let Some(rest) = s.strip_prefix("solaris_") {
// Ex) solaris_11_4_x86_64_64bit
if rest.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "solaris",
tag: s.to_string(),
});
}
if let Some(release_arch) = rest.strip_suffix("_64bit") {
if !release_arch.is_empty() {
return Ok(Self::Solaris {
release_arch: SmallString::from(release_arch),
});
}
}
return Err(ParsePlatformTagError::InvalidArch {
platform: "solaris",
tag: s.to_string(),
});
}
if let Some(rest) = s.strip_prefix("pyodide_") {
let mid =
rest.strip_suffix("_wasm32")
.ok_or_else(|| ParsePlatformTagError::InvalidArch {
platform: "pyodide",
tag: s.to_string(),
})?;
let underscore = memchr::memchr(b'_', mid.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "pyodide",
tag: s.to_string(),
}
})?;
let major: u16 = mid[..underscore].parse().map_err(|_| {
ParsePlatformTagError::InvalidMajorVersion {
platform: "pyodide",
tag: s.to_string(),
}
})?;
let minor: u16 = mid[underscore + 1..].parse().map_err(|_| {
ParsePlatformTagError::InvalidMinorVersion {
platform: "pyodide",
tag: s.to_string(),
}
})?;
return Ok(Self::Pyodide { major, minor });
}
if let Some(rest) = s.strip_prefix("ios_") {
// Ex) ios_13_0_arm64_iphoneos
let first_underscore = memchr::memchr(b'_', rest.as_bytes()).ok_or_else(|| {
ParsePlatformTagError::InvalidFormat {
platform: "ios",
tag: s.to_string(),
}
})?;
let second_underscore = memchr::memchr(b'_', &rest.as_bytes()[first_underscore + 1..])
.map(|i| i + first_underscore + 1)
.ok_or_else(|| ParsePlatformTagError::InvalidFormat {
platform: "ios",
tag: s.to_string(),
})?;
let major = rest[..first_underscore].parse().map_err(|_| {
ParsePlatformTagError::InvalidMajorVersion {
platform: "ios",
tag: s.to_string(),
}
})?;
let minor = rest[first_underscore + 1..second_underscore]
.parse()
.map_err(|_| ParsePlatformTagError::InvalidMinorVersion {
platform: "ios",
tag: s.to_string(),
})?;
let multiarch_str = &rest[second_underscore + 1..];
if multiarch_str.is_empty() {
return Err(ParsePlatformTagError::InvalidFormat {
platform: "ios",
tag: s.to_string(),
});
}
let multiarch =
multiarch_str
.parse()
.map_err(|_| ParsePlatformTagError::InvalidArch {
platform: "ios",
tag: s.to_string(),
})?;
return Ok(Self::Ios {
major,
minor,
multiarch,
});
}
Err(ParsePlatformTagError::UnknownFormat(s.to_string()))
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParsePlatformTagError {
#[error("Unknown platform tag format: {0}")]
UnknownFormat(String),
#[error("Invalid format for {platform} platform tag: {tag}")]
InvalidFormat { platform: &'static str, tag: String },
#[error("Invalid major version in {platform} platform tag: {tag}")]
InvalidMajorVersion { platform: &'static str, tag: String },
#[error("Invalid minor version in {platform} platform tag: {tag}")]
InvalidMinorVersion { platform: &'static str, tag: String },
#[error("Invalid architecture in {platform} platform tag: {tag}")]
InvalidArch { platform: &'static str, tag: String },
#[error("Invalid API level in {platform} platform tag: {tag}")]
InvalidApiLevel { platform: &'static str, tag: String },
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use crate::platform_tag::{ParsePlatformTagError, PlatformTag};
use crate::tags::AndroidAbi;
use crate::tags::IosMultiarch;
use crate::{Arch, BinaryFormat};
#[test]
fn any_platform() {
assert_eq!(PlatformTag::from_str("any"), Ok(PlatformTag::Any));
assert_eq!(PlatformTag::Any.to_string(), "any");
}
#[test]
fn manylinux_platform() {
let tag = PlatformTag::Manylinux {
major: 2,
minor: 24,
arch: Arch::X86_64,
};
assert_eq!(
PlatformTag::from_str("manylinux_2_24_x86_64").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "manylinux_2_24_x86_64");
assert_eq!(
PlatformTag::from_str("manylinux_x_24_x86_64"),
Err(ParsePlatformTagError::InvalidMajorVersion {
platform: "manylinux",
tag: "manylinux_x_24_x86_64".to_string()
})
);
assert_eq!(
PlatformTag::from_str("manylinux_2_x_x86_64"),
Err(ParsePlatformTagError::InvalidMinorVersion {
platform: "manylinux",
tag: "manylinux_2_x_x86_64".to_string()
})
);
assert_eq!(
PlatformTag::from_str("manylinux_2_24_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "manylinux",
tag: "manylinux_2_24_invalid".to_string()
})
);
}
#[test]
fn manylinux1_platform() {
let tag = PlatformTag::Manylinux1 { arch: Arch::X86_64 };
assert_eq!(
PlatformTag::from_str("manylinux1_x86_64").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "manylinux1_x86_64");
assert_eq!(
PlatformTag::from_str("manylinux1_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "manylinux1",
tag: "manylinux1_invalid".to_string()
})
);
}
#[test]
fn manylinux2010_platform() {
let tag = PlatformTag::Manylinux2010 { arch: Arch::X86_64 };
assert_eq!(
PlatformTag::from_str("manylinux2010_x86_64").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "manylinux2010_x86_64");
assert_eq!(
PlatformTag::from_str("manylinux2010_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "manylinux2010",
tag: "manylinux2010_invalid".to_string()
})
);
}
#[test]
fn manylinux2014_platform() {
let tag = PlatformTag::Manylinux2014 { arch: Arch::X86_64 };
assert_eq!(
PlatformTag::from_str("manylinux2014_x86_64").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "manylinux2014_x86_64");
assert_eq!(
PlatformTag::from_str("manylinux2014_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "manylinux2014",
tag: "manylinux2014_invalid".to_string()
})
);
}
#[test]
fn linux_platform() {
let tag = PlatformTag::Linux { arch: Arch::X86_64 };
assert_eq!(PlatformTag::from_str("linux_x86_64").as_ref(), Ok(&tag));
assert_eq!(tag.to_string(), "linux_x86_64");
assert_eq!(
PlatformTag::from_str("linux_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "linux",
tag: "linux_invalid".to_string()
})
);
}
#[test]
fn musllinux_platform() {
let tag = PlatformTag::Musllinux {
major: 1,
minor: 2,
arch: Arch::X86_64,
};
assert_eq!(
PlatformTag::from_str("musllinux_1_2_x86_64").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "musllinux_1_2_x86_64");
assert_eq!(
PlatformTag::from_str("musllinux_x_2_x86_64"),
Err(ParsePlatformTagError::InvalidMajorVersion {
platform: "musllinux",
tag: "musllinux_x_2_x86_64".to_string()
})
);
assert_eq!(
PlatformTag::from_str("musllinux_1_x_x86_64"),
Err(ParsePlatformTagError::InvalidMinorVersion {
platform: "musllinux",
tag: "musllinux_1_x_x86_64".to_string()
})
);
assert_eq!(
PlatformTag::from_str("musllinux_1_2_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "musllinux",
tag: "musllinux_1_2_invalid".to_string()
})
);
}
#[test]
fn macos_platform() {
let tag = PlatformTag::Macos {
major: 11,
minor: 0,
binary_format: BinaryFormat::Universal2,
};
assert_eq!(
PlatformTag::from_str("macosx_11_0_universal2").as_ref(),
Ok(&tag)
);
assert_eq!(tag.to_string(), "macosx_11_0_universal2");
assert_eq!(
PlatformTag::from_str("macosx_x_0_universal2"),
Err(ParsePlatformTagError::InvalidMajorVersion {
platform: "macosx",
tag: "macosx_x_0_universal2".to_string()
})
);
assert_eq!(
PlatformTag::from_str("macosx_11_x_universal2"),
Err(ParsePlatformTagError::InvalidMinorVersion {
platform: "macosx",
tag: "macosx_11_x_universal2".to_string()
})
);
assert_eq!(
PlatformTag::from_str("macosx_11_0_invalid"),
Err(ParsePlatformTagError::InvalidArch {
platform: "macosx",
tag: "macosx_11_0_invalid".to_string()
})
);
}
#[test]
fn win32_platform() {
assert_eq!(PlatformTag::from_str("win32"), Ok(PlatformTag::Win32));
assert_eq!(PlatformTag::Win32.to_string(), "win32");
}
#[test]
fn win_amd64_platform() {
assert_eq!(
PlatformTag::from_str("win_amd64"),
Ok(PlatformTag::WinAmd64)
);
assert_eq!(PlatformTag::WinAmd64.to_string(), "win_amd64");
}
#[test]
fn win_arm64_platform() {
assert_eq!(
PlatformTag::from_str("win_arm64"),
Ok(PlatformTag::WinArm64)
);
assert_eq!(PlatformTag::WinArm64.to_string(), "win_arm64");
}
#[test]
fn freebsd_platform() {
let tag = PlatformTag::FreeBsd {
| 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-platform-tags/src/language_tag.rs | crates/uv-platform-tags/src/language_tag.rs | use std::fmt::Formatter;
use std::str::FromStr;
/// A tag to represent the language and implementation of the Python interpreter.
///
/// This is the first segment in the wheel filename. For example, in `cp39-none-manylinux_2_24_x86_64.whl`,
/// the language tag is `cp39`.
#[derive(
Debug,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum LanguageTag {
/// Ex) `none`
None,
/// Ex) `py3`, `py39`
Python { major: u8, minor: Option<u8> },
/// Ex) `cp39`
CPython { python_version: (u8, u8) },
/// Ex) `pp39`
PyPy { python_version: (u8, u8) },
/// Ex) `graalpy310`
GraalPy { python_version: (u8, u8) },
/// Ex) `pyston38`
Pyston { python_version: (u8, u8) },
}
impl LanguageTag {
/// Return a pretty string representation of the language tag.
pub fn pretty(self) -> Option<String> {
match self {
Self::None => None,
Self::Python { major, minor } => {
if let Some(minor) = minor {
Some(format!("Python {major}.{minor}"))
} else {
Some(format!("Python {major}"))
}
}
Self::CPython {
python_version: (major, minor),
} => Some(format!("CPython {major}.{minor}")),
Self::PyPy {
python_version: (major, minor),
} => Some(format!("PyPy {major}.{minor}")),
Self::GraalPy {
python_version: (major, minor),
} => Some(format!("GraalPy {major}.{minor}")),
Self::Pyston {
python_version: (major, minor),
} => Some(format!("Pyston {major}.{minor}")),
}
}
}
impl std::fmt::Display for LanguageTag {
/// Format a [`LanguageTag`] as a string.
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::None => write!(f, "none"),
Self::Python { major, minor } => {
if let Some(minor) = minor {
write!(f, "py{major}{minor}")
} else {
write!(f, "py{major}")
}
}
Self::CPython {
python_version: (major, minor),
} => {
write!(f, "cp{major}{minor}")
}
Self::PyPy {
python_version: (major, minor),
} => {
write!(f, "pp{major}{minor}")
}
Self::GraalPy {
python_version: (major, minor),
} => {
write!(f, "graalpy{major}{minor}")
}
Self::Pyston {
python_version: (major, minor),
} => {
write!(f, "pyston{major}{minor}")
}
}
}
}
impl FromStr for LanguageTag {
type Err = ParseLanguageTagError;
/// Parse a [`LanguageTag`] from a string.
#[allow(clippy::cast_possible_truncation)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
/// Parse a Python version from a string (e.g., convert `39` into `(3, 9)`).
fn parse_python_version(
version_str: &str,
implementation: &'static str,
full_tag: &str,
) -> Result<(u8, u8), ParseLanguageTagError> {
let major = version_str
.chars()
.next()
.ok_or_else(|| ParseLanguageTagError::MissingMajorVersion {
implementation,
tag: full_tag.to_string(),
})?
.to_digit(10)
.ok_or_else(|| ParseLanguageTagError::InvalidMajorVersion {
implementation,
tag: full_tag.to_string(),
})? as u8;
let minor = version_str
.get(1..)
.ok_or_else(|| ParseLanguageTagError::MissingMinorVersion {
implementation,
tag: full_tag.to_string(),
})?
.parse::<u8>()
.map_err(|_| ParseLanguageTagError::InvalidMinorVersion {
implementation,
tag: full_tag.to_string(),
})?;
Ok((major, minor))
}
if s == "none" {
Ok(Self::None)
} else if let Some(py) = s.strip_prefix("py") {
match py.len() {
0 => Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "Python",
tag: s.to_string(),
}),
1 => {
// Ex) `py3`
let major = py
.chars()
.next()
.ok_or_else(|| ParseLanguageTagError::MissingMajorVersion {
implementation: "Python",
tag: s.to_string(),
})?
.to_digit(10)
.ok_or_else(|| ParseLanguageTagError::InvalidMajorVersion {
implementation: "Python",
tag: s.to_string(),
})? as u8;
Ok(Self::Python { major, minor: None })
}
2 | 3 => {
// Ex) `py39`, `py310`
let (major, minor) = parse_python_version(py, "Python", s)?;
Ok(Self::Python {
major,
minor: Some(minor),
})
}
_ => {
if let Some(pyston) = py.strip_prefix("ston") {
// Ex) `pyston38`
let (major, minor) = parse_python_version(pyston, "Pyston", s)?;
Ok(Self::Pyston {
python_version: (major, minor),
})
} else {
Err(ParseLanguageTagError::UnknownFormat(s.to_string()))
}
}
}
} else if let Some(cp) = s.strip_prefix("cp") {
// Ex) `cp39`
let (major, minor) = parse_python_version(cp, "CPython", s)?;
Ok(Self::CPython {
python_version: (major, minor),
})
} else if let Some(pp) = s.strip_prefix("pp") {
// Ex) `pp39`
let (major, minor) = parse_python_version(pp, "PyPy", s)?;
Ok(Self::PyPy {
python_version: (major, minor),
})
} else if let Some(graalpy) = s.strip_prefix("graalpy") {
// Ex) `graalpy310`
let (major, minor) = parse_python_version(graalpy, "GraalPy", s)?;
Ok(Self::GraalPy {
python_version: (major, minor),
})
} else {
Err(ParseLanguageTagError::UnknownFormat(s.to_string()))
}
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParseLanguageTagError {
#[error("Unknown language tag format: {0}")]
UnknownFormat(String),
#[error("Missing major version in {implementation} language tag: {tag}")]
MissingMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid major version in {implementation} language tag: {tag}")]
InvalidMajorVersion {
implementation: &'static str,
tag: String,
},
#[error("Missing minor version in {implementation} language tag: {tag}")]
MissingMinorVersion {
implementation: &'static str,
tag: String,
},
#[error("Invalid minor version in {implementation} language tag: {tag}")]
InvalidMinorVersion {
implementation: &'static str,
tag: String,
},
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use crate::LanguageTag;
use crate::language_tag::ParseLanguageTagError;
#[test]
fn none() {
assert_eq!(LanguageTag::from_str("none"), Ok(LanguageTag::None));
assert_eq!(LanguageTag::None.to_string(), "none");
}
#[test]
fn python_language() {
let tag = LanguageTag::Python {
major: 3,
minor: None,
};
assert_eq!(LanguageTag::from_str("py3"), Ok(tag));
assert_eq!(tag.to_string(), "py3");
let tag = LanguageTag::Python {
major: 3,
minor: Some(9),
};
assert_eq!(LanguageTag::from_str("py39"), Ok(tag));
assert_eq!(tag.to_string(), "py39");
assert_eq!(
LanguageTag::from_str("py"),
Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "Python",
tag: "py".to_string()
})
);
assert_eq!(
LanguageTag::from_str("pyX"),
Err(ParseLanguageTagError::InvalidMajorVersion {
implementation: "Python",
tag: "pyX".to_string()
})
);
assert_eq!(
LanguageTag::from_str("py3X"),
Err(ParseLanguageTagError::InvalidMinorVersion {
implementation: "Python",
tag: "py3X".to_string()
})
);
}
#[test]
fn cpython_language() {
let tag = LanguageTag::CPython {
python_version: (3, 9),
};
assert_eq!(LanguageTag::from_str("cp39"), Ok(tag));
assert_eq!(tag.to_string(), "cp39");
assert_eq!(
LanguageTag::from_str("cp"),
Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "CPython",
tag: "cp".to_string()
})
);
assert_eq!(
LanguageTag::from_str("cpX"),
Err(ParseLanguageTagError::InvalidMajorVersion {
implementation: "CPython",
tag: "cpX".to_string()
})
);
assert_eq!(
LanguageTag::from_str("cp3X"),
Err(ParseLanguageTagError::InvalidMinorVersion {
implementation: "CPython",
tag: "cp3X".to_string()
})
);
}
#[test]
fn pypy_language() {
let tag = LanguageTag::PyPy {
python_version: (3, 9),
};
assert_eq!(LanguageTag::from_str("pp39"), Ok(tag));
assert_eq!(tag.to_string(), "pp39");
assert_eq!(
LanguageTag::from_str("pp"),
Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "PyPy",
tag: "pp".to_string()
})
);
assert_eq!(
LanguageTag::from_str("ppX"),
Err(ParseLanguageTagError::InvalidMajorVersion {
implementation: "PyPy",
tag: "ppX".to_string()
})
);
assert_eq!(
LanguageTag::from_str("pp3X"),
Err(ParseLanguageTagError::InvalidMinorVersion {
implementation: "PyPy",
tag: "pp3X".to_string()
})
);
}
#[test]
fn graalpy_language() {
let tag = LanguageTag::GraalPy {
python_version: (3, 10),
};
assert_eq!(LanguageTag::from_str("graalpy310"), Ok(tag));
assert_eq!(tag.to_string(), "graalpy310");
assert_eq!(
LanguageTag::from_str("graalpy"),
Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "GraalPy",
tag: "graalpy".to_string()
})
);
assert_eq!(
LanguageTag::from_str("graalpyX"),
Err(ParseLanguageTagError::InvalidMajorVersion {
implementation: "GraalPy",
tag: "graalpyX".to_string()
})
);
assert_eq!(
LanguageTag::from_str("graalpy3X"),
Err(ParseLanguageTagError::InvalidMinorVersion {
implementation: "GraalPy",
tag: "graalpy3X".to_string()
})
);
}
#[test]
fn pyston_language() {
let tag = LanguageTag::Pyston {
python_version: (3, 8),
};
assert_eq!(LanguageTag::from_str("pyston38"), Ok(tag));
assert_eq!(tag.to_string(), "pyston38");
assert_eq!(
LanguageTag::from_str("pyston"),
Err(ParseLanguageTagError::MissingMajorVersion {
implementation: "Pyston",
tag: "pyston".to_string()
})
);
assert_eq!(
LanguageTag::from_str("pystonX"),
Err(ParseLanguageTagError::InvalidMajorVersion {
implementation: "Pyston",
tag: "pystonX".to_string()
})
);
assert_eq!(
LanguageTag::from_str("pyston3X"),
Err(ParseLanguageTagError::InvalidMinorVersion {
implementation: "Pyston",
tag: "pyston3X".to_string()
})
);
}
#[test]
fn unknown_language() {
assert_eq!(
LanguageTag::from_str("unknown"),
Err(ParseLanguageTagError::UnknownFormat("unknown".to_string()))
);
assert_eq!(
LanguageTag::from_str(""),
Err(ParseLanguageTagError::UnknownFormat(String::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-platform-tags/src/tags.rs | crates/uv-platform-tags/src/tags.rs | use std::collections::BTreeSet;
use std::fmt::Formatter;
use std::str::FromStr;
use std::sync::Arc;
use std::{cmp, num::NonZeroU32};
use rustc_hash::FxHashMap;
use uv_small_str::SmallString;
use crate::{AbiTag, Arch, LanguageTag, Os, Platform, PlatformError, PlatformTag};
#[derive(Debug, thiserror::Error)]
pub enum TagsError {
#[error(transparent)]
PlatformError(#[from] PlatformError),
#[error("Unsupported implementation: `{0}`")]
UnsupportedImplementation(String),
#[error("Unknown implementation: `{0}`")]
UnknownImplementation(String),
#[error("Invalid priority: `{0}`")]
InvalidPriority(usize, #[source] std::num::TryFromIntError),
#[error("Only CPython can be freethreading, not: {0}")]
GilIsACPythonProblem(String),
}
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Copy, Clone)]
pub enum IncompatibleTag {
/// The tag is invalid and cannot be used.
Invalid,
/// The Python implementation tag is incompatible.
Python,
/// The ABI tag is incompatible.
Abi,
/// The Python version component of the ABI tag is incompatible with `requires-python`.
AbiPythonVersion,
/// The platform tag is incompatible.
Platform,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum TagCompatibility {
Incompatible(IncompatibleTag),
Compatible(TagPriority),
}
impl Ord for TagCompatibility {
fn cmp(&self, other: &Self) -> cmp::Ordering {
match (self, other) {
(Self::Compatible(p_self), Self::Compatible(p_other)) => p_self.cmp(p_other),
(Self::Incompatible(_), Self::Compatible(_)) => cmp::Ordering::Less,
(Self::Compatible(_), Self::Incompatible(_)) => cmp::Ordering::Greater,
(Self::Incompatible(t_self), Self::Incompatible(t_other)) => t_self.cmp(t_other),
}
}
}
impl PartialOrd for TagCompatibility {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(Self::cmp(self, other))
}
}
impl TagCompatibility {
/// Returns `true` if the tag is compatible.
pub fn is_compatible(&self) -> bool {
matches!(self, Self::Compatible(_))
}
}
/// A set of compatible tags for a given Python version and platform.
///
/// Its principle function is to determine whether the tags for a particular
/// wheel are compatible with the current environment.
#[derive(Debug, Clone)]
pub struct Tags {
/// `python_tag` |--> `abi_tag` |--> `platform_tag` |--> priority
#[allow(clippy::type_complexity)]
map: Arc<FxHashMap<LanguageTag, FxHashMap<AbiTag, FxHashMap<PlatformTag, TagPriority>>>>,
/// The highest-priority tag for the Python version and platform.
best: Option<(LanguageTag, AbiTag, PlatformTag)>,
/// Python platform used to generate the tags, for error messages.
python_platform: Platform,
/// Python version used to generate the tags, for error messages.
python_version: (u8, u8),
/// Whether the tags are for a different Python interpreter than the current one, for error
/// messages.
is_cross: bool,
}
impl Tags {
/// Create a new set of tags.
///
/// Tags are prioritized based on their position in the given vector. Specifically, tags that
/// appear earlier in the vector are given higher priority than tags that appear later.
fn new(
tags: Vec<(LanguageTag, AbiTag, PlatformTag)>,
python_platform: Platform,
python_version: (u8, u8),
is_cross: bool,
) -> Self {
// Store the highest-priority tag for each component.
let best = tags.first().cloned();
// Index the tags by Python version, ABI, and platform.
let mut map = FxHashMap::default();
for (index, (py, abi, platform)) in tags.into_iter().rev().enumerate() {
map.entry(py)
.or_insert(FxHashMap::default())
.entry(abi)
.or_insert(FxHashMap::default())
.entry(platform)
.or_insert(TagPriority::try_from(index).expect("valid tag priority"));
}
Self {
map: Arc::new(map),
best,
python_platform,
python_version,
is_cross,
}
}
/// Returns the compatible tags for the given Python implementation (e.g., `cpython`), version,
/// and platform.
pub fn from_env(
platform: &Platform,
python_version: (u8, u8),
implementation_name: &str,
implementation_version: (u8, u8),
manylinux_compatible: bool,
gil_disabled: bool,
is_cross: bool,
) -> Result<Self, TagsError> {
let implementation = Implementation::parse(implementation_name, gil_disabled)?;
// Determine the compatible tags for the current platform.
let platform_tags = {
let mut platform_tags = compatible_tags(platform)?;
if matches!(platform.os(), Os::Manylinux { .. }) && !manylinux_compatible {
platform_tags.retain(|tag| !tag.is_manylinux());
}
platform_tags
};
let mut tags = Vec::with_capacity(5 * platform_tags.len());
// 1. This exact c api version
for platform_tag in &platform_tags {
tags.push((
implementation.language_tag(python_version),
implementation.abi_tag(python_version, implementation_version),
platform_tag.clone(),
));
}
// 2. abi3 and no abi (e.g. executable binary)
if let Implementation::CPython { gil_disabled } = implementation {
// For some reason 3.2 is the minimum python for the cp abi
for minor in (2..=python_version.1).rev() {
// No abi3 for free-threading python
if !gil_disabled {
for platform_tag in &platform_tags {
tags.push((
implementation.language_tag((python_version.0, minor)),
AbiTag::Abi3,
platform_tag.clone(),
));
}
}
// Only include `none` tags for the current CPython version
if minor == python_version.1 {
for platform_tag in &platform_tags {
tags.push((
implementation.language_tag((python_version.0, minor)),
AbiTag::None,
platform_tag.clone(),
));
}
}
}
}
// 3. no abi (e.g. executable binary)
for minor in (0..=python_version.1).rev() {
for platform_tag in &platform_tags {
tags.push((
LanguageTag::Python {
major: python_version.0,
minor: Some(minor),
},
AbiTag::None,
platform_tag.clone(),
));
}
// After the matching version emit `none` tags for the major version i.e. `py3`
if minor == python_version.1 {
for platform_tag in &platform_tags {
tags.push((
LanguageTag::Python {
major: python_version.0,
minor: None,
},
AbiTag::None,
platform_tag.clone(),
));
}
}
}
// 4. no binary
if matches!(implementation, Implementation::CPython { .. }) {
tags.push((
implementation.language_tag(python_version),
AbiTag::None,
PlatformTag::Any,
));
}
for minor in (0..=python_version.1).rev() {
tags.push((
LanguageTag::Python {
major: python_version.0,
minor: Some(minor),
},
AbiTag::None,
PlatformTag::Any,
));
// After the matching version emit `none` tags for the major version i.e. `py3`
if minor == python_version.1 {
tags.push((
LanguageTag::Python {
major: python_version.0,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
));
}
}
Ok(Self::new(tags, platform.clone(), python_version, is_cross))
}
/// Returns true when there exists at least one tag for this platform
/// whose individual components all appear in each of the slices given.
///
/// Like [`Tags::compatibility`], but short-circuits as soon as a compatible
/// tag is found.
pub fn is_compatible(
&self,
wheel_python_tags: &[LanguageTag],
wheel_abi_tags: &[AbiTag],
wheel_platform_tags: &[PlatformTag],
) -> bool {
// NOTE: A typical work-load is a context in which the platform tags
// are quite large, but the tags of a wheel are quite small. It is
// common, for example, for the lengths of the slices given to all be
// 1. So while the looping here might look slow, the key thing we want
// to avoid is looping over all of the platform tags. We avoid that
// with hashmap lookups.
for wheel_py in wheel_python_tags {
let Some(abis) = self.map.get(wheel_py) else {
continue;
};
for wheel_abi in wheel_abi_tags {
let Some(platforms) = abis.get(wheel_abi) else {
continue;
};
for wheel_platform in wheel_platform_tags {
if platforms.contains_key(wheel_platform) {
return true;
}
}
}
}
false
}
/// Returns the [`TagCompatibility`] of the given tags.
///
/// If compatible, includes the score of the most-compatible platform tag.
/// If incompatible, includes the tag part which was a closest match.
pub fn compatibility(
&self,
wheel_python_tags: &[LanguageTag],
wheel_abi_tags: &[AbiTag],
wheel_platform_tags: &[PlatformTag],
) -> TagCompatibility {
let mut max_compatibility = TagCompatibility::Incompatible(IncompatibleTag::Invalid);
for wheel_py in wheel_python_tags {
let Some(abis) = self.map.get(wheel_py) else {
max_compatibility =
max_compatibility.max(TagCompatibility::Incompatible(IncompatibleTag::Python));
continue;
};
for wheel_abi in wheel_abi_tags {
let Some(platforms) = abis.get(wheel_abi) else {
max_compatibility =
max_compatibility.max(TagCompatibility::Incompatible(IncompatibleTag::Abi));
continue;
};
for wheel_platform in wheel_platform_tags {
let priority = platforms.get(wheel_platform).copied();
if let Some(priority) = priority {
max_compatibility =
max_compatibility.max(TagCompatibility::Compatible(priority));
} else {
max_compatibility = max_compatibility
.max(TagCompatibility::Incompatible(IncompatibleTag::Platform));
}
}
}
}
max_compatibility
}
/// Return the highest-priority Python tag for the [`Tags`].
pub fn python_tag(&self) -> Option<LanguageTag> {
self.best.as_ref().map(|(python, _, _)| *python)
}
/// Return the highest-priority ABI tag for the [`Tags`].
pub fn abi_tag(&self) -> Option<AbiTag> {
self.best.as_ref().map(|(_, abi, _)| *abi)
}
/// Return the highest-priority platform tag for the [`Tags`].
pub fn platform_tag(&self) -> Option<&PlatformTag> {
self.best.as_ref().map(|(_, _, platform)| platform)
}
/// Returns `true` if the given language and ABI tags are compatible with the current
/// environment.
pub fn is_compatible_abi(&self, python_tag: LanguageTag, abi_tag: AbiTag) -> bool {
self.map
.get(&python_tag)
.map(|abis| abis.contains_key(&abi_tag))
.unwrap_or(false)
}
pub fn python_platform(&self) -> &Platform {
&self.python_platform
}
pub fn python_version(&self) -> (u8, u8) {
self.python_version
}
pub fn is_cross(&self) -> bool {
self.is_cross
}
}
/// The priority of a platform tag.
///
/// A wrapper around [`NonZeroU32`]. Higher values indicate higher priority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct TagPriority(NonZeroU32);
impl TryFrom<usize> for TagPriority {
type Error = TagsError;
/// Create a [`TagPriority`] from a `usize`, where higher `usize` values are given higher
/// priority.
fn try_from(priority: usize) -> Result<Self, TagsError> {
match u32::try_from(priority).and_then(|priority| NonZeroU32::try_from(1 + priority)) {
Ok(priority) => Ok(Self(priority)),
Err(err) => Err(TagsError::InvalidPriority(priority, err)),
}
}
}
impl std::fmt::Display for Tags {
/// Display tags from high to low priority
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut tags = BTreeSet::new();
for (python_tag, abi_tags) in self.map.iter() {
for (abi_tag, platform_tags) in abi_tags {
for (platform_tag, priority) in platform_tags {
tags.insert((priority, format!("{python_tag}-{abi_tag}-{platform_tag}")));
}
}
}
for (_, tag) in tags.iter().rev() {
writeln!(f, "{tag}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
enum Implementation {
CPython { gil_disabled: bool },
PyPy,
GraalPy,
Pyston,
}
impl Implementation {
/// Returns the "language implementation and version tag" for the current implementation and
/// Python version (e.g., `cp39` or `pp37`).
fn language_tag(self, python_version: (u8, u8)) -> LanguageTag {
match self {
// Ex) `cp39`
Self::CPython { .. } => LanguageTag::CPython { python_version },
// Ex) `pp39`
Self::PyPy => LanguageTag::PyPy { python_version },
// Ex) `graalpy310`
Self::GraalPy => LanguageTag::GraalPy { python_version },
// Ex) `pyston38`
Self::Pyston => LanguageTag::Pyston { python_version },
}
}
fn abi_tag(self, python_version: (u8, u8), implementation_version: (u8, u8)) -> AbiTag {
match self {
// Ex) `cp39`
Self::CPython { gil_disabled } => AbiTag::CPython {
gil_disabled,
python_version,
},
// Ex) `pypy39_pp73`
Self::PyPy => AbiTag::PyPy {
python_version: Some(python_version),
implementation_version,
},
// Ex) `graalpy240_310_native
Self::GraalPy => AbiTag::GraalPy {
python_version,
implementation_version,
},
// Ex) `pyston_23_x86_64_linux`
Self::Pyston => AbiTag::Pyston {
implementation_version,
},
}
}
fn parse(name: &str, gil_disabled: bool) -> Result<Self, TagsError> {
if gil_disabled && name != "cpython" {
return Err(TagsError::GilIsACPythonProblem(name.to_string()));
}
match name {
// Known and supported implementations.
"cpython" => Ok(Self::CPython { gil_disabled }),
"pypy" => Ok(Self::PyPy),
"graalpy" => Ok(Self::GraalPy),
"pyston" => Ok(Self::Pyston),
// Known but unsupported implementations.
"python" => Err(TagsError::UnsupportedImplementation(name.to_string())),
"ironpython" => Err(TagsError::UnsupportedImplementation(name.to_string())),
"jython" => Err(TagsError::UnsupportedImplementation(name.to_string())),
// Unknown implementations.
_ => Err(TagsError::UnknownImplementation(name.to_string())),
}
}
}
/// Returns the compatible tags for the current [`Platform`] (e.g., `manylinux_2_17`,
/// `macosx_11_0_arm64`, or `win_amd64`).
///
/// We have two cases: Actual platform specific tags (including "merged" tags such as universal2)
/// and "any".
fn compatible_tags(platform: &Platform) -> Result<Vec<PlatformTag>, PlatformError> {
let os = platform.os();
let arch = platform.arch();
let platform_tags = match (&os, arch) {
(Os::Manylinux { major, minor }, _) => {
let mut platform_tags = Vec::new();
if let Some(min_minor) = arch.get_minimum_manylinux_minor() {
for minor in (min_minor..=*minor).rev() {
platform_tags.push(PlatformTag::Manylinux {
major: *major,
minor,
arch,
});
// Support legacy manylinux tags with lower priority
// <https://peps.python.org/pep-0600/#legacy-manylinux-tags>
if minor == 12 {
platform_tags.push(PlatformTag::Manylinux2010 { arch });
}
if minor == 17 {
platform_tags.push(PlatformTag::Manylinux2014 { arch });
}
if minor == 5 {
platform_tags.push(PlatformTag::Manylinux1 { arch });
}
}
}
// Non-manylinux is given lowest priority.
// <https://github.com/pypa/packaging/blob/fd4f11139d1c884a637be8aa26bb60a31fbc9411/packaging/tags.py#L444>
platform_tags.push(PlatformTag::Linux { arch });
platform_tags
}
(Os::Musllinux { major, minor }, _) => {
let mut platform_tags = vec![PlatformTag::Linux { arch }];
platform_tags.extend((0..=*minor).map(|minor| PlatformTag::Musllinux {
major: *major,
minor,
arch,
}));
platform_tags
}
(Os::Macos { major, minor }, Arch::X86_64) => {
// Source: https://github.com/pypa/packaging/blob/fd4f11139d1c884a637be8aa26bb60a31fbc9411/packaging/tags.py#L346
let mut platform_tags = vec![];
match major {
10 => {
// Prior to Mac OS 11, each yearly release of Mac OS bumped the "minor" version
// number. The major version was always 10.
for minor in (4..=*minor).rev() {
for binary_format in BinaryFormat::from_arch(arch) {
platform_tags.push(PlatformTag::Macos {
major: 10,
minor,
binary_format: *binary_format,
});
}
}
}
value if *value >= 11 => {
// Starting with Mac OS 11, each yearly release bumps the major version number.
// The minor versions are now the midyear updates.
for major in (11..=*major).rev() {
for binary_format in BinaryFormat::from_arch(arch) {
platform_tags.push(PlatformTag::Macos {
major,
minor: 0,
binary_format: *binary_format,
});
}
}
// The "universal2" binary format can have a macOS version earlier than 11.0
// when the x86_64 part of the binary supports that version of macOS.
for minor in (4..=16).rev() {
for binary_format in BinaryFormat::from_arch(arch) {
platform_tags.push(PlatformTag::Macos {
major: 10,
minor,
binary_format: *binary_format,
});
}
}
}
_ => {
return Err(PlatformError::OsVersionDetectionError(format!(
"Unsupported macOS version: {major}",
)));
}
}
platform_tags
}
(Os::Macos { major, .. }, Arch::Aarch64) => {
// Source: https://github.com/pypa/packaging/blob/fd4f11139d1c884a637be8aa26bb60a31fbc9411/packaging/tags.py#L346
let mut platform_tags = vec![];
// Starting with Mac OS 11, each yearly release bumps the major version number.
// The minor versions are now the midyear updates.
for major in (11..=*major).rev() {
for binary_format in BinaryFormat::from_arch(arch) {
platform_tags.push(PlatformTag::Macos {
major,
minor: 0,
binary_format: *binary_format,
});
}
}
// The "universal2" binary format can have a macOS version earlier than 11.0
// when the x86_64 part of the binary supports that version of macOS.
platform_tags.extend((4..=16).rev().map(|minor| PlatformTag::Macos {
major: 10,
minor,
binary_format: BinaryFormat::Universal2,
}));
platform_tags
}
(Os::Windows, Arch::X86) => {
vec![PlatformTag::Win32]
}
(Os::Windows, Arch::X86_64) => {
vec![PlatformTag::WinAmd64]
}
(Os::Windows, Arch::Aarch64) => vec![PlatformTag::WinArm64],
(Os::FreeBsd { release }, arch) => {
let release_tag = release.replace(['.', '-'], "_").to_lowercase();
let arch_tag = arch.machine();
let release_arch = format!("{release_tag}_{arch_tag}");
vec![PlatformTag::FreeBsd {
release_arch: SmallString::from(release_arch),
}]
}
(Os::NetBsd { release }, arch) => {
let release_tag = release.replace(['.', '-'], "_");
let arch_tag = arch.machine();
let release_arch = format!("{release_tag}_{arch_tag}");
vec![PlatformTag::NetBsd {
release_arch: SmallString::from(release_arch),
}]
}
(Os::OpenBsd { release }, arch) => {
let release_tag = release.replace(['.', '-'], "_");
let arch_tag = arch.machine();
let release_arch = format!("{release_tag}_{arch_tag}");
vec![PlatformTag::OpenBsd {
release_arch: SmallString::from(release_arch),
}]
}
(Os::Dragonfly { release }, arch) => {
let release = release.replace(['.', '-'], "_");
let release_arch = format!("{release}_{arch}");
vec![PlatformTag::Dragonfly {
release_arch: SmallString::from(release_arch),
}]
}
(Os::Haiku { release }, arch) => {
let release = release.replace(['.', '-'], "_");
let release_arch = format!("{release}_{arch}");
vec![PlatformTag::Haiku {
release_arch: SmallString::from(release_arch),
}]
}
(Os::Illumos { release, arch }, _) => {
// See https://github.com/python/cpython/blob/46c8d915715aa2bd4d697482aa051fe974d440e1/Lib/sysconfig.py#L722-L730
if let Some((major, other)) = release.split_once('_') {
let major_ver: u64 = major.parse().map_err(|err| {
PlatformError::OsVersionDetectionError(format!(
"illumos major version is not a number: {err}"
))
})?;
if major_ver >= 5 {
// SunOS 5 == Solaris 2
let release = format!("{}_{}", major_ver - 3, other);
let arch = format!("{arch}_64bit");
let release_arch = format!("{release}_{arch}");
return Ok(vec![PlatformTag::Solaris {
release_arch: SmallString::from(release_arch),
}]);
}
}
let release_arch = format!("{release}_{arch}");
vec![PlatformTag::Illumos {
release_arch: SmallString::from(release_arch),
}]
}
(Os::Android { api_level }, arch) => {
// Source: https://github.com/pypa/packaging/blob/e5470c1854e352f68fa3f83df9cbb0af59558c49/src/packaging/tags.py#L541
let mut platform_tags = vec![];
// 16 is the minimum API level known to have enough features to support CPython
// without major patching. Yield every API level from the maximum down to the
// minimum, inclusive.
for ver in (16..=*api_level).rev() {
platform_tags.push(PlatformTag::Android {
api_level: ver,
abi: AndroidAbi::from_arch(arch).map_err(PlatformError::ArchDetectionError)?,
});
}
platform_tags
}
(Os::Pyodide { major, minor }, Arch::Wasm32) => {
vec![PlatformTag::Pyodide {
major: *major,
minor: *minor,
}]
}
(
Os::Ios {
major,
minor,
simulator,
},
arch,
) => {
// Source: https://github.com/pypa/packaging/blob/e9b9d09ebc5992ecad1799da22ee5faefb9cc7cb/src/packaging/tags.py#L484
let mut platform_tags = vec![];
let multiarch = IosMultiarch::from_arch(arch, *simulator)
.map_err(PlatformError::ArchDetectionError)?;
// Consider any iOS major.minor version from the version requested, down to
// 12.0. 12.0 is the first iOS version that is known to have enough features
// to support CPython. Consider every possible minor release up to X.9. The
// highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra
// candidates that won't ever match doesn't really hurt, and it saves us from
// having to keep an explicit list of known iOS versions in the code. Return
// the results descending order of version number.
// If the requested major version is less than 12, there won't be any matches.
if *major < 12 {
return Ok(platform_tags);
}
// Consider the actual X.Y version that was requested.
platform_tags.push(PlatformTag::Ios {
major: *major,
minor: *minor,
multiarch,
});
// Consider every minor version from X.0 to the minor version prior to the
// version requested by the platform.
for min in (0..*minor).rev() {
platform_tags.push(PlatformTag::Ios {
major: *major,
minor: min,
multiarch,
});
}
for maj in (12..*major).rev() {
for min in (0..=9).rev() {
platform_tags.push(PlatformTag::Ios {
major: maj,
minor: min,
multiarch,
});
}
}
platform_tags
}
_ => {
return Err(PlatformError::OsVersionDetectionError(format!(
"Unsupported operating system and architecture combination: {os} {arch}"
)));
}
};
Ok(platform_tags)
}
#[derive(
Debug,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum BinaryFormat {
Arm64,
Fat,
Fat32,
Fat64,
I386,
Intel,
Ppc,
Ppc64,
Universal,
Universal2,
X86_64,
}
impl std::fmt::Display for BinaryFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name())
}
}
impl FromStr for BinaryFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"arm64" => Ok(Self::Arm64),
"fat" => Ok(Self::Fat),
"fat32" => Ok(Self::Fat32),
"fat64" => Ok(Self::Fat64),
"i386" => Ok(Self::I386),
"intel" => Ok(Self::Intel),
"ppc" => Ok(Self::Ppc),
"ppc64" => Ok(Self::Ppc64),
"universal" => Ok(Self::Universal),
"universal2" => Ok(Self::Universal2),
"x86_64" => Ok(Self::X86_64),
_ => Err(format!("Invalid binary format: {s}")),
}
}
}
impl BinaryFormat {
/// Determine the appropriate binary formats for a macOS version.
///
/// See: <https://github.com/pypa/packaging/blob/fd4f11139d1c884a637be8aa26bb60a31fbc9411/packaging/tags.py#L314>
pub fn from_arch(arch: Arch) -> &'static [Self] {
match arch {
Arch::Aarch64 => &[Self::Arm64, Self::Universal2],
Arch::Powerpc64 => &[Self::Ppc64, Self::Fat64, Self::Universal],
Arch::Powerpc => &[Self::Ppc, Self::Fat32, Self::Fat, Self::Universal],
Arch::X86 => &[
Self::I386,
Self::Intel,
Self::Fat32,
Self::Fat,
Self::Universal,
],
Arch::X86_64 => &[
Self::X86_64,
Self::Intel,
Self::Fat64,
Self::Fat32,
Self::Universal2,
Self::Universal,
],
_ => unreachable!(),
}
}
/// Return the supported `platform_machine` tags for the binary format.
///
/// This is roughly the inverse of the above: given a binary format, which `platform_machine`
/// tags are supported?
pub fn platform_machine(&self) -> &'static [Self] {
match self {
Self::Arm64 => &[Self::Arm64],
Self::Fat => &[Self::X86_64, Self::Ppc],
Self::Fat32 => &[Self::X86_64, Self::I386, Self::Ppc, Self::Ppc64],
Self::Fat64 => &[Self::X86_64, Self::Ppc64],
Self::I386 => &[Self::I386],
Self::Intel => &[Self::X86_64, Self::I386],
Self::Ppc => &[Self::Ppc],
Self::Ppc64 => &[Self::Ppc64],
Self::Universal => &[
Self::X86_64,
Self::I386,
Self::Ppc64,
Self::Ppc,
Self::Intel,
],
Self::Universal2 => &[Self::X86_64, Self::Arm64],
Self::X86_64 => &[Self::X86_64],
}
}
/// Return the canonical name of the binary format.
pub fn name(&self) -> &'static str {
match self {
Self::Arm64 => "arm64",
Self::Fat => "fat",
Self::Fat32 => "fat32",
Self::Fat64 => "fat64",
Self::I386 => "i386",
Self::Intel => "intel",
Self::Ppc => "ppc",
Self::Ppc64 => "ppc64",
Self::Universal => "universal",
Self::Universal2 => "universal2",
Self::X86_64 => "x86_64",
}
}
}
#[derive(
Debug,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum AndroidAbi {
// Source: https://packaging.python.org/en/latest/specifications/platform-compatibility-tags/#android
ArmeabiV7a,
Arm64V8a,
X86,
X86_64,
}
| 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-cli/build.rs | crates/uv-cli/build.rs | use std::{
path::{Path, PathBuf},
process::Command,
};
use fs_err as fs;
use uv_static::EnvVars;
fn main() {
// The workspace root directory is not available without walking up the tree
// https://github.com/rust-lang/cargo/issues/3946
let workspace_root = Path::new(&std::env::var(EnvVars::CARGO_MANIFEST_DIR).unwrap())
.parent()
.expect("CARGO_MANIFEST_DIR should be nested in workspace")
.parent()
.expect("CARGO_MANIFEST_DIR should be doubly nested in workspace")
.to_path_buf();
commit_info(&workspace_root);
#[allow(clippy::disallowed_methods)]
let target = std::env::var(EnvVars::TARGET).unwrap();
println!("cargo:rustc-env=RUST_HOST_TARGET={target}");
}
fn commit_info(workspace_root: &Path) {
// If not in a git repository, do not attempt to retrieve commit information
let git_dir = workspace_root.join(".git");
if !git_dir.exists() {
return;
}
if let Some(git_head_path) = git_head(&git_dir) {
println!("cargo:rerun-if-changed={}", git_head_path.display());
let git_head_contents = fs::read_to_string(git_head_path);
if let Ok(git_head_contents) = git_head_contents {
// The contents are either a commit or a reference in the following formats
// - "<commit>" when the head is detached
// - "ref <ref>" when working on a branch
// If a commit, checking if the HEAD file has changed is sufficient
// If a ref, we need to add the head file for that ref to rebuild on commit
let mut git_ref_parts = git_head_contents.split_whitespace();
git_ref_parts.next();
if let Some(git_ref) = git_ref_parts.next() {
let git_ref_path = git_dir.join(git_ref);
println!("cargo:rerun-if-changed={}", git_ref_path.display());
}
}
}
let output = match Command::new("git")
.arg("log")
.arg("-1")
.arg("--date=short")
.arg("--abbrev=9")
.arg("--format=%H %h %cd %(describe:tags)")
.output()
{
Ok(output) if output.status.success() => output,
_ => return,
};
let stdout = String::from_utf8(output.stdout).unwrap();
let mut parts = stdout.split_whitespace();
let mut next = || parts.next().unwrap();
println!("cargo:rustc-env={}={}", EnvVars::UV_COMMIT_HASH, next());
println!(
"cargo:rustc-env={}={}",
EnvVars::UV_COMMIT_SHORT_HASH,
next()
);
println!("cargo:rustc-env={}={}", EnvVars::UV_COMMIT_DATE, next());
// Describe can fail for some commits
// https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt-emdescribeoptionsem
if let Some(describe) = parts.next() {
let mut describe_parts = describe.split('-');
println!(
"cargo:rustc-env={}={}",
EnvVars::UV_LAST_TAG,
describe_parts.next().unwrap()
);
// If this is the tagged commit, this component will be missing
println!(
"cargo:rustc-env={}={}",
EnvVars::UV_LAST_TAG_DISTANCE,
describe_parts.next().unwrap_or("0")
);
}
}
fn git_head(git_dir: &Path) -> Option<PathBuf> {
// The typical case is a standard git repository.
let git_head_path = git_dir.join("HEAD");
if git_head_path.exists() {
return Some(git_head_path);
}
if !git_dir.is_file() {
return None;
}
// If `.git/HEAD` doesn't exist and `.git` is actually a file,
// then let's try to attempt to read it as a worktree. If it's
// a worktree, then its contents will look like this, e.g.:
//
// gitdir: /home/andrew/astral/uv/main/.git/worktrees/pr2
//
// And the HEAD file we want to watch will be at:
//
// /home/andrew/astral/uv/main/.git/worktrees/pr2/HEAD
let contents = fs::read_to_string(git_dir).ok()?;
let (label, worktree_path) = contents.split_once(':')?;
if label != "gitdir" {
return None;
}
let worktree_path = worktree_path.trim();
Some(PathBuf::from(worktree_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-cli/src/lib.rs | crates/uv-cli/src/lib.rs | use std::ffi::OsString;
use std::fmt::{self, Display, Formatter};
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::{Result, anyhow};
use clap::builder::styling::{AnsiColor, Effects, Style};
use clap::builder::{PossibleValue, Styles, TypedValueParser, ValueParserFactory};
use clap::error::ErrorKind;
use clap::{Args, Parser, Subcommand};
use clap::{ValueEnum, ValueHint};
use uv_auth::Service;
use uv_cache::CacheArgs;
use uv_configuration::{
ExportFormat, IndexStrategy, KeyringProviderType, PackageNameSpecifier, PipCompileFormat,
ProjectBuildBackend, TargetTriple, TrustedHost, TrustedPublishing, VersionControlSystem,
};
use uv_distribution_types::{
ConfigSettingEntry, ConfigSettingPackageEntry, Index, IndexUrl, Origin, PipExtraIndex,
PipFindLinks, PipIndex,
};
use uv_normalize::{ExtraName, GroupName, PackageName, PipGroupName};
use uv_pep508::{MarkerTree, Requirement};
use uv_preview::PreviewFeatures;
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::{PythonDownloads, PythonPreference, PythonVersion};
use uv_redacted::DisplaySafeUrl;
use uv_resolver::{
AnnotationStyle, ExcludeNewerPackageEntry, ExcludeNewerValue, ForkStrategy, PrereleaseMode,
ResolutionMode,
};
use uv_settings::PythonInstallMirrors;
use uv_static::EnvVars;
use uv_torch::TorchMode;
use uv_workspace::pyproject_mut::AddBoundsKind;
pub mod comma;
pub mod compat;
pub mod options;
pub mod version;
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum VersionFormat {
/// Display the version as plain text.
Text,
/// Display the version as JSON.
Json,
}
#[derive(Debug, Default, Clone, Copy, clap::ValueEnum)]
pub enum PythonListFormat {
/// Plain text (for humans).
#[default]
Text,
/// JSON (for computers).
Json,
}
#[derive(Debug, Default, Clone, Copy, clap::ValueEnum)]
pub enum SyncFormat {
/// Display the result in a human-readable format.
#[default]
Text,
/// Display the result in JSON format.
Json,
}
#[derive(Debug, Default, Clone, clap::ValueEnum)]
pub enum ListFormat {
/// Display the list of packages in a human-readable table.
#[default]
Columns,
/// Display the list of packages in a `pip freeze`-like format, with one package per line
/// alongside its version.
Freeze,
/// Display the list of packages in a machine-readable JSON format.
Json,
}
fn extra_name_with_clap_error(arg: &str) -> Result<ExtraName> {
ExtraName::from_str(arg).map_err(|_err| {
anyhow!(
"Extra names must start and end with a letter or digit and may only \
contain -, _, ., and alphanumeric characters"
)
})
}
// Configures Clap v3-style help menu colors
const STYLES: Styles = Styles::styled()
.header(AnsiColor::Green.on_default().effects(Effects::BOLD))
.usage(AnsiColor::Green.on_default().effects(Effects::BOLD))
.literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))
.placeholder(AnsiColor::Cyan.on_default());
#[derive(Parser)]
#[command(name = "uv", author, long_version = crate::version::uv_self_version())]
#[command(about = "An extremely fast Python package manager.")]
#[command(
after_help = "Use `uv help` for more details.",
after_long_help = "",
disable_help_flag = true,
disable_help_subcommand = true,
disable_version_flag = true
)]
#[command(styles=STYLES)]
pub struct Cli {
#[command(subcommand)]
pub command: Box<Commands>,
#[command(flatten)]
pub top_level: TopLevelArgs,
}
#[derive(Parser)]
#[command(disable_help_flag = true, disable_version_flag = true)]
pub struct TopLevelArgs {
#[command(flatten)]
pub cache_args: Box<CacheArgs>,
#[command(flatten)]
pub global_args: Box<GlobalArgs>,
/// The path to a `uv.toml` file to use for configuration.
///
/// While uv configuration can be included in a `pyproject.toml` file, it is
/// not allowed in this context.
#[arg(
global = true,
long,
env = EnvVars::UV_CONFIG_FILE,
help_heading = "Global options",
value_hint = ValueHint::FilePath,
)]
pub config_file: Option<PathBuf>,
/// Avoid discovering configuration files (`pyproject.toml`, `uv.toml`).
///
/// Normally, configuration files are discovered in the current directory,
/// parent directories, or user configuration directories.
#[arg(global = true, long, env = EnvVars::UV_NO_CONFIG, value_parser = clap::builder::BoolishValueParser::new(), help_heading = "Global options")]
pub no_config: bool,
/// Display the concise help for this command.
#[arg(global = true, short, long, action = clap::ArgAction::HelpShort, help_heading = "Global options")]
help: Option<bool>,
/// Display the uv version.
#[arg(short = 'V', long, action = clap::ArgAction::Version)]
version: Option<bool>,
}
#[derive(Parser, Debug, Clone)]
#[command(next_help_heading = "Global options", next_display_order = 1000)]
pub struct GlobalArgs {
#[arg(
global = true,
long,
help_heading = "Python options",
display_order = 700,
env = EnvVars::UV_PYTHON_PREFERENCE,
hide = true
)]
pub python_preference: Option<PythonPreference>,
/// Require use of uv-managed Python versions.
///
/// By default, uv prefers using Python versions it manages. However, it
/// will use system Python versions if a uv-managed Python is not
/// installed. This option disables use of system Python versions.
#[arg(
global = true,
long,
help_heading = "Python options",
env = EnvVars::UV_MANAGED_PYTHON,
value_parser = clap::builder::BoolishValueParser::new(),
overrides_with = "no_managed_python",
conflicts_with = "python_preference"
)]
pub managed_python: bool,
/// Disable use of uv-managed Python versions.
///
/// Instead, uv will search for a suitable Python version on the system.
#[arg(
global = true,
long,
help_heading = "Python options",
env = EnvVars::UV_NO_MANAGED_PYTHON,
value_parser = clap::builder::BoolishValueParser::new(),
overrides_with = "managed_python",
conflicts_with = "python_preference"
)]
pub no_managed_python: bool,
#[allow(clippy::doc_markdown)]
/// Allow automatically downloading Python when required. [env: "UV_PYTHON_DOWNLOADS=auto"]
#[arg(global = true, long, help_heading = "Python options", hide = true)]
pub allow_python_downloads: bool,
#[allow(clippy::doc_markdown)]
/// Disable automatic downloads of Python. [env: "UV_PYTHON_DOWNLOADS=never"]
#[arg(global = true, long, help_heading = "Python options")]
pub no_python_downloads: bool,
/// Deprecated version of [`Self::python_downloads`].
#[arg(global = true, long, hide = true)]
pub python_fetch: Option<PythonDownloads>,
/// Use quiet output.
///
/// Repeating this option, e.g., `-qq`, will enable a silent mode in which
/// uv will write no output to stdout.
#[arg(global = true, action = clap::ArgAction::Count, long, short, conflicts_with = "verbose")]
pub quiet: u8,
/// Use verbose output.
///
/// You can configure fine-grained logging using the `RUST_LOG` environment variable.
/// (<https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives>)
#[arg(global = true, action = clap::ArgAction::Count, long, short, conflicts_with = "quiet")]
pub verbose: u8,
/// Disable colors.
///
/// Provided for compatibility with `pip`, use `--color` instead.
#[arg(global = true, long, hide = true, conflicts_with = "color")]
pub no_color: bool,
/// Control the use of color in output.
///
/// By default, uv will automatically detect support for colors when writing to a terminal.
#[arg(
global = true,
long,
value_enum,
conflicts_with = "no_color",
value_name = "COLOR_CHOICE"
)]
pub color: Option<ColorChoice>,
/// Whether to load TLS certificates from the platform's native certificate store.
///
/// By default, uv loads certificates from the bundled `webpki-roots` crate. The
/// `webpki-roots` are a reliable set of trust roots from Mozilla, and including them in uv
/// improves portability and performance (especially on macOS).
///
/// However, in some cases, you may want to use the platform's native certificate store,
/// especially if you're relying on a corporate trust root (e.g., for a mandatory proxy) that's
/// included in your system's certificate store.
#[arg(global = true, long, env = EnvVars::UV_NATIVE_TLS, value_parser = clap::builder::BoolishValueParser::new(), overrides_with("no_native_tls"))]
pub native_tls: bool,
#[arg(global = true, long, overrides_with("native_tls"), hide = true)]
pub no_native_tls: bool,
/// Disable network access.
///
/// When disabled, uv will only use locally cached data and locally available files.
#[arg(global = true, long, overrides_with("no_offline"), env = EnvVars::UV_OFFLINE, value_parser = clap::builder::BoolishValueParser::new())]
pub offline: bool,
#[arg(global = true, long, overrides_with("offline"), hide = true)]
pub no_offline: bool,
/// Allow insecure connections to a host.
///
/// Can be provided multiple times.
///
/// Expects to receive either a hostname (e.g., `localhost`), a host-port pair (e.g.,
/// `localhost:8080`), or a URL (e.g., `https://localhost`).
///
/// WARNING: Hosts included in this list will not be verified against the system's certificate
/// store. Only use `--allow-insecure-host` in a secure network with verified sources, as it
/// bypasses SSL verification and could expose you to MITM attacks.
#[arg(
global = true,
long,
alias = "trusted-host",
env = EnvVars::UV_INSECURE_HOST,
value_delimiter = ' ',
value_parser = parse_insecure_host,
value_hint = ValueHint::Url,
)]
pub allow_insecure_host: Option<Vec<Maybe<TrustedHost>>>,
/// Whether to enable all experimental preview features.
///
/// Preview features may change without warning.
#[arg(global = true, long, hide = true, env = EnvVars::UV_PREVIEW, value_parser = clap::builder::BoolishValueParser::new(), overrides_with("no_preview"))]
pub preview: bool,
#[arg(global = true, long, overrides_with("preview"), hide = true)]
pub no_preview: bool,
/// Enable experimental preview features.
///
/// Preview features may change without warning.
///
/// Use comma-separated values or pass multiple times to enable multiple features.
///
/// The following features are available: `python-install-default`, `python-upgrade`,
/// `json-output`, `pylock`, `add-bounds`.
#[arg(
global = true,
long = "preview-features",
env = EnvVars::UV_PREVIEW_FEATURES,
value_delimiter = ',',
hide = true,
alias = "preview-feature",
value_enum,
)]
pub preview_features: Vec<PreviewFeatures>,
/// Avoid discovering a `pyproject.toml` or `uv.toml` file.
///
/// Normally, configuration files are discovered in the current directory,
/// parent directories, or user configuration directories.
///
/// This option is deprecated in favor of `--no-config`.
#[arg(global = true, long, hide = true, env = EnvVars::UV_ISOLATED, value_parser = clap::builder::BoolishValueParser::new())]
pub isolated: bool,
/// Show the resolved settings for the current command.
///
/// This option is used for debugging and development purposes.
#[arg(global = true, long, hide = true)]
pub show_settings: bool,
/// Hide all progress outputs.
///
/// For example, spinners or progress bars.
#[arg(global = true, long, env = EnvVars::UV_NO_PROGRESS, value_parser = clap::builder::BoolishValueParser::new())]
pub no_progress: bool,
/// Skip writing `uv` installer metadata files (e.g., `INSTALLER`, `REQUESTED`, and `direct_url.json`) to site-packages `.dist-info` directories.
#[arg(global = true, long, hide = true, env = EnvVars::UV_NO_INSTALLER_METADATA, value_parser = clap::builder::BoolishValueParser::new())]
pub no_installer_metadata: bool,
/// Change to the given directory prior to running the command.
///
/// Relative paths are resolved with the given directory as the base.
///
/// See `--project` to only change the project root directory.
#[arg(global = true, long, env = EnvVars::UV_WORKING_DIR, value_hint = ValueHint::DirPath)]
pub directory: Option<PathBuf>,
/// Discover a project in the given directory.
///
/// All `pyproject.toml`, `uv.toml`, and `.python-version` files will be discovered by walking
/// up the directory tree from the project root, as will the project's virtual environment
/// (`.venv`).
///
/// Other command-line arguments (such as relative paths) will be resolved relative
/// to the current working directory.
///
/// See `--directory` to change the working directory entirely.
///
/// This setting has no effect when used in the `uv pip` interface.
#[arg(global = true, long, env = EnvVars::UV_PROJECT, value_hint = ValueHint::DirPath)]
pub project: Option<PathBuf>,
}
#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub enum ColorChoice {
/// Enables colored output only when the output is going to a terminal or TTY with support.
Auto,
/// Enables colored output regardless of the detected environment.
Always,
/// Disables colored output.
Never,
}
impl ColorChoice {
/// Combine self (higher priority) with an [`anstream::ColorChoice`] (lower priority).
///
/// This method allows prioritizing the user choice, while using the inferred choice for a
/// stream as default.
#[must_use]
pub fn and_colorchoice(self, next: anstream::ColorChoice) -> Self {
match self {
Self::Auto => match next {
anstream::ColorChoice::Auto => Self::Auto,
anstream::ColorChoice::Always | anstream::ColorChoice::AlwaysAnsi => Self::Always,
anstream::ColorChoice::Never => Self::Never,
},
Self::Always | Self::Never => self,
}
}
}
impl From<ColorChoice> for anstream::ColorChoice {
fn from(value: ColorChoice) -> Self {
match value {
ColorChoice::Auto => Self::Auto,
ColorChoice::Always => Self::Always,
ColorChoice::Never => Self::Never,
}
}
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Commands {
/// Manage authentication.
#[command(
after_help = "Use `uv help auth` for more details.",
after_long_help = ""
)]
Auth(AuthNamespace),
/// Manage Python projects.
#[command(flatten)]
Project(Box<ProjectCommand>),
/// Run and install commands provided by Python packages.
#[command(
after_help = "Use `uv help tool` for more details.",
after_long_help = ""
)]
Tool(ToolNamespace),
/// Manage Python versions and installations
///
/// Generally, uv first searches for Python in a virtual environment, either active or in a
/// `.venv` directory in the current working directory or any parent directory. If a virtual
/// environment is not required, uv will then search for a Python interpreter. Python
/// interpreters are found by searching for Python executables in the `PATH` environment
/// variable.
///
/// On Windows, the registry is also searched for Python executables.
///
/// By default, uv will download Python if a version cannot be found. This behavior can be
/// disabled with the `--no-python-downloads` flag or the `python-downloads` setting.
///
/// The `--python` option allows requesting a different interpreter.
///
/// The following Python version request formats are supported:
///
/// - `<version>` e.g. `3`, `3.12`, `3.12.3`
/// - `<version-specifier>` e.g. `>=3.12,<3.13`
/// - `<version><short-variant>` (e.g., `3.13t`, `3.12.0d`)
/// - `<version>+<variant>` (e.g., `3.13+freethreaded`, `3.12.0+debug`)
/// - `<implementation>` e.g. `cpython` or `cp`
/// - `<implementation>@<version>` e.g. `cpython@3.12`
/// - `<implementation><version>` e.g. `cpython3.12` or `cp312`
/// - `<implementation><version-specifier>` e.g. `cpython>=3.12,<3.13`
/// - `<implementation>-<version>-<os>-<arch>-<libc>` e.g. `cpython-3.12.3-macos-aarch64-none`
///
/// Additionally, a specific system Python interpreter can often be requested with:
///
/// - `<executable-path>` e.g. `/opt/homebrew/bin/python3`
/// - `<executable-name>` e.g. `mypython3`
/// - `<install-dir>` e.g. `/some/environment/`
///
/// When the `--python` option is used, normal discovery rules apply but discovered interpreters
/// are checked for compatibility with the request, e.g., if `pypy` is requested, uv will first
/// check if the virtual environment contains a PyPy interpreter then check if each executable
/// in the path is a PyPy interpreter.
///
/// uv supports discovering CPython, PyPy, and GraalPy interpreters. Unsupported interpreters
/// will be skipped during discovery. If an unsupported interpreter implementation is requested,
/// uv will exit with an error.
#[clap(verbatim_doc_comment)]
#[command(
after_help = "Use `uv help python` for more details.",
after_long_help = ""
)]
Python(PythonNamespace),
/// Manage Python packages with a pip-compatible interface.
#[command(
after_help = "Use `uv help pip` for more details.",
after_long_help = ""
)]
Pip(PipNamespace),
/// Create a virtual environment.
///
/// By default, creates a virtual environment named `.venv` in the working
/// directory. An alternative path may be provided positionally.
///
/// If in a project, the default environment name can be changed with
/// the `UV_PROJECT_ENVIRONMENT` environment variable; this only applies
/// when run from the project root directory.
///
/// If a virtual environment exists at the target path, it will be removed
/// and a new, empty virtual environment will be created.
///
/// When using uv, the virtual environment does not need to be activated. uv
/// will find a virtual environment (named `.venv`) in the working directory
/// or any parent directories.
#[command(
alias = "virtualenv",
alias = "v",
after_help = "Use `uv help venv` for more details.",
after_long_help = ""
)]
Venv(VenvArgs),
/// Build Python packages into source distributions and wheels.
///
/// `uv build` accepts a path to a directory or source distribution,
/// which defaults to the current working directory.
///
/// By default, if passed a directory, `uv build` will build a source
/// distribution ("sdist") from the source directory, and a binary
/// distribution ("wheel") from the source distribution.
///
/// `uv build --sdist` can be used to build only the source distribution,
/// `uv build --wheel` can be used to build only the binary distribution,
/// and `uv build --sdist --wheel` can be used to build both distributions
/// from source.
///
/// If passed a source distribution, `uv build --wheel` will build a wheel
/// from the source distribution.
#[command(
after_help = "Use `uv help build` for more details.",
after_long_help = ""
)]
Build(BuildArgs),
/// Upload distributions to an index.
Publish(PublishArgs),
/// Inspect uv workspaces.
#[command(
after_help = "Use `uv help workspace` for more details.",
after_long_help = "",
hide = true
)]
Workspace(WorkspaceNamespace),
/// The implementation of the build backend.
///
/// These commands are not directly exposed to the user, instead users invoke their build
/// frontend (PEP 517) which calls the Python shims which calls back into uv with this method.
#[command(hide = true)]
BuildBackend {
#[command(subcommand)]
command: BuildBackendCommand,
},
/// Manage uv's cache.
#[command(
after_help = "Use `uv help cache` for more details.",
after_long_help = ""
)]
Cache(CacheNamespace),
/// Manage the uv executable.
#[command(name = "self")]
Self_(SelfNamespace),
/// Clear the cache, removing all entries or those linked to specific packages.
#[command(hide = true)]
Clean(CleanArgs),
/// Generate shell completion
#[command(alias = "--generate-shell-completion", hide = true)]
GenerateShellCompletion(GenerateShellCompletionArgs),
/// Display documentation for a command.
// To avoid showing the global options when displaying help for the help command, we are
// responsible for maintaining the options using the `after_help`.
#[command(help_template = "\
{about-with-newline}
{usage-heading} {usage}{after-help}
",
after_help = format!("\
{heading}Options:{heading:#}
{option}--no-pager{option:#} Disable pager when printing help
",
heading = Style::new().bold().underline(),
option = Style::new().bold(),
),
)]
Help(HelpArgs),
}
#[derive(Args, Debug)]
pub struct HelpArgs {
/// Disable pager when printing help
#[arg(long)]
pub no_pager: bool,
#[arg(value_hint = ValueHint::Other)]
pub command: Option<Vec<String>>,
}
#[derive(Args)]
#[command(group = clap::ArgGroup::new("operation"))]
pub struct VersionArgs {
/// Set the project version to this value
///
/// To update the project using semantic versioning components instead, use `--bump`.
#[arg(group = "operation", value_hint = ValueHint::Other)]
pub value: Option<String>,
/// Update the project version using the given semantics
///
/// This flag can be passed multiple times.
#[arg(group = "operation", long, value_name = "BUMP[=VALUE]")]
pub bump: Vec<VersionBumpSpec>,
/// Don't write a new version to the `pyproject.toml`
///
/// Instead, the version will be displayed.
#[arg(long)]
pub dry_run: bool,
/// Only show the version
///
/// By default, uv will show the project name before the version.
#[arg(long)]
pub short: bool,
/// The format of the output
#[arg(long, value_enum, default_value = "text")]
pub output_format: VersionFormat,
/// Avoid syncing the virtual environment after re-locking the project.
#[arg(long, env = EnvVars::UV_NO_SYNC, value_parser = clap::builder::BoolishValueParser::new(), conflicts_with = "frozen")]
pub no_sync: bool,
/// Prefer the active virtual environment over the project's virtual environment.
///
/// If the project virtual environment is active or no virtual environment is active, this has
/// no effect.
#[arg(long, overrides_with = "no_active")]
pub active: bool,
/// Prefer project's virtual environment over an active environment.
///
/// This is the default behavior.
#[arg(long, overrides_with = "active", hide = true)]
pub no_active: bool,
/// Assert that the `uv.lock` will remain unchanged.
///
/// Requires that the lockfile is up-to-date. If the lockfile is missing or needs to be updated,
/// uv will exit with an error.
#[arg(long, env = EnvVars::UV_LOCKED, value_parser = clap::builder::BoolishValueParser::new(), conflicts_with_all = ["frozen", "upgrade"])]
pub locked: bool,
/// Update the version without re-locking the project.
///
/// The project environment will not be synced.
#[arg(long, env = EnvVars::UV_FROZEN, value_parser = clap::builder::BoolishValueParser::new(), conflicts_with_all = ["locked", "upgrade", "no_sources"])]
pub frozen: bool,
#[command(flatten)]
pub installer: ResolverInstallerArgs,
#[command(flatten)]
pub build: BuildOptionsArgs,
#[command(flatten)]
pub refresh: RefreshArgs,
/// Update the version of a specific package in the workspace.
#[arg(long, conflicts_with = "isolated", value_hint = ValueHint::Other)]
pub package: Option<PackageName>,
/// The Python interpreter to use for resolving and syncing.
///
/// See `uv help python` for details on Python discovery and supported request formats.
#[arg(
long,
short,
env = EnvVars::UV_PYTHON,
verbatim_doc_comment,
help_heading = "Python options",
value_parser = parse_maybe_string,
value_hint = ValueHint::Other,
)]
pub python: Option<Maybe<String>>,
}
// Note that the ordering of the variants is significant, as when given a list of operations
// to perform, we sort them and apply them in order, so users don't have to think too hard about it.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)]
pub enum VersionBump {
/// Increase the major version (e.g., 1.2.3 => 2.0.0)
Major,
/// Increase the minor version (e.g., 1.2.3 => 1.3.0)
Minor,
/// Increase the patch version (e.g., 1.2.3 => 1.2.4)
Patch,
/// Move from a pre-release to stable version (e.g., 1.2.3b4.post5.dev6 => 1.2.3)
///
/// Removes all pre-release components, but will not remove "local" components.
Stable,
/// Increase the alpha version (e.g., 1.2.3a4 => 1.2.3a5)
///
/// To move from a stable to a pre-release version, combine this with a stable component, e.g.,
/// for 1.2.3 => 2.0.0a1, you'd also include [`VersionBump::Major`].
Alpha,
/// Increase the beta version (e.g., 1.2.3b4 => 1.2.3b5)
///
/// To move from a stable to a pre-release version, combine this with a stable component, e.g.,
/// for 1.2.3 => 2.0.0b1, you'd also include [`VersionBump::Major`].
Beta,
/// Increase the rc version (e.g., 1.2.3rc4 => 1.2.3rc5)
///
/// To move from a stable to a pre-release version, combine this with a stable component, e.g.,
/// for 1.2.3 => 2.0.0rc1, you'd also include [`VersionBump::Major`].]
Rc,
/// Increase the post version (e.g., 1.2.3.post5 => 1.2.3.post6)
Post,
/// Increase the dev version (e.g., 1.2.3a4.dev6 => 1.2.3.dev7)
Dev,
}
impl Display for VersionBump {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let string = match self {
Self::Major => "major",
Self::Minor => "minor",
Self::Patch => "patch",
Self::Stable => "stable",
Self::Alpha => "alpha",
Self::Beta => "beta",
Self::Rc => "rc",
Self::Post => "post",
Self::Dev => "dev",
};
string.fmt(f)
}
}
impl FromStr for VersionBump {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"major" => Ok(Self::Major),
"minor" => Ok(Self::Minor),
"patch" => Ok(Self::Patch),
"stable" => Ok(Self::Stable),
"alpha" => Ok(Self::Alpha),
"beta" => Ok(Self::Beta),
"rc" => Ok(Self::Rc),
"post" => Ok(Self::Post),
"dev" => Ok(Self::Dev),
_ => Err(format!("invalid bump component `{value}`")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct VersionBumpSpec {
pub bump: VersionBump,
pub value: Option<u64>,
}
impl Display for VersionBumpSpec {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.value {
Some(value) => write!(f, "{}={value}", self.bump),
None => self.bump.fmt(f),
}
}
}
impl FromStr for VersionBumpSpec {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let (name, value) = match input.split_once('=') {
Some((name, value)) => (name, Some(value)),
None => (input, None),
};
let bump = name.parse::<VersionBump>()?;
if bump == VersionBump::Stable && value.is_some() {
return Err("`--bump stable` does not accept a value".to_string());
}
let value = match value {
Some("") => {
return Err("`--bump` values cannot be empty".to_string());
}
Some(raw) => Some(
raw.parse::<u64>()
.map_err(|_| format!("invalid numeric value `{raw}` for `--bump {name}`"))?,
),
None => None,
};
Ok(Self { bump, value })
}
}
impl ValueParserFactory for VersionBumpSpec {
type Parser = VersionBumpSpecValueParser;
fn value_parser() -> Self::Parser {
VersionBumpSpecValueParser
}
}
#[derive(Clone, Debug)]
pub struct VersionBumpSpecValueParser;
impl TypedValueParser for VersionBumpSpecValueParser {
type Value = VersionBumpSpec;
fn parse_ref(
&self,
_cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
let raw = value.to_str().ok_or_else(|| {
clap::Error::raw(
ErrorKind::InvalidUtf8,
"`--bump` values must be valid UTF-8",
)
})?;
VersionBumpSpec::from_str(raw)
.map_err(|message| clap::Error::raw(ErrorKind::InvalidValue, message))
}
fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
Some(Box::new(
VersionBump::value_variants()
.iter()
.filter_map(ValueEnum::to_possible_value),
))
}
}
#[derive(Args)]
pub struct SelfNamespace {
#[command(subcommand)]
pub command: SelfCommand,
}
#[derive(Subcommand)]
pub enum SelfCommand {
/// Update uv.
Update(SelfUpdateArgs),
/// Display uv's version
Version {
/// Only print the version
#[arg(long)]
short: bool,
#[arg(long, value_enum, default_value = "text")]
output_format: VersionFormat,
},
}
#[derive(Args, Debug)]
pub struct SelfUpdateArgs {
/// Update to the specified version. If not provided, uv will update to the latest version.
#[arg(value_hint = ValueHint::Other)]
pub target_version: Option<String>,
/// A GitHub token for authentication.
/// A token is not required but can be used to reduce the chance of encountering rate limits.
#[arg(long, env = EnvVars::UV_GITHUB_TOKEN, value_hint = ValueHint::Other)]
pub token: Option<String>,
/// Run without performing the update.
#[arg(long)]
pub dry_run: bool,
}
#[derive(Args)]
pub struct CacheNamespace {
#[command(subcommand)]
pub command: CacheCommand,
}
#[derive(Subcommand)]
pub enum CacheCommand {
/// Clear the cache, removing all entries or those linked to specific packages.
Clean(CleanArgs),
/// Prune all unreachable objects from the cache.
Prune(PruneArgs),
/// Show the cache directory.
///
/// By default, the cache is stored in `$XDG_CACHE_HOME/uv` or `$HOME/.cache/uv` on Unix and
/// `%LOCALAPPDATA%\uv\cache` on Windows.
///
/// When `--no-cache` is used, the cache is stored in a temporary directory and discarded when
/// the process exits.
///
/// An alternative cache directory may be specified via the `cache-dir` setting, the
/// `--cache-dir` option, or the `$UV_CACHE_DIR` environment variable.
///
/// Note that it is important for performance for the cache directory to be located on the same
/// file system as the Python environment uv is operating on.
Dir,
/// Show the cache size.
///
/// Displays the total size of the cache directory. This includes all downloaded and built
/// wheels, source distributions, and other cached data. By default, outputs the size in raw
/// bytes; use `--human` for human-readable output.
Size(SizeArgs),
}
#[derive(Args, Debug)]
pub struct CleanArgs {
/// The packages to remove from the cache.
#[arg(value_hint = ValueHint::Other)]
pub package: Vec<PackageName>,
/// Force removal of the cache, ignoring in-use checks.
///
/// By default, `uv cache clean` will block until no process is reading the cache. When
| 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-cli/src/version.rs | crates/uv-cli/src/version.rs | //! Code for representing uv's release version number.
// See also <https://github.com/astral-sh/ruff/blob/8118d29419055b779719cc96cdf3dacb29ac47c9/crates/ruff/src/version.rs>
use std::fmt;
use serde::Serialize;
use uv_normalize::PackageName;
use uv_pep508::uv_pep440::Version;
/// Information about the git repository where uv was built from.
#[derive(Serialize)]
pub(crate) struct CommitInfo {
short_commit_hash: String,
commit_hash: String,
commit_date: String,
last_tag: Option<String>,
commits_since_last_tag: u32,
}
/// uv's version.
#[derive(Serialize)]
pub struct VersionInfo {
/// Name of the package (or "uv" if printing uv's own version)
pub package_name: Option<String>,
/// version, such as "0.5.1"
version: String,
/// Information about the git commit we may have been built from.
///
/// `None` if not built from a git repo or if retrieval failed.
commit_info: Option<CommitInfo>,
}
impl VersionInfo {
pub fn new(package_name: Option<&PackageName>, version: &Version) -> Self {
Self {
package_name: package_name.map(ToString::to_string),
version: version.to_string(),
commit_info: None,
}
}
}
impl fmt::Display for VersionInfo {
/// Formatted version information: "<version>[+<commits>] (<commit> <date>)"
///
/// This is intended for consumption by `clap` to provide `uv --version`,
/// and intentionally omits the name of the package
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.version)?;
if let Some(ci) = &self.commit_info {
write!(f, "{ci}")?;
}
Ok(())
}
}
impl fmt::Display for CommitInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.commits_since_last_tag > 0 {
write!(f, "+{}", self.commits_since_last_tag)?;
}
write!(f, " ({} {})", self.short_commit_hash, self.commit_date)?;
Ok(())
}
}
impl From<VersionInfo> for clap::builder::Str {
fn from(val: VersionInfo) -> Self {
val.to_string().into()
}
}
/// Returns information about uv's version.
pub fn uv_self_version() -> VersionInfo {
// Environment variables are only read at compile-time
macro_rules! option_env_str {
($name:expr) => {
option_env!($name).map(|s| s.to_string())
};
}
// This version is pulled from Cargo.toml and set by Cargo
let version = uv_version::version().to_string();
// Commit info is pulled from git and set by `build.rs`
let commit_info = option_env_str!("UV_COMMIT_HASH").map(|commit_hash| CommitInfo {
short_commit_hash: option_env_str!("UV_COMMIT_SHORT_HASH").unwrap(),
commit_hash,
commit_date: option_env_str!("UV_COMMIT_DATE").unwrap(),
last_tag: option_env_str!("UV_LAST_TAG"),
commits_since_last_tag: option_env_str!("UV_LAST_TAG_DISTANCE")
.as_deref()
.map_or(0, |value| value.parse::<u32>().unwrap_or(0)),
});
VersionInfo {
package_name: Some("uv".to_owned()),
version,
commit_info,
}
}
#[cfg(test)]
mod tests {
use insta::{assert_json_snapshot, assert_snapshot};
use super::{CommitInfo, VersionInfo};
#[test]
fn version_formatting() {
let version = VersionInfo {
package_name: Some("uv".to_string()),
version: "0.0.0".to_string(),
commit_info: None,
};
assert_snapshot!(version, @"0.0.0");
}
#[test]
fn version_formatting_with_commit_info() {
let version = VersionInfo {
package_name: Some("uv".to_string()),
version: "0.0.0".to_string(),
commit_info: Some(CommitInfo {
short_commit_hash: "53b0f5d92".to_string(),
commit_hash: "53b0f5d924110e5b26fbf09f6fd3a03d67b475b7".to_string(),
last_tag: Some("v0.0.1".to_string()),
commit_date: "2023-10-19".to_string(),
commits_since_last_tag: 0,
}),
};
assert_snapshot!(version, @"0.0.0 (53b0f5d92 2023-10-19)");
}
#[test]
fn version_formatting_with_commits_since_last_tag() {
let version = VersionInfo {
package_name: Some("uv".to_string()),
version: "0.0.0".to_string(),
commit_info: Some(CommitInfo {
short_commit_hash: "53b0f5d92".to_string(),
commit_hash: "53b0f5d924110e5b26fbf09f6fd3a03d67b475b7".to_string(),
last_tag: Some("v0.0.1".to_string()),
commit_date: "2023-10-19".to_string(),
commits_since_last_tag: 24,
}),
};
assert_snapshot!(version, @"0.0.0+24 (53b0f5d92 2023-10-19)");
}
#[test]
fn version_serializable() {
let version = VersionInfo {
package_name: Some("uv".to_string()),
version: "0.0.0".to_string(),
commit_info: Some(CommitInfo {
short_commit_hash: "53b0f5d92".to_string(),
commit_hash: "53b0f5d924110e5b26fbf09f6fd3a03d67b475b7".to_string(),
last_tag: Some("v0.0.1".to_string()),
commit_date: "2023-10-19".to_string(),
commits_since_last_tag: 0,
}),
};
assert_json_snapshot!(version, @r#"
{
"package_name": "uv",
"version": "0.0.0",
"commit_info": {
"short_commit_hash": "53b0f5d92",
"commit_hash": "53b0f5d924110e5b26fbf09f6fd3a03d67b475b7",
"commit_date": "2023-10-19",
"last_tag": "v0.0.1",
"commits_since_last_tag": 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-cli/src/comma.rs | crates/uv-cli/src/comma.rs | use std::str::FromStr;
/// A comma-separated string of requirements, e.g., `"flask,anyio"`, that takes extras into account
/// (i.e., treats `"psycopg[binary,pool]"` as a single requirement).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CommaSeparatedRequirements(Vec<String>);
impl IntoIterator for CommaSeparatedRequirements {
type Item = String;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromStr for CommaSeparatedRequirements {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
// Split on commas _outside_ of brackets.
let mut requirements = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (i, c) in input.char_indices() {
match c {
'[' => {
depth = depth.saturating_add(1);
}
']' => {
depth = depth.saturating_sub(1);
}
',' if depth == 0 => {
// If the next character is a version identifier, skip the comma, as in:
// `requests>=2.1,<3`.
if let Some(c) = input
.get(i + ','.len_utf8()..)
.and_then(|s| s.chars().find(|c| !c.is_whitespace()))
{
if matches!(c, '!' | '=' | '<' | '>' | '~') {
continue;
}
}
let requirement = input[start..i].trim().to_string();
if !requirement.is_empty() {
requirements.push(requirement);
}
start = i + ','.len_utf8();
}
_ => {}
}
}
let requirement = input[start..].trim().to_string();
if !requirement.is_empty() {
requirements.push(requirement);
}
Ok(Self(requirements))
}
}
#[cfg(test)]
mod tests {
use super::CommaSeparatedRequirements;
use std::str::FromStr;
#[test]
fn single() {
assert_eq!(
CommaSeparatedRequirements::from_str("flask").unwrap(),
CommaSeparatedRequirements(vec!["flask".to_string()])
);
}
#[test]
fn double() {
assert_eq!(
CommaSeparatedRequirements::from_str("flask,anyio").unwrap(),
CommaSeparatedRequirements(vec!["flask".to_string(), "anyio".to_string()])
);
}
#[test]
fn empty() {
assert_eq!(
CommaSeparatedRequirements::from_str("flask,,anyio").unwrap(),
CommaSeparatedRequirements(vec!["flask".to_string(), "anyio".to_string()])
);
}
#[test]
fn single_extras() {
assert_eq!(
CommaSeparatedRequirements::from_str("psycopg[binary,pool]").unwrap(),
CommaSeparatedRequirements(vec!["psycopg[binary,pool]".to_string()])
);
}
#[test]
fn double_extras() {
assert_eq!(
CommaSeparatedRequirements::from_str("psycopg[binary,pool], flask").unwrap(),
CommaSeparatedRequirements(vec![
"psycopg[binary,pool]".to_string(),
"flask".to_string()
])
);
}
#[test]
fn single_specifiers() {
assert_eq!(
CommaSeparatedRequirements::from_str("requests>=2.1,<3").unwrap(),
CommaSeparatedRequirements(vec!["requests>=2.1,<3".to_string()])
);
}
#[test]
fn double_specifiers() {
assert_eq!(
CommaSeparatedRequirements::from_str("requests>=2.1,<3, flask").unwrap(),
CommaSeparatedRequirements(vec!["requests>=2.1,<3".to_string(), "flask".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-cli/src/options.rs | crates/uv-cli/src/options.rs | use anstream::eprintln;
use uv_cache::Refresh;
use uv_configuration::{BuildIsolation, Reinstall, Upgrade};
use uv_distribution_types::{ConfigSettings, PackageConfigSettings, Requirement};
use uv_resolver::{ExcludeNewer, ExcludeNewerPackage, PrereleaseMode};
use uv_settings::{Combine, PipOptions, ResolverInstallerOptions, ResolverOptions};
use uv_warnings::owo_colors::OwoColorize;
use crate::{
BuildOptionsArgs, FetchArgs, IndexArgs, InstallerArgs, Maybe, RefreshArgs, ResolverArgs,
ResolverInstallerArgs,
};
/// Given a boolean flag pair (like `--upgrade` and `--no-upgrade`), resolve the value of the flag.
pub fn flag(yes: bool, no: bool, name: &str) -> Option<bool> {
match (yes, no) {
(true, false) => Some(true),
(false, true) => Some(false),
(false, false) => None,
(..) => {
eprintln!(
"{}{} `{}` and `{}` cannot be used together. \
Boolean flags on different levels are currently not supported \
(https://github.com/clap-rs/clap/issues/6049)",
"error".bold().red(),
":".bold(),
format!("--{name}").green(),
format!("--no-{name}").green(),
);
// No error forwarding since should eventually be solved on the clap side.
#[allow(clippy::exit)]
{
std::process::exit(2);
}
}
}
}
impl From<RefreshArgs> for Refresh {
fn from(value: RefreshArgs) -> Self {
let RefreshArgs {
refresh,
no_refresh,
refresh_package,
} = value;
Self::from_args(flag(refresh, no_refresh, "no-refresh"), refresh_package)
}
}
impl From<ResolverArgs> for PipOptions {
fn from(args: ResolverArgs) -> Self {
let ResolverArgs {
index_args,
upgrade,
no_upgrade,
upgrade_package,
index_strategy,
keyring_provider,
resolution,
prerelease,
pre,
fork_strategy,
config_setting,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
build_isolation,
exclude_newer,
link_mode,
no_sources,
exclude_newer_package,
} = args;
Self {
upgrade: flag(upgrade, no_upgrade, "no-upgrade"),
upgrade_package: Some(upgrade_package),
index_strategy,
keyring_provider,
resolution,
fork_strategy,
prerelease: if pre {
Some(PrereleaseMode::Allow)
} else {
prerelease
},
config_settings: config_setting
.map(|config_settings| config_settings.into_iter().collect::<ConfigSettings>()),
config_settings_package: config_settings_package.map(|config_settings| {
config_settings
.into_iter()
.collect::<PackageConfigSettings>()
}),
no_build_isolation: flag(no_build_isolation, build_isolation, "build-isolation"),
no_build_isolation_package: Some(no_build_isolation_package),
exclude_newer,
exclude_newer_package: exclude_newer_package.map(ExcludeNewerPackage::from_iter),
link_mode,
no_sources: if no_sources { Some(true) } else { None },
..Self::from(index_args)
}
}
}
impl From<InstallerArgs> for PipOptions {
fn from(args: InstallerArgs) -> Self {
let InstallerArgs {
index_args,
reinstall,
no_reinstall,
reinstall_package,
index_strategy,
keyring_provider,
config_setting,
config_settings_package,
no_build_isolation,
build_isolation,
exclude_newer,
link_mode,
compile_bytecode,
no_compile_bytecode,
no_sources,
exclude_newer_package,
} = args;
Self {
reinstall: flag(reinstall, no_reinstall, "reinstall"),
reinstall_package: Some(reinstall_package),
index_strategy,
keyring_provider,
config_settings: config_setting
.map(|config_settings| config_settings.into_iter().collect::<ConfigSettings>()),
config_settings_package: config_settings_package.map(|config_settings| {
config_settings
.into_iter()
.collect::<PackageConfigSettings>()
}),
no_build_isolation: flag(no_build_isolation, build_isolation, "build-isolation"),
exclude_newer,
exclude_newer_package: exclude_newer_package.map(ExcludeNewerPackage::from_iter),
link_mode,
compile_bytecode: flag(compile_bytecode, no_compile_bytecode, "compile-bytecode"),
no_sources: if no_sources { Some(true) } else { None },
..Self::from(index_args)
}
}
}
impl From<ResolverInstallerArgs> for PipOptions {
fn from(args: ResolverInstallerArgs) -> Self {
let ResolverInstallerArgs {
index_args,
upgrade,
no_upgrade,
upgrade_package,
reinstall,
no_reinstall,
reinstall_package,
index_strategy,
keyring_provider,
resolution,
prerelease,
pre,
fork_strategy,
config_setting,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
build_isolation,
exclude_newer,
link_mode,
compile_bytecode,
no_compile_bytecode,
no_sources,
exclude_newer_package,
} = args;
Self {
upgrade: flag(upgrade, no_upgrade, "upgrade"),
upgrade_package: Some(upgrade_package),
reinstall: flag(reinstall, no_reinstall, "reinstall"),
reinstall_package: Some(reinstall_package),
index_strategy,
keyring_provider,
resolution,
prerelease: if pre {
Some(PrereleaseMode::Allow)
} else {
prerelease
},
fork_strategy,
config_settings: config_setting
.map(|config_settings| config_settings.into_iter().collect::<ConfigSettings>()),
config_settings_package: config_settings_package.map(|config_settings| {
config_settings
.into_iter()
.collect::<PackageConfigSettings>()
}),
no_build_isolation: flag(no_build_isolation, build_isolation, "build-isolation"),
no_build_isolation_package: Some(no_build_isolation_package),
exclude_newer,
exclude_newer_package: exclude_newer_package.map(ExcludeNewerPackage::from_iter),
link_mode,
compile_bytecode: flag(compile_bytecode, no_compile_bytecode, "compile-bytecode"),
no_sources: if no_sources { Some(true) } else { None },
..Self::from(index_args)
}
}
}
impl From<FetchArgs> for PipOptions {
fn from(args: FetchArgs) -> Self {
let FetchArgs {
index_args,
index_strategy,
keyring_provider,
exclude_newer,
} = args;
Self {
index_strategy,
keyring_provider,
exclude_newer,
..Self::from(index_args)
}
}
}
impl From<IndexArgs> for PipOptions {
fn from(args: IndexArgs) -> Self {
let IndexArgs {
default_index,
index,
index_url,
extra_index_url,
no_index,
find_links,
} = args;
Self {
index: default_index
.and_then(Maybe::into_option)
.map(|default_index| vec![default_index])
.combine(index.map(|index| {
index
.iter()
.flat_map(std::clone::Clone::clone)
.filter_map(Maybe::into_option)
.collect()
})),
index_url: index_url.and_then(Maybe::into_option),
extra_index_url: extra_index_url.map(|extra_index_urls| {
extra_index_urls
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
no_index: if no_index { Some(true) } else { None },
find_links: find_links.map(|find_links| {
find_links
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
..Self::default()
}
}
}
/// Construct the [`ResolverOptions`] from the [`ResolverArgs`] and [`BuildOptionsArgs`].
pub fn resolver_options(
resolver_args: ResolverArgs,
build_args: BuildOptionsArgs,
) -> ResolverOptions {
let ResolverArgs {
index_args,
upgrade,
no_upgrade,
upgrade_package,
index_strategy,
keyring_provider,
resolution,
prerelease,
pre,
fork_strategy,
config_setting,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
build_isolation,
exclude_newer,
link_mode,
no_sources,
exclude_newer_package,
} = resolver_args;
let BuildOptionsArgs {
no_build,
build,
no_build_package,
no_binary,
binary,
no_binary_package,
} = build_args;
ResolverOptions {
index: index_args
.default_index
.and_then(Maybe::into_option)
.map(|default_index| vec![default_index])
.combine(index_args.index.map(|index| {
index
.into_iter()
.flat_map(|v| v.clone())
.filter_map(Maybe::into_option)
.collect()
})),
index_url: index_args.index_url.and_then(Maybe::into_option),
extra_index_url: index_args.extra_index_url.map(|extra_index_url| {
extra_index_url
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
no_index: if index_args.no_index {
Some(true)
} else {
None
},
find_links: index_args.find_links.map(|find_links| {
find_links
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
upgrade: Upgrade::from_args(
flag(upgrade, no_upgrade, "no-upgrade"),
upgrade_package.into_iter().map(Requirement::from).collect(),
),
index_strategy,
keyring_provider,
resolution,
prerelease: if pre {
Some(PrereleaseMode::Allow)
} else {
prerelease
},
fork_strategy,
dependency_metadata: None,
config_settings: config_setting
.map(|config_settings| config_settings.into_iter().collect::<ConfigSettings>()),
config_settings_package: config_settings_package.map(|config_settings| {
config_settings
.into_iter()
.collect::<PackageConfigSettings>()
}),
build_isolation: BuildIsolation::from_args(
flag(no_build_isolation, build_isolation, "build-isolation"),
no_build_isolation_package,
),
extra_build_dependencies: None,
extra_build_variables: None,
exclude_newer: ExcludeNewer::from_args(
exclude_newer,
exclude_newer_package.unwrap_or_default(),
),
link_mode,
torch_backend: None,
no_build: flag(no_build, build, "build"),
no_build_package: Some(no_build_package),
no_binary: flag(no_binary, binary, "binary"),
no_binary_package: Some(no_binary_package),
no_sources: if no_sources { Some(true) } else { None },
}
}
/// Construct the [`ResolverInstallerOptions`] from the [`ResolverInstallerArgs`] and [`BuildOptionsArgs`].
pub fn resolver_installer_options(
resolver_installer_args: ResolverInstallerArgs,
build_args: BuildOptionsArgs,
) -> ResolverInstallerOptions {
let ResolverInstallerArgs {
index_args,
upgrade,
no_upgrade,
upgrade_package,
reinstall,
no_reinstall,
reinstall_package,
index_strategy,
keyring_provider,
resolution,
prerelease,
pre,
fork_strategy,
config_setting,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
build_isolation,
exclude_newer,
exclude_newer_package,
link_mode,
compile_bytecode,
no_compile_bytecode,
no_sources,
} = resolver_installer_args;
let BuildOptionsArgs {
no_build,
build,
no_build_package,
no_binary,
binary,
no_binary_package,
} = build_args;
let default_index = index_args
.default_index
.and_then(Maybe::into_option)
.map(|default_index| vec![default_index]);
let index = index_args.index.map(|index| {
index
.into_iter()
.flat_map(|v| v.clone())
.filter_map(Maybe::into_option)
.collect()
});
ResolverInstallerOptions {
index: default_index.combine(index),
index_url: index_args.index_url.and_then(Maybe::into_option),
extra_index_url: index_args.extra_index_url.map(|extra_index_url| {
extra_index_url
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
no_index: if index_args.no_index {
Some(true)
} else {
None
},
find_links: index_args.find_links.map(|find_links| {
find_links
.into_iter()
.filter_map(Maybe::into_option)
.collect()
}),
upgrade: Upgrade::from_args(
flag(upgrade, no_upgrade, "upgrade"),
upgrade_package.into_iter().map(Requirement::from).collect(),
),
reinstall: Reinstall::from_args(
flag(reinstall, no_reinstall, "reinstall"),
reinstall_package,
),
index_strategy,
keyring_provider,
resolution,
prerelease: if pre {
Some(PrereleaseMode::Allow)
} else {
prerelease
},
fork_strategy,
dependency_metadata: None,
config_settings: config_setting
.map(|config_settings| config_settings.into_iter().collect::<ConfigSettings>()),
config_settings_package: config_settings_package.map(|config_settings| {
config_settings
.into_iter()
.collect::<PackageConfigSettings>()
}),
build_isolation: BuildIsolation::from_args(
flag(no_build_isolation, build_isolation, "build-isolation"),
no_build_isolation_package,
),
extra_build_dependencies: None,
extra_build_variables: None,
exclude_newer,
exclude_newer_package: exclude_newer_package.map(ExcludeNewerPackage::from_iter),
link_mode,
compile_bytecode: flag(compile_bytecode, no_compile_bytecode, "compile-bytecode"),
no_build: flag(no_build, build, "build"),
no_build_package: if no_build_package.is_empty() {
None
} else {
Some(no_build_package)
},
no_binary: flag(no_binary, binary, "binary"),
no_binary_package: if no_binary_package.is_empty() {
None
} else {
Some(no_binary_package)
},
no_sources: if no_sources { Some(true) } else { None },
torch_backend: 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-cli/src/compat.rs | crates/uv-cli/src/compat.rs | use anyhow::{Result, anyhow};
use clap::{Args, ValueEnum};
use uv_warnings::warn_user;
pub trait CompatArgs {
fn validate(&self) -> Result<()>;
}
/// Arguments for `pip-compile` compatibility.
///
/// These represent a subset of the `pip-compile` interface that uv supports by default.
/// For example, users often pass `--allow-unsafe`, which is unnecessary with uv. But it's a
/// nice user experience to warn, rather than fail, when users pass `--allow-unsafe`.
#[derive(Args)]
pub struct PipCompileCompatArgs {
#[clap(long, hide = true)]
allow_unsafe: bool,
#[clap(long, hide = true)]
no_allow_unsafe: bool,
#[clap(long, hide = true)]
reuse_hashes: bool,
#[clap(long, hide = true)]
no_reuse_hashes: bool,
#[clap(long, hide = true)]
resolver: Option<Resolver>,
#[clap(long, hide = true)]
max_rounds: Option<usize>,
#[clap(long, hide = true)]
cert: Option<String>,
#[clap(long, hide = true)]
client_cert: Option<String>,
#[clap(long, hide = true)]
emit_trusted_host: bool,
#[clap(long, hide = true)]
no_emit_trusted_host: bool,
#[clap(long, hide = true)]
config: Option<String>,
#[clap(long, hide = true)]
no_config: bool,
#[clap(long, hide = true)]
emit_options: bool,
#[clap(long, hide = true)]
no_emit_options: bool,
#[clap(long, hide = true)]
pip_args: Option<String>,
}
impl CompatArgs for PipCompileCompatArgs {
/// Validate the arguments passed for `pip-compile` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior (e.g.,
/// `--no-build-isolation`), this method will return an error.
fn validate(&self) -> Result<()> {
if self.allow_unsafe {
warn_user!(
"pip-compile's `--allow-unsafe` has no effect (uv can safely pin `pip` and other packages)"
);
}
if self.no_allow_unsafe {
warn_user!(
"pip-compile's `--no-allow-unsafe` has no effect (uv can safely pin `pip` and other packages)"
);
}
if self.reuse_hashes {
return Err(anyhow!(
"pip-compile's `--reuse-hashes` is unsupported (uv doesn't reuse hashes)"
));
}
if self.no_reuse_hashes {
warn_user!("pip-compile's `--no-reuse-hashes` has no effect (uv doesn't reuse hashes)");
}
if let Some(resolver) = self.resolver {
match resolver {
Resolver::Backtracking => {
warn_user!(
"pip-compile's `--resolver=backtracking` has no effect (uv always backtracks)"
);
}
Resolver::Legacy => {
return Err(anyhow!(
"pip-compile's `--resolver=legacy` is unsupported (uv always backtracks)"
));
}
}
}
if self.max_rounds.is_some() {
return Err(anyhow!(
"pip-compile's `--max-rounds` is unsupported (uv always resolves until convergence)"
));
}
if self.client_cert.is_some() {
return Err(anyhow!(
"pip-compile's `--client-cert` is unsupported (uv doesn't support dedicated client certificates)"
));
}
if self.emit_trusted_host {
return Err(anyhow!(
"pip-compile's `--emit-trusted-host` is unsupported"
));
}
if self.no_emit_trusted_host {
warn_user!(
"pip-compile's `--no-emit-trusted-host` has no effect (uv never emits trusted hosts)"
);
}
if self.config.is_some() {
return Err(anyhow!(
"pip-compile's `--config` is unsupported (uv does not use a configuration file)"
));
}
if self.emit_options {
return Err(anyhow!(
"pip-compile's `--emit-options` is unsupported (uv never emits options)"
));
}
if self.no_emit_options {
warn_user!("pip-compile's `--no-emit-options` has no effect (uv never emits options)");
}
if self.pip_args.is_some() {
return Err(anyhow!(
"pip-compile's `--pip-args` is unsupported (try passing arguments to uv directly)"
));
}
Ok(())
}
}
/// Arguments for `pip list` compatibility.
///
/// These represent a subset of the `pip list` interface that uv supports by default.
#[derive(Args)]
pub struct PipListCompatArgs {
#[clap(long, hide = true)]
disable_pip_version_check: bool,
}
impl CompatArgs for PipListCompatArgs {
/// Validate the arguments passed for `pip list` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior (e.g.,
/// `--disable-pip-version-check`), this method will return an error.
fn validate(&self) -> Result<()> {
if self.disable_pip_version_check {
warn_user!("pip's `--disable-pip-version-check` has no effect");
}
Ok(())
}
}
/// Arguments for `pip-sync` compatibility.
///
/// These represent a subset of the `pip-sync` interface that uv supports by default.
#[derive(Args)]
pub struct PipSyncCompatArgs {
#[clap(short, long, hide = true)]
ask: bool,
#[clap(long, hide = true)]
python_executable: Option<String>,
#[clap(long, hide = true)]
user: bool,
#[clap(long, hide = true)]
cert: Option<String>,
#[clap(long, hide = true)]
client_cert: Option<String>,
#[clap(long, hide = true)]
config: Option<String>,
#[clap(long, hide = true)]
no_config: bool,
#[clap(long, hide = true)]
pip_args: Option<String>,
}
impl CompatArgs for PipSyncCompatArgs {
/// Validate the arguments passed for `pip-sync` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior, this method will
/// return an error.
fn validate(&self) -> Result<()> {
if self.ask {
return Err(anyhow!(
"pip-sync's `--ask` is unsupported (uv never asks for confirmation)"
));
}
if self.python_executable.is_some() {
return Err(anyhow!(
"pip-sync's `--python-executable` is unsupported (to install into a separate Python environment, try setting `VIRTUAL_ENV` instead)"
));
}
if self.user {
return Err(anyhow!(
"pip-sync's `--user` is unsupported (use a virtual environment instead)"
));
}
if self.client_cert.is_some() {
return Err(anyhow!(
"pip-sync's `--client-cert` is unsupported (uv doesn't support dedicated client certificates)"
));
}
if self.config.is_some() {
return Err(anyhow!(
"pip-sync's `--config` is unsupported (uv does not use a configuration file)"
));
}
if self.pip_args.is_some() {
return Err(anyhow!(
"pip-sync's `--pip-args` is unsupported (try passing arguments to uv directly)"
));
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, ValueEnum)]
enum Resolver {
Backtracking,
Legacy,
}
/// Arguments for `venv` compatibility.
///
/// These represent a subset of the `virtualenv` interface that uv supports by default.
#[derive(Args)]
pub struct VenvCompatArgs {
#[clap(long, hide = true)]
no_seed: bool,
#[clap(long, hide = true)]
no_pip: bool,
#[clap(long, hide = true)]
no_setuptools: bool,
#[clap(long, hide = true)]
no_wheel: bool,
}
impl CompatArgs for VenvCompatArgs {
/// Validate the arguments passed for `venv` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior, this method will
/// return an error.
fn validate(&self) -> Result<()> {
if self.no_seed {
warn_user!(
"virtualenv's `--no-seed` has no effect (uv omits seed packages by default)"
);
}
if self.no_pip {
warn_user!("virtualenv's `--no-pip` has no effect (uv omits `pip` by default)");
}
if self.no_setuptools {
warn_user!(
"virtualenv's `--no-setuptools` has no effect (uv omits `setuptools` by default)"
);
}
if self.no_wheel {
warn_user!("virtualenv's `--no-wheel` has no effect (uv omits `wheel` by default)");
}
Ok(())
}
}
/// Arguments for `pip install` compatibility.
///
/// These represent a subset of the `pip install` interface that uv supports by default.
#[derive(Args)]
pub struct PipInstallCompatArgs {
#[clap(long, hide = true)]
disable_pip_version_check: bool,
#[clap(long, hide = false)]
user: bool,
}
impl CompatArgs for PipInstallCompatArgs {
/// Validate the arguments passed for `pip install` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior, this method will
/// return an error.
fn validate(&self) -> Result<()> {
if self.disable_pip_version_check {
warn_user!("pip's `--disable-pip-version-check` has no effect");
}
if self.user {
return Err(anyhow!(
"pip's `--user` is unsupported (use a virtual environment instead)"
));
}
Ok(())
}
}
/// Arguments for generic `pip` command compatibility.
///
/// These represent a subset of the `pip` interface that exists on all commands.
#[derive(Args)]
pub struct PipGlobalCompatArgs {
#[clap(long, hide = true)]
disable_pip_version_check: bool,
}
impl CompatArgs for PipGlobalCompatArgs {
/// Validate the arguments passed for `pip` compatibility.
///
/// This method will warn when an argument is passed that has no effect but matches uv's
/// behavior. If an argument is passed that does _not_ match uv's behavior, this method will
/// return an error.
fn validate(&self) -> Result<()> {
if self.disable_pip_version_check {
warn_user!("pip's `--disable-pip-version-check` has no effect");
}
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-build-backend/src/settings.rs | crates/uv-build-backend/src/settings.rs | use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use uv_macros::OptionsMetadata;
/// Settings for the uv build backend (`uv_build`).
///
/// Note that those settings only apply when using the `uv_build` backend, other build backends
/// (such as hatchling) have their own configuration.
///
/// All options that accept globs use the portable glob patterns from
/// [PEP 639](https://packaging.python.org/en/latest/specifications/glob-patterns/).
#[derive(Deserialize, Serialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
#[serde(default, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct BuildBackendSettings {
/// The directory that contains the module directory.
///
/// Common values are `src` (src layout, the default) or an empty path (flat layout).
#[option(
default = r#""src""#,
value_type = "str",
example = r#"module-root = """#
)]
pub module_root: PathBuf,
/// The name of the module directory inside `module-root`.
///
/// The default module name is the package name with dots and dashes replaced by underscores.
///
/// Package names need to be valid Python identifiers, and the directory needs to contain a
/// `__init__.py`. An exception are stubs packages, whose name ends with `-stubs`, with the stem
/// being the module name, and which contain a `__init__.pyi` file.
///
/// For namespace packages with a single module, the path can be dotted, e.g., `foo.bar` or
/// `foo-stubs.bar`.
///
/// For namespace packages with multiple modules, the path can be a list, e.g.,
/// `["foo", "bar"]`. We recommend using a single module per package, splitting multiple
/// packages into a workspace.
///
/// Note that using this option runs the risk of creating two packages with different names but
/// the same module names. Installing such packages together leads to unspecified behavior,
/// often with corrupted files or directory trees.
#[option(
default = r#"None"#,
value_type = "str | list[str]",
example = r#"module-name = "sklearn""#
)]
pub module_name: Option<ModuleName>,
/// Glob expressions which files and directories to additionally include in the source
/// distribution.
///
/// `pyproject.toml` and the contents of the module directory are always included.
#[option(
default = r#"[]"#,
value_type = "list[str]",
example = r#"source-include = ["tests/**"]"#
)]
pub source_include: Vec<String>,
/// If set to `false`, the default excludes aren't applied.
///
/// Default excludes: `__pycache__`, `*.pyc`, and `*.pyo`.
#[option(
default = r#"true"#,
value_type = "bool",
example = r#"default-excludes = false"#
)]
pub default_excludes: bool,
/// Glob expressions which files and directories to exclude from the source distribution.
///
/// These exclusions are also applied to wheels to ensure that a wheel built from a source tree
/// is consistent with a wheel built from a source distribution.
#[option(
default = r#"[]"#,
value_type = "list[str]",
example = r#"source-exclude = ["*.bin"]"#
)]
pub source_exclude: Vec<String>,
/// Glob expressions which files and directories to exclude from the wheel.
#[option(
default = r#"[]"#,
value_type = "list[str]",
example = r#"wheel-exclude = ["*.bin"]"#
)]
pub wheel_exclude: Vec<String>,
/// Build a namespace package.
///
/// Build a PEP 420 implicit namespace package, allowing more than one root `__init__.py`.
///
/// Use this option when the namespace package contains multiple root `__init__.py`, for
/// namespace packages with a single root `__init__.py` use a dotted `module-name` instead.
///
/// To compare dotted `module-name` and `namespace = true`, the first example below can be
/// expressed with `module-name = "cloud.database"`: There is one root `__init__.py` `database`.
/// In the second example, we have three roots (`cloud.database`, `cloud.database_pro`,
/// `billing.modules.database_pro`), so `namespace = true` is required.
///
/// ```text
/// src
/// └── cloud
/// └── database
/// ├── __init__.py
/// ├── query_builder
/// │ └── __init__.py
/// └── sql
/// ├── parser.py
/// └── __init__.py
/// ```
///
/// ```text
/// src
/// ├── cloud
/// │ ├── database
/// │ │ ├── __init__.py
/// │ │ ├── query_builder
/// │ │ │ └── __init__.py
/// │ │ └── sql
/// │ │ ├── __init__.py
/// │ │ └── parser.py
/// │ └── database_pro
/// │ ├── __init__.py
/// │ └── query_builder.py
/// └── billing
/// └── modules
/// └── database_pro
/// ├── __init__.py
/// └── sql.py
/// ```
#[option(
default = r#"false"#,
value_type = "bool",
example = r#"namespace = true"#
)]
pub namespace: bool,
/// Data includes for wheels.
///
/// Each entry is a directory, whose contents are copied to the matching directory in the wheel
/// in `<name>-<version>.data/(purelib|platlib|headers|scripts|data)`. Upon installation, this
/// data is moved to its target location, as defined by
/// <https://docs.python.org/3.12/library/sysconfig.html#installation-paths>. Usually, small
/// data files are included by placing them in the Python module instead of using data includes.
///
/// - `scripts`: Installed to the directory for executables, `<venv>/bin` on Unix or
/// `<venv>\Scripts` on Windows. This directory is added to `PATH` when the virtual
/// environment is activated or when using `uv run`, so this data type can be used to install
/// additional binaries. Consider using `project.scripts` instead for Python entrypoints.
/// - `data`: Installed over the virtualenv environment root.
///
/// Warning: This may override existing files!
///
/// - `headers`: Installed to the include directory. Compilers building Python packages
/// with this package as build requirement use the include directory to find additional header
/// files.
/// - `purelib` and `platlib`: Installed to the `site-packages` directory. It is not recommended
/// to use these two options.
// TODO(konsti): We should show a flat example instead.
// ```toml
// [tool.uv.build-backend.data]
// headers = "include/headers",
// scripts = "bin"
// ```
#[option(
default = r#"{}"#,
value_type = "dict[str, str]",
example = r#"data = { headers = "include/headers", scripts = "bin" }"#
)]
pub data: WheelDataIncludes,
}
impl Default for BuildBackendSettings {
fn default() -> Self {
Self {
module_root: PathBuf::from("src"),
module_name: None,
source_include: Vec::new(),
default_excludes: true,
source_exclude: Vec::new(),
wheel_exclude: Vec::new(),
namespace: false,
data: WheelDataIncludes::default(),
}
}
}
/// Whether to include a single module or multiple modules.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum ModuleName {
/// A single module name.
Name(String),
/// Multiple module names, which are all included.
Names(Vec<String>),
}
/// Data includes for wheels.
///
/// See `BuildBackendSettings::data`.
#[derive(Default, Deserialize, Serialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
// `deny_unknown_fields` to catch typos such as `header` vs `headers`.
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct WheelDataIncludes {
purelib: Option<PathBuf>,
platlib: Option<PathBuf>,
headers: Option<PathBuf>,
scripts: Option<PathBuf>,
data: Option<PathBuf>,
}
impl WheelDataIncludes {
/// Yield all data directories name and corresponding paths.
pub fn iter(&self) -> impl Iterator<Item = (&'static str, &Path)> {
[
("purelib", self.purelib.as_deref()),
("platlib", self.platlib.as_deref()),
("headers", self.headers.as_deref()),
("scripts", self.scripts.as_deref()),
("data", self.data.as_deref()),
]
.into_iter()
.filter_map(|(name, value)| Some((name, value?)))
}
}
| 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-build-backend/src/lib.rs | crates/uv-build-backend/src/lib.rs | use itertools::Itertools;
mod metadata;
mod serde_verbatim;
mod settings;
mod source_dist;
mod wheel;
pub use metadata::{PyProjectToml, check_direct_build};
pub use settings::{BuildBackendSettings, WheelDataIncludes};
pub use source_dist::{build_source_dist, list_source_dist};
use uv_warnings::warn_user_once;
pub use wheel::{build_editable, build_wheel, list_wheel, metadata};
use std::collections::HashSet;
use std::ffi::OsStr;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use thiserror::Error;
use tracing::debug;
use walkdir::DirEntry;
use uv_fs::Simplified;
use uv_globfilter::PortableGlobError;
use uv_normalize::PackageName;
use uv_pypi_types::{Identifier, IdentifierParseError};
use crate::metadata::ValidationError;
use crate::settings::ModuleName;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error("Invalid metadata format in: {}", _0.user_display())]
Toml(PathBuf, #[source] toml::de::Error),
#[error("Invalid project metadata")]
Validation(#[from] ValidationError),
#[error("Invalid module name: {0}")]
InvalidModuleName(String, #[source] IdentifierParseError),
#[error("Unsupported glob expression in: {field}")]
PortableGlob {
field: String,
#[source]
source: PortableGlobError,
},
/// <https://github.com/BurntSushi/ripgrep/discussions/2927>
#[error("Glob expressions caused to large regex in: {field}")]
GlobSetTooLarge {
field: String,
#[source]
source: globset::Error,
},
#[error("`pyproject.toml` must not be excluded from source distribution build")]
PyprojectTomlExcluded,
#[error("Failed to walk source tree: {}", root.user_display())]
WalkDir {
root: PathBuf,
#[source]
err: walkdir::Error,
},
#[error("Failed to write wheel zip archive")]
Zip(#[from] zip::result::ZipError),
#[error("Failed to write RECORD file")]
Csv(#[from] csv::Error),
#[error("Expected a Python module at: {}", _0.user_display())]
MissingInitPy(PathBuf),
#[error("For namespace packages, `__init__.py[i]` is not allowed in parent directory: {}", _0.user_display())]
NotANamespace(PathBuf),
/// Either an absolute path or a parent path through `..`.
#[error("Module root must be inside the project: {}", _0.user_display())]
InvalidModuleRoot(PathBuf),
/// Either an absolute path or a parent path through `..`.
#[error("The path for the data directory {} must be inside the project: {}", name, path.user_display())]
InvalidDataRoot { name: String, path: PathBuf },
#[error("Virtual environments must not be added to source distributions or wheels, remove the directory or exclude it from the build: {}", _0.user_display())]
VenvInSourceTree(PathBuf),
#[error("Inconsistent metadata between prepare and build step: {0}")]
InconsistentSteps(&'static str),
#[error("Failed to write to {}", _0.user_display())]
TarWrite(PathBuf, #[source] io::Error),
}
/// Dispatcher between writing to a directory, writing to a zip, writing to a `.tar.gz` and
/// listing files.
///
/// All paths are string types instead of path types since wheels are portable between platforms.
///
/// Contract: You must call close before dropping to obtain a valid output (dropping is fine in the
/// error case).
trait DirectoryWriter {
/// Add a file with the given content.
///
/// Files added through the method are considered generated when listing included files.
fn write_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error>;
/// Add the file or directory to the path.
fn write_dir_entry(&mut self, entry: &DirEntry, target_path: &str) -> Result<(), Error> {
if entry.file_type().is_dir() {
self.write_directory(target_path)?;
} else {
self.write_file(target_path, entry.path())?;
}
Ok(())
}
/// Add a local file.
fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error>;
/// Create a directory.
fn write_directory(&mut self, directory: &str) -> Result<(), Error>;
/// Write the `RECORD` file and if applicable, the central directory.
fn close(self, dist_info_dir: &str) -> Result<(), Error>;
}
/// Name of the file in the archive and path outside, if it wasn't generated.
pub(crate) type FileList = Vec<(String, Option<PathBuf>)>;
/// A dummy writer to collect the file names that would be included in a build.
pub(crate) struct ListWriter<'a> {
files: &'a mut FileList,
}
impl<'a> ListWriter<'a> {
/// Convert the writer to the collected file names.
pub(crate) fn new(files: &'a mut FileList) -> Self {
Self { files }
}
}
impl DirectoryWriter for ListWriter<'_> {
fn write_bytes(&mut self, path: &str, _bytes: &[u8]) -> Result<(), Error> {
self.files.push((path.to_string(), None));
Ok(())
}
fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error> {
self.files
.push((path.to_string(), Some(file.to_path_buf())));
Ok(())
}
fn write_directory(&mut self, _directory: &str) -> Result<(), Error> {
Ok(())
}
fn close(self, _dist_info_dir: &str) -> Result<(), Error> {
Ok(())
}
}
/// PEP 517 requires that the metadata directory from the prepare metadata call is identical to the
/// build wheel call. This method performs a prudence check that `METADATA` and `entry_points.txt`
/// match.
fn check_metadata_directory(
source_tree: &Path,
metadata_directory: Option<&Path>,
pyproject_toml: &PyProjectToml,
) -> Result<(), Error> {
let Some(metadata_directory) = metadata_directory else {
return Ok(());
};
debug!(
"Checking metadata directory {}",
metadata_directory.user_display()
);
// `METADATA` is a mandatory file.
let current = pyproject_toml
.to_metadata(source_tree)?
.core_metadata_format();
let previous = fs_err::read_to_string(metadata_directory.join("METADATA"))?;
if previous != current {
return Err(Error::InconsistentSteps("METADATA"));
}
// `entry_points.txt` is not written if it would be empty.
let entrypoints_path = metadata_directory.join("entry_points.txt");
match pyproject_toml.to_entry_points()? {
None => {
if entrypoints_path.is_file() {
return Err(Error::InconsistentSteps("entry_points.txt"));
}
}
Some(entrypoints) => {
if fs_err::read_to_string(&entrypoints_path)? != entrypoints {
return Err(Error::InconsistentSteps("entry_points.txt"));
}
}
}
Ok(())
}
/// Returns the list of module names without names which would be included twice
///
/// In normal cases it should do nothing:
///
/// * `["aaa"] -> ["aaa"]`
/// * `["aaa", "bbb"] -> ["aaa", "bbb"]`
///
/// Duplicate elements are removed:
///
/// * `["aaa", "aaa"] -> ["aaa"]`
/// * `["bbb", "aaa", "bbb"] -> ["aaa", "bbb"]`
///
/// Names with more specific paths are removed in favour of more general paths:
///
/// * `["aaa.foo", "aaa"] -> ["aaa"]`
/// * `["bbb", "aaa", "bbb.foo", "ccc.foo", "ccc.foo.bar", "aaa"] -> ["aaa", "bbb.foo", "ccc.foo"]`
///
/// This does not preserve the order of the elements.
fn prune_redundant_modules(mut names: Vec<String>) -> Vec<String> {
names.sort();
let mut pruned = Vec::with_capacity(names.len());
for name in names {
if let Some(last) = pruned.last() {
if name == *last {
continue;
}
// This is a more specific (narrow) module name than what came before
if name
.strip_prefix(last)
.is_some_and(|suffix| suffix.starts_with('.'))
{
continue;
}
}
pruned.push(name);
}
pruned
}
/// Wraps [`prune_redundant_modules`] with a conditional warning when modules are ignored
fn prune_redundant_modules_warn(names: &[String], show_warnings: bool) -> Vec<String> {
let pruned = prune_redundant_modules(names.to_vec());
if show_warnings && names.len() != pruned.len() {
let mut pruned: HashSet<_> = pruned.iter().collect();
let ignored: Vec<_> = names.iter().filter(|name| !pruned.remove(name)).collect();
let s = if ignored.len() == 1 { "" } else { "s" };
warn_user_once!(
"Ignoring redundant module name{s} in `tool.uv.build-backend.module-name`: `{}`",
ignored.into_iter().join("`, `")
);
}
pruned
}
/// Returns the source root and the module path(s) with the `__init__.py[i]` below to it while
/// checking the project layout and names.
///
/// Some target platforms have case-sensitive filesystems, while others have case-insensitive
/// filesystems. We always lower case the package name, our default for the module, while some
/// users want uppercase letters in their module names. For example, the package name is `pil_util`,
/// but the module `PIL_util`. To make the behavior as consistent as possible across platforms as
/// possible, we require that an upper case name is given explicitly through
/// `tool.uv.build-backend.module-name`.
///
/// By default, the dist-info-normalized package name is the module name. For
/// dist-info-normalization, the rules are lowercasing, replacing `.` with `_` and
/// replace `-` with `_`. Since `.` and `-` are not allowed in identifiers, we can use a string
/// comparison with the module name.
///
/// While we recommend one module per package, it is possible to declare a list of modules.
fn find_roots(
source_tree: &Path,
pyproject_toml: &PyProjectToml,
relative_module_root: &Path,
module_name: Option<&ModuleName>,
namespace: bool,
show_warnings: bool,
) -> Result<(PathBuf, Vec<PathBuf>), Error> {
let relative_module_root = uv_fs::normalize_path(relative_module_root);
// Check that even if a path contains `..`, we only include files below the module root.
if !uv_fs::normalize_path(&source_tree.join(&relative_module_root))
.starts_with(uv_fs::normalize_path(source_tree))
{
return Err(Error::InvalidModuleRoot(relative_module_root.to_path_buf()));
}
let src_root = source_tree.join(&relative_module_root);
debug!("Source root: {}", src_root.user_display());
if namespace {
// `namespace = true` disables module structure checks.
let modules_relative = if let Some(module_name) = module_name {
match module_name {
ModuleName::Name(name) => {
vec![name.split('.').collect::<PathBuf>()]
}
ModuleName::Names(names) => prune_redundant_modules_warn(names, show_warnings)
.into_iter()
.map(|name| name.split('.').collect::<PathBuf>())
.collect(),
}
} else {
vec![PathBuf::from(
pyproject_toml.name().as_dist_info_name().to_string(),
)]
};
for module_relative in &modules_relative {
debug!("Namespace module path: {}", module_relative.user_display());
}
return Ok((src_root, modules_relative));
}
let modules_relative = if let Some(module_name) = module_name {
match module_name {
ModuleName::Name(name) => vec![module_path_from_module_name(&src_root, name)?],
ModuleName::Names(names) => prune_redundant_modules_warn(names, show_warnings)
.into_iter()
.map(|name| module_path_from_module_name(&src_root, &name))
.collect::<Result<_, _>>()?,
}
} else {
vec![find_module_path_from_package_name(
&src_root,
pyproject_toml.name(),
)?]
};
for module_relative in &modules_relative {
debug!("Module path: {}", module_relative.user_display());
}
Ok((src_root, modules_relative))
}
/// Infer stubs packages from package name alone.
///
/// There are potential false positives if someone had a regular package with `-stubs`.
/// The `Identifier` checks in `module_path_from_module_name` are here covered by the `PackageName`
/// validation.
fn find_module_path_from_package_name(
src_root: &Path,
package_name: &PackageName,
) -> Result<PathBuf, Error> {
if let Some(stem) = package_name.to_string().strip_suffix("-stubs") {
debug!("Building stubs package instead of a regular package");
let module_name = PackageName::from_str(stem)
.expect("non-empty package name prefix must be valid package name")
.as_dist_info_name()
.to_string();
let module_relative = PathBuf::from(format!("{module_name}-stubs"));
let init_pyi = src_root.join(&module_relative).join("__init__.pyi");
if !init_pyi.is_file() {
return Err(Error::MissingInitPy(init_pyi));
}
Ok(module_relative)
} else {
// This name is always lowercase.
let module_relative = PathBuf::from(package_name.as_dist_info_name().to_string());
let init_py = src_root.join(&module_relative).join("__init__.py");
if !init_py.is_file() {
return Err(Error::MissingInitPy(init_py));
}
Ok(module_relative)
}
}
/// Determine the relative module path from an explicit module name.
fn module_path_from_module_name(src_root: &Path, module_name: &str) -> Result<PathBuf, Error> {
// This name can be uppercase.
let module_relative = module_name.split('.').collect::<PathBuf>();
// Check if we have a regular module or a namespace.
let (root_name, namespace_segments) =
if let Some((root_name, namespace_segments)) = module_name.split_once('.') {
(
root_name,
namespace_segments.split('.').collect::<Vec<&str>>(),
)
} else {
(module_name, Vec::new())
};
// Check if we have an implementation or a stubs package.
// For stubs for a namespace, the `-stubs` prefix must be on the root.
let stubs = if let Some(stem) = root_name.strip_suffix("-stubs") {
// Check that the stubs belong to a valid module.
Identifier::from_str(stem)
.map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
true
} else {
Identifier::from_str(root_name)
.map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
false
};
// For a namespace, check that all names below the root is valid.
for segment in namespace_segments {
Identifier::from_str(segment)
.map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
}
// Check that an `__init__.py[i]` exists for the module.
let init_py =
src_root
.join(&module_relative)
.join(if stubs { "__init__.pyi" } else { "__init__.py" });
if !init_py.is_file() {
return Err(Error::MissingInitPy(init_py));
}
// For a namespace, check that the directories above the lowest are namespace directories.
for namespace_dir in module_relative.ancestors().skip(1) {
if src_root.join(namespace_dir).join("__init__.py").exists()
|| src_root.join(namespace_dir).join("__init__.pyi").exists()
{
return Err(Error::NotANamespace(src_root.join(namespace_dir)));
}
}
Ok(module_relative)
}
/// Error if we're adding a venv to a distribution.
pub(crate) fn error_on_venv(file_name: &OsStr, path: &Path) -> Result<(), Error> {
// On 64-bit Unix, `lib64` is a (compatibility) symlink to lib. If we traverse `lib64` before
// `pyvenv.cfg`, we show a generic error for symlink directories instead.
if !(file_name == "pyvenv.cfg" || file_name == "lib64") {
return Ok(());
}
let Some(parent) = path.parent() else {
return Ok(());
};
if parent.join("bin").join("python").is_symlink()
|| parent.join("Scripts").join("python.exe").is_file()
{
return Err(Error::VenvInSourceTree(parent.to_path_buf()));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use flate2::bufread::GzDecoder;
use fs_err::File;
use indoc::indoc;
use insta::assert_snapshot;
use itertools::Itertools;
use regex::Regex;
use sha2::Digest;
use std::io::{BufReader, Read};
use std::iter;
use tempfile::TempDir;
use uv_distribution_filename::{SourceDistFilename, WheelFilename};
use uv_fs::{copy_dir_all, relative_to};
const MOCK_UV_VERSION: &str = "1.0.0+test";
fn format_err(err: &Error) -> String {
let context = iter::successors(std::error::Error::source(&err), |&err| err.source())
.map(|err| format!(" Caused by: {err}"))
.join("\n");
err.to_string() + "\n" + &context
}
/// File listings, generated archives and archive contents for both a build with
/// source tree -> wheel
/// and a build with
/// source tree -> source dist -> wheel.
#[derive(Debug, PartialEq, Eq)]
struct BuildResults {
source_dist_list_files: FileList,
source_dist_filename: SourceDistFilename,
source_dist_contents: Vec<String>,
wheel_list_files: FileList,
wheel_filename: WheelFilename,
wheel_contents: Vec<String>,
}
/// Run both a direct wheel build and an indirect wheel build through a source distribution,
/// while checking that directly built wheel and indirectly built wheel are the same.
fn build(source_root: &Path, dist: &Path) -> Result<BuildResults, Error> {
// Build a direct wheel, capture all its properties to compare it with the indirect wheel
// latest and remove it since it has the same filename as the indirect wheel.
let (_name, direct_wheel_list_files) = list_wheel(source_root, MOCK_UV_VERSION, false)?;
let direct_wheel_filename = build_wheel(source_root, dist, None, MOCK_UV_VERSION, false)?;
let direct_wheel_path = dist.join(direct_wheel_filename.to_string());
let direct_wheel_contents = wheel_contents(&direct_wheel_path);
let direct_wheel_hash = sha2::Sha256::digest(fs_err::read(&direct_wheel_path)?);
fs_err::remove_file(&direct_wheel_path)?;
// Build a source distribution.
let (_name, source_dist_list_files) =
list_source_dist(source_root, MOCK_UV_VERSION, false)?;
// TODO(konsti): This should run in the unpacked source dist tempdir, but we need to
// normalize the path.
let (_name, wheel_list_files) = list_wheel(source_root, MOCK_UV_VERSION, false)?;
let source_dist_filename = build_source_dist(source_root, dist, MOCK_UV_VERSION, false)?;
let source_dist_path = dist.join(source_dist_filename.to_string());
let source_dist_contents = sdist_contents(&source_dist_path);
// Unpack the source distribution and build a wheel from it.
let sdist_tree = TempDir::new()?;
let sdist_reader = BufReader::new(File::open(&source_dist_path)?);
let mut source_dist = tar::Archive::new(GzDecoder::new(sdist_reader));
source_dist.unpack(sdist_tree.path())?;
let sdist_top_level_directory = sdist_tree.path().join(format!(
"{}-{}",
source_dist_filename.name.as_dist_info_name(),
source_dist_filename.version
));
let wheel_filename = build_wheel(
&sdist_top_level_directory,
dist,
None,
MOCK_UV_VERSION,
false,
)?;
let wheel_contents = wheel_contents(&dist.join(wheel_filename.to_string()));
// Check that direct and indirect wheels are identical.
assert_eq!(direct_wheel_filename, wheel_filename);
assert_eq!(direct_wheel_contents, wheel_contents);
assert_eq!(direct_wheel_list_files, wheel_list_files);
assert_eq!(
direct_wheel_hash,
sha2::Sha256::digest(fs_err::read(dist.join(wheel_filename.to_string()))?)
);
Ok(BuildResults {
source_dist_list_files,
source_dist_filename,
source_dist_contents,
wheel_list_files,
wheel_filename,
wheel_contents,
})
}
fn build_err(source_root: &Path) -> String {
let dist = TempDir::new().unwrap();
let build_err = build(source_root, dist.path()).unwrap_err();
let err_message: String = format_err(&build_err)
.replace(&source_root.user_display().to_string(), "[TEMP_PATH]")
.replace('\\', "/");
err_message
}
fn sdist_contents(source_dist_path: &Path) -> Vec<String> {
let sdist_reader = BufReader::new(File::open(source_dist_path).unwrap());
let mut source_dist = tar::Archive::new(GzDecoder::new(sdist_reader));
let mut source_dist_contents: Vec<_> = source_dist
.entries()
.unwrap()
.map(|entry| {
entry
.unwrap()
.path()
.unwrap()
.to_str()
.unwrap()
.replace('\\', "/")
})
.collect();
source_dist_contents.sort();
source_dist_contents
}
fn wheel_contents(direct_output_dir: &Path) -> Vec<String> {
let wheel = zip::ZipArchive::new(File::open(direct_output_dir).unwrap()).unwrap();
let mut wheel_contents: Vec<_> = wheel
.file_names()
.map(|path| path.replace('\\', "/"))
.collect();
wheel_contents.sort_unstable();
wheel_contents
}
fn format_file_list(file_list: FileList, src: &Path) -> String {
file_list
.into_iter()
.map(|(path, source)| {
let path = path.replace('\\', "/");
if let Some(source) = source {
let source = relative_to(source, src)
.unwrap()
.portable_display()
.to_string();
format!("{path} ({source})")
} else {
format!("{path} (generated)")
}
})
.join("\n")
}
/// Tests that builds are stable and include the right files and.
///
/// Tests that both source tree -> source dist -> wheel and source tree -> wheel include the
/// right files. Also checks that the resulting archives are byte-by-byte identical
/// independent of the build path or platform, with the caveat that we cannot serialize an
/// executable bit on Window. This ensures reproducible builds and best-effort
/// platform-independent deterministic builds.
#[test]
fn built_by_uv_building() {
let built_by_uv = Path::new("../../test/packages/built-by-uv");
let src = TempDir::new().unwrap();
for dir in [
"src",
"tests",
"data-dir",
"third-party-licenses",
"assets",
"header",
"scripts",
] {
copy_dir_all(built_by_uv.join(dir), src.path().join(dir)).unwrap();
}
for filename in [
"pyproject.toml",
"README.md",
"uv.lock",
"LICENSE-APACHE",
"LICENSE-MIT",
] {
fs_err::copy(built_by_uv.join(filename), src.path().join(filename)).unwrap();
}
// Clear executable bit on Unix to build the same archive between Unix and Windows.
// This is a caveat to the determinism of the uv build backend: When a file has the
// executable in the source repository, it only has the executable bit on Unix, as Windows
// does not have the concept of the executable bit.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let path = src.path().join("scripts").join("whoami.sh");
let metadata = fs_err::metadata(&path).unwrap();
let mut perms = metadata.permissions();
perms.set_mode(perms.mode() & !0o111);
fs_err::set_permissions(&path, perms).unwrap();
}
// Redact the uv_build version to keep the hash stable across releases
let pyproject_toml = fs_err::read_to_string(src.path().join("pyproject.toml")).unwrap();
let current_requires =
Regex::new(r#"requires = \["uv_build>=[0-9.]+,<[0-9.]+"\]"#).unwrap();
let mocked_requires = r#"requires = ["uv_build>=1,<2"]"#;
let pyproject_toml = current_requires.replace(pyproject_toml.as_str(), mocked_requires);
fs_err::write(src.path().join("pyproject.toml"), pyproject_toml.as_bytes()).unwrap();
// Add some files to be excluded
let module_root = src.path().join("src").join("built_by_uv");
fs_err::create_dir_all(module_root.join("__pycache__")).unwrap();
File::create(module_root.join("__pycache__").join("compiled.pyc")).unwrap();
File::create(module_root.join("arithmetic").join("circle.pyc")).unwrap();
// Perform both the direct and the indirect build.
let dist = TempDir::new().unwrap();
let build = build(src.path(), dist.path()).unwrap();
let source_dist_path = dist.path().join(build.source_dist_filename.to_string());
assert_eq!(
build.source_dist_filename.to_string(),
"built_by_uv-0.1.0.tar.gz"
);
// Check that the source dist is reproducible across platforms.
assert_snapshot!(
format!("{:x}", sha2::Sha256::digest(fs_err::read(&source_dist_path).unwrap())),
@"bb74bff575b135bb39e5c9bce56349441fb0923bb8857e32a5eaf34ec1843967"
);
// Check both the files we report and the actual files
assert_snapshot!(format_file_list(build.source_dist_list_files, src.path()), @r"
built_by_uv-0.1.0/PKG-INFO (generated)
built_by_uv-0.1.0/LICENSE-APACHE (LICENSE-APACHE)
built_by_uv-0.1.0/LICENSE-MIT (LICENSE-MIT)
built_by_uv-0.1.0/README.md (README.md)
built_by_uv-0.1.0/assets/data.csv (assets/data.csv)
built_by_uv-0.1.0/header/built_by_uv.h (header/built_by_uv.h)
built_by_uv-0.1.0/pyproject.toml (pyproject.toml)
built_by_uv-0.1.0/scripts/whoami.sh (scripts/whoami.sh)
built_by_uv-0.1.0/src/built_by_uv/__init__.py (src/built_by_uv/__init__.py)
built_by_uv-0.1.0/src/built_by_uv/arithmetic/__init__.py (src/built_by_uv/arithmetic/__init__.py)
built_by_uv-0.1.0/src/built_by_uv/arithmetic/circle.py (src/built_by_uv/arithmetic/circle.py)
built_by_uv-0.1.0/src/built_by_uv/arithmetic/pi.txt (src/built_by_uv/arithmetic/pi.txt)
built_by_uv-0.1.0/src/built_by_uv/build-only.h (src/built_by_uv/build-only.h)
built_by_uv-0.1.0/src/built_by_uv/cli.py (src/built_by_uv/cli.py)
built_by_uv-0.1.0/third-party-licenses/PEP-401.txt (third-party-licenses/PEP-401.txt)
");
assert_snapshot!(build.source_dist_contents.iter().join("\n"), @r"
built_by_uv-0.1.0/
built_by_uv-0.1.0/LICENSE-APACHE
built_by_uv-0.1.0/LICENSE-MIT
built_by_uv-0.1.0/PKG-INFO
built_by_uv-0.1.0/README.md
built_by_uv-0.1.0/assets
built_by_uv-0.1.0/assets/data.csv
built_by_uv-0.1.0/header
built_by_uv-0.1.0/header/built_by_uv.h
built_by_uv-0.1.0/pyproject.toml
built_by_uv-0.1.0/scripts
built_by_uv-0.1.0/scripts/whoami.sh
built_by_uv-0.1.0/src
built_by_uv-0.1.0/src/built_by_uv
built_by_uv-0.1.0/src/built_by_uv/__init__.py
built_by_uv-0.1.0/src/built_by_uv/arithmetic
built_by_uv-0.1.0/src/built_by_uv/arithmetic/__init__.py
built_by_uv-0.1.0/src/built_by_uv/arithmetic/circle.py
built_by_uv-0.1.0/src/built_by_uv/arithmetic/pi.txt
built_by_uv-0.1.0/src/built_by_uv/build-only.h
built_by_uv-0.1.0/src/built_by_uv/cli.py
built_by_uv-0.1.0/third-party-licenses
built_by_uv-0.1.0/third-party-licenses/PEP-401.txt
");
let wheel_path = dist.path().join(build.wheel_filename.to_string());
assert_eq!(
build.wheel_filename.to_string(),
"built_by_uv-0.1.0-py3-none-any.whl"
);
// Check that the wheel is reproducible across platforms.
assert_snapshot!(
format!("{:x}", sha2::Sha256::digest(fs_err::read(&wheel_path).unwrap())),
@"319afb04e87caf894b1362b508ec745253c6d241423ea59021694d2015e821da"
);
assert_snapshot!(build.wheel_contents.join("\n"), @r"
built_by_uv-0.1.0.data/data/
built_by_uv-0.1.0.data/data/data.csv
built_by_uv-0.1.0.data/headers/
built_by_uv-0.1.0.data/headers/built_by_uv.h
built_by_uv-0.1.0.data/scripts/
built_by_uv-0.1.0.data/scripts/whoami.sh
built_by_uv-0.1.0.dist-info/
built_by_uv-0.1.0.dist-info/METADATA
built_by_uv-0.1.0.dist-info/RECORD
built_by_uv-0.1.0.dist-info/WHEEL
built_by_uv-0.1.0.dist-info/entry_points.txt
built_by_uv-0.1.0.dist-info/licenses/
built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE
built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT
built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/
built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt
built_by_uv/
built_by_uv/__init__.py
built_by_uv/arithmetic/
built_by_uv/arithmetic/__init__.py
built_by_uv/arithmetic/circle.py
built_by_uv/arithmetic/pi.txt
built_by_uv/cli.py
");
assert_snapshot!(format_file_list(build.wheel_list_files, src.path()), @r"
built_by_uv/__init__.py (src/built_by_uv/__init__.py)
built_by_uv/arithmetic/__init__.py (src/built_by_uv/arithmetic/__init__.py)
built_by_uv/arithmetic/circle.py (src/built_by_uv/arithmetic/circle.py)
built_by_uv/arithmetic/pi.txt (src/built_by_uv/arithmetic/pi.txt)
built_by_uv/cli.py (src/built_by_uv/cli.py)
built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE (LICENSE-APACHE)
built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT (LICENSE-MIT)
built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt (third-party-licenses/PEP-401.txt)
built_by_uv-0.1.0.data/headers/built_by_uv.h (header/built_by_uv.h)
built_by_uv-0.1.0.data/scripts/whoami.sh (scripts/whoami.sh)
built_by_uv-0.1.0.data/data/data.csv (assets/data.csv)
built_by_uv-0.1.0.dist-info/WHEEL (generated)
built_by_uv-0.1.0.dist-info/entry_points.txt (generated)
built_by_uv-0.1.0.dist-info/METADATA (generated)
");
let mut wheel = zip::ZipArchive::new(File::open(wheel_path).unwrap()).unwrap();
let mut record = String::new();
wheel
.by_name("built_by_uv-0.1.0.dist-info/RECORD")
.unwrap()
.read_to_string(&mut record)
.unwrap();
assert_snapshot!(record, @r###"
built_by_uv/__init__.py,sha256=AJ7XpTNWxYktP97ydb81UpnNqoebH7K4sHRakAMQKG4,44
built_by_uv/arithmetic/__init__.py,sha256=x2agwFbJAafc9Z6TdJ0K6b6bLMApQdvRSQjP4iy7IEI,67
built_by_uv/arithmetic/circle.py,sha256=FYZkv6KwrF9nJcwGOKigjke1dm1Fkie7qW1lWJoh3AE,287
built_by_uv/arithmetic/pi.txt,sha256=-4HqoLoIrSKGf0JdTrM8BTTiIz8rq-MSCDL6LeF0iuU,8
built_by_uv/cli.py,sha256=Jcm3PxSb8wTAN3dGm5vKEDQwCgoUXkoeggZeF34QyKM,44
built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT,sha256=F5Z0Cpu8QWyblXwXhrSo0b9WmYXQxd1LwLjVLJZwbiI,1077
built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt,sha256=KN-KAx829G2saLjVmByc08RFFtIDWvHulqPyD0qEBZI,270
built_by_uv-0.1.0.data/headers/built_by_uv.h,sha256=p5-HBunJ1dY-xd4dMn03PnRClmGyRosScIp8rT46kg4,144
built_by_uv-0.1.0.data/scripts/whoami.sh,sha256=T2cmhuDFuX-dTkiSkuAmNyIzvv8AKopjnuTCcr9o-eE,20
built_by_uv-0.1.0.data/data/data.csv,sha256=7z7u-wXu7Qr2eBZFVpBILlNUiGSngv_1vYqZHVWOU94,265
built_by_uv-0.1.0.dist-info/WHEEL,sha256=PaG_oOj9G2zCRqoLK0SjWBVZbGAMtIXDmm-MEGw9Wo0,83
built_by_uv-0.1.0.dist-info/entry_points.txt,sha256=-IO6yaq6x6HSl-zWH96rZmgYvfyHlH00L5WQoCpz-YI,50
| 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-build-backend/src/source_dist.rs | crates/uv-build-backend/src/source_dist.rs | use crate::metadata::DEFAULT_EXCLUDES;
use crate::wheel::build_exclude_matcher;
use crate::{
BuildBackendSettings, DirectoryWriter, Error, FileList, ListWriter, PyProjectToml,
error_on_venv, find_roots,
};
use flate2::Compression;
use flate2::write::GzEncoder;
use fs_err::File;
use globset::{Glob, GlobSet};
use std::io;
use std::io::{BufReader, Cursor};
use std::path::{Component, Path, PathBuf};
use tar::{EntryType, Header};
use tracing::{debug, trace};
use uv_distribution_filename::{SourceDistExtension, SourceDistFilename};
use uv_fs::Simplified;
use uv_globfilter::{GlobDirFilter, PortableGlobParser};
use uv_warnings::warn_user_once;
use walkdir::WalkDir;
/// Build a source distribution from the source tree and place it in the output directory.
pub fn build_source_dist(
source_tree: &Path,
source_dist_directory: &Path,
uv_version: &str,
show_warnings: bool,
) -> Result<SourceDistFilename, Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
let filename = SourceDistFilename {
name: pyproject_toml.name().clone(),
version: pyproject_toml.version().clone(),
extension: SourceDistExtension::TarGz,
};
let source_dist_path = source_dist_directory.join(filename.to_string());
let writer = TarGzWriter::new(&source_dist_path)?;
write_source_dist(source_tree, writer, uv_version, show_warnings)?;
Ok(filename)
}
/// List the files that would be included in a source distribution and their origin.
pub fn list_source_dist(
source_tree: &Path,
uv_version: &str,
show_warnings: bool,
) -> Result<(SourceDistFilename, FileList), Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
let filename = SourceDistFilename {
name: pyproject_toml.name().clone(),
version: pyproject_toml.version().clone(),
extension: SourceDistExtension::TarGz,
};
let mut files = FileList::new();
let writer = ListWriter::new(&mut files);
write_source_dist(source_tree, writer, uv_version, show_warnings)?;
Ok((filename, files))
}
/// Build includes and excludes for source tree walking for source dists.
fn source_dist_matcher(
source_tree: &Path,
pyproject_toml: &PyProjectToml,
settings: BuildBackendSettings,
show_warnings: bool,
) -> Result<(GlobDirFilter, GlobSet), Error> {
// File and directories to include in the source directory
let mut include_globs = Vec::new();
let mut includes: Vec<String> = settings.source_include;
// pyproject.toml is always included.
includes.push(globset::escape("pyproject.toml"));
// Check that the source tree contains a module.
let (src_root, modules_relative) = find_roots(
source_tree,
pyproject_toml,
&settings.module_root,
settings.module_name.as_ref(),
settings.namespace,
show_warnings,
)?;
for module_relative in modules_relative {
// The wheel must not include any files included by the source distribution (at least until we
// have files generated in the source dist -> wheel build step).
let import_path = uv_fs::normalize_path(
&uv_fs::relative_to(src_root.join(module_relative), source_tree)
.expect("module root is inside source tree"),
)
.portable_display()
.to_string();
includes.push(format!("{}/**", globset::escape(&import_path)));
}
for include in includes {
let glob = PortableGlobParser::Uv
.parse(&include)
.map_err(|err| Error::PortableGlob {
field: "tool.uv.build-backend.source-include".to_string(),
source: err,
})?;
include_globs.push(glob);
}
// Include the Readme
if let Some(readme) = pyproject_toml
.readme()
.as_ref()
.and_then(|readme| readme.path())
{
let readme = uv_fs::normalize_path(readme);
trace!("Including readme at: {}", readme.user_display());
let readme = readme.portable_display().to_string();
let glob = Glob::new(&globset::escape(&readme)).expect("escaped globset is parseable");
include_globs.push(glob);
}
// Include the license files
for license_files in pyproject_toml.license_files_source_dist() {
trace!("Including license files at: {license_files}`");
let glob = PortableGlobParser::Pep639
.parse(license_files)
.map_err(|err| Error::PortableGlob {
field: "project.license-files".to_string(),
source: err,
})?;
include_globs.push(glob);
}
// Include the data files
for (name, directory) in settings.data.iter() {
let directory = uv_fs::normalize_path(directory);
trace!("Including data ({}) at: {}", name, directory.user_display());
if directory
.components()
.next()
.is_some_and(|component| !matches!(component, Component::CurDir | Component::Normal(_)))
{
return Err(Error::InvalidDataRoot {
name: name.to_string(),
path: directory.to_path_buf(),
});
}
let directory = directory.portable_display().to_string();
let glob = PortableGlobParser::Uv
.parse(&format!("{}/**", globset::escape(&directory)))
.map_err(|err| Error::PortableGlob {
field: format!("tool.uv.build-backend.data.{name}"),
source: err,
})?;
include_globs.push(glob);
}
debug!(
"Source distribution includes: {:?}",
include_globs
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
);
let include_matcher =
GlobDirFilter::from_globs(&include_globs).map_err(|err| Error::GlobSetTooLarge {
field: "tool.uv.build-backend.source-include".to_string(),
source: err,
})?;
let mut excludes: Vec<String> = Vec::new();
if settings.default_excludes {
excludes.extend(DEFAULT_EXCLUDES.iter().map(ToString::to_string));
}
for exclude in settings.source_exclude {
// Avoid duplicate entries.
if !excludes.contains(&exclude) {
excludes.push(exclude);
}
}
debug!("Source dist excludes: {:?}", excludes);
let exclude_matcher = build_exclude_matcher(excludes)?;
if exclude_matcher.is_match("pyproject.toml") {
return Err(Error::PyprojectTomlExcluded);
}
Ok((include_matcher, exclude_matcher))
}
/// Shared implementation for building and listing a source distribution.
fn write_source_dist(
source_tree: &Path,
mut writer: impl DirectoryWriter,
uv_version: &str,
show_warnings: bool,
) -> Result<SourceDistFilename, Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
for warning in pyproject_toml.check_build_system(uv_version) {
warn_user_once!("{warning}");
}
let settings = pyproject_toml
.settings()
.cloned()
.unwrap_or_else(BuildBackendSettings::default);
let filename = SourceDistFilename {
name: pyproject_toml.name().clone(),
version: pyproject_toml.version().clone(),
extension: SourceDistExtension::TarGz,
};
let top_level = format!(
"{}-{}",
pyproject_toml.name().as_dist_info_name(),
pyproject_toml.version()
);
let metadata = pyproject_toml.to_metadata(source_tree)?;
let metadata_email = metadata.core_metadata_format();
debug!("Adding content files to source distribution");
writer.write_bytes(
&Path::new(&top_level)
.join("PKG-INFO")
.portable_display()
.to_string(),
metadata_email.as_bytes(),
)?;
let (include_matcher, exclude_matcher) =
source_dist_matcher(source_tree, &pyproject_toml, settings, show_warnings)?;
let mut files_visited = 0;
for entry in WalkDir::new(source_tree)
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| {
// TODO(konsti): This should be prettier.
let relative = entry
.path()
.strip_prefix(source_tree)
.expect("walkdir starts with root");
// Fast path: Don't descend into a directory that can't be included. This is the most
// important performance optimization, it avoids descending into directories such as
// `.venv`. While walkdir is generally cheap, we still avoid traversing large data
// directories that often exist on the top level of a project. This is especially noticeable
// on network file systems with high latencies per operation (while contiguous reading may
// still be fast).
include_matcher.match_directory(relative) && !exclude_matcher.is_match(relative)
})
{
let entry = entry.map_err(|err| Error::WalkDir {
root: source_tree.to_path_buf(),
err,
})?;
files_visited += 1;
if files_visited > 10000 {
warn_user_once!(
"Visited more than 10,000 files for source distribution build. \
Consider using more constrained includes or more excludes."
);
}
// TODO(konsti): This should be prettier.
let relative = entry
.path()
.strip_prefix(source_tree)
.expect("walkdir starts with root");
if !include_matcher.match_path(relative) || exclude_matcher.is_match(relative) {
trace!("Excluding from sdist: {}", relative.user_display());
continue;
}
error_on_venv(entry.file_name(), entry.path())?;
let entry_path = Path::new(&top_level)
.join(relative)
.portable_display()
.to_string();
debug!("Adding to sdist: {}", relative.user_display());
writer.write_dir_entry(&entry, &entry_path)?;
}
debug!("Visited {files_visited} files for source dist build");
writer.close(&top_level)?;
Ok(filename)
}
struct TarGzWriter {
path: PathBuf,
tar: tar::Builder<GzEncoder<File>>,
}
impl TarGzWriter {
fn new(path: impl Into<PathBuf>) -> Result<Self, Error> {
let path = path.into();
let file = File::create(&path)?;
let enc = GzEncoder::new(file, Compression::default());
let tar = tar::Builder::new(enc);
Ok(Self { path, tar })
}
}
impl DirectoryWriter for TarGzWriter {
fn write_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
let mut header = Header::new_gnu();
// Work around bug in Python's std tar module
// https://github.com/python/cpython/issues/141707
// https://github.com/astral-sh/uv/pull/17043#issuecomment-3636841022
header.set_entry_type(EntryType::Regular);
header.set_size(bytes.len() as u64);
// Reasonable default to avoid 0o000 permissions, the user's umask will be applied on
// unpacking.
header.set_mode(0o644);
self.tar
.append_data(&mut header, path, Cursor::new(bytes))
.map_err(|err| Error::TarWrite(self.path.clone(), err))?;
Ok(())
}
fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error> {
let metadata = fs_err::metadata(file)?;
let mut header = Header::new_gnu();
// Work around bug in Python's std tar module
// https://github.com/python/cpython/issues/141707
// https://github.com/astral-sh/uv/pull/17043#issuecomment-3636841022
header.set_entry_type(EntryType::Regular);
// Preserve the executable bit, especially for scripts
#[cfg(unix)]
let executable_bit = {
use std::os::unix::fs::PermissionsExt;
file.metadata()?.permissions().mode() & 0o111 != 0
};
// Windows has no executable bit
#[cfg(not(unix))]
let executable_bit = false;
// Set reasonable defaults to avoid 0o000 permissions, while avoiding adding the exact
// filesystem permissions to the archive for reproducibility. Where applicable, the
// operating system filters the stored permission by the user's umask when unpacking.
if executable_bit {
header.set_mode(0o755);
} else {
header.set_mode(0o644);
}
header.set_size(metadata.len());
let reader = BufReader::new(File::open(file)?);
self.tar
.append_data(&mut header, path, reader)
.map_err(|err| Error::TarWrite(self.path.clone(), err))?;
Ok(())
}
fn write_directory(&mut self, directory: &str) -> Result<(), Error> {
let mut header = Header::new_gnu();
// Directories are always executable, which means they can be listed.
header.set_mode(0o755);
header.set_entry_type(EntryType::Directory);
header.set_size(0);
self.tar
.append_data(&mut header, directory, io::empty())
.map_err(|err| Error::TarWrite(self.path.clone(), err))?;
Ok(())
}
fn close(mut self, _dist_info_dir: &str) -> Result<(), Error> {
self.tar
.finish()
.map_err(|err| Error::TarWrite(self.path.clone(), err))?;
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-build-backend/src/wheel.rs | crates/uv-build-backend/src/wheel.rs | use base64::{Engine, prelude::BASE64_URL_SAFE_NO_PAD as base64};
use fs_err::File;
use globset::{GlobSet, GlobSetBuilder};
use itertools::Itertools;
use rustc_hash::FxHashSet;
use sha2::{Digest, Sha256};
use std::io::{BufReader, Read, Write};
use std::path::{Component, Path, PathBuf};
use std::{io, mem};
use tracing::{debug, trace};
use walkdir::WalkDir;
use zip::{CompressionMethod, ZipWriter};
use uv_distribution_filename::WheelFilename;
use uv_fs::Simplified;
use uv_globfilter::{GlobDirFilter, PortableGlobParser};
use uv_platform_tags::{AbiTag, LanguageTag, PlatformTag};
use uv_warnings::warn_user_once;
use crate::metadata::DEFAULT_EXCLUDES;
use crate::{
BuildBackendSettings, DirectoryWriter, Error, FileList, ListWriter, PyProjectToml,
error_on_venv, find_roots,
};
/// Build a wheel from the source tree and place it in the output directory.
pub fn build_wheel(
source_tree: &Path,
wheel_dir: &Path,
metadata_directory: Option<&Path>,
uv_version: &str,
show_warnings: bool,
) -> Result<WheelFilename, Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
for warning in pyproject_toml.check_build_system(uv_version) {
warn_user_once!("{warning}");
}
crate::check_metadata_directory(source_tree, metadata_directory, &pyproject_toml)?;
let filename = WheelFilename::new(
pyproject_toml.name().clone(),
pyproject_toml.version().clone(),
LanguageTag::Python {
major: 3,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
);
let wheel_path = wheel_dir.join(filename.to_string());
debug!("Writing wheel at {}", wheel_path.user_display());
let wheel_writer = ZipDirectoryWriter::new_wheel(File::create(&wheel_path)?);
write_wheel(
source_tree,
&pyproject_toml,
&filename,
uv_version,
wheel_writer,
show_warnings,
)?;
Ok(filename)
}
/// List the files that would be included in a source distribution and their origin.
pub fn list_wheel(
source_tree: &Path,
uv_version: &str,
show_warnings: bool,
) -> Result<(WheelFilename, FileList), Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
for warning in pyproject_toml.check_build_system(uv_version) {
warn_user_once!("{warning}");
}
let filename = WheelFilename::new(
pyproject_toml.name().clone(),
pyproject_toml.version().clone(),
LanguageTag::Python {
major: 3,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
);
let mut files = FileList::new();
let writer = ListWriter::new(&mut files);
write_wheel(
source_tree,
&pyproject_toml,
&filename,
uv_version,
writer,
show_warnings,
)?;
Ok((filename, files))
}
fn write_wheel(
source_tree: &Path,
pyproject_toml: &PyProjectToml,
filename: &WheelFilename,
uv_version: &str,
mut wheel_writer: impl DirectoryWriter,
show_warnings: bool,
) -> Result<(), Error> {
let settings = pyproject_toml
.settings()
.cloned()
.unwrap_or_else(BuildBackendSettings::default);
// Wheel excludes
let mut excludes: Vec<String> = Vec::new();
if settings.default_excludes {
excludes.extend(DEFAULT_EXCLUDES.iter().map(ToString::to_string));
}
for exclude in settings.wheel_exclude {
// Avoid duplicate entries.
if !excludes.contains(&exclude) {
excludes.push(exclude);
}
}
// The wheel must not include any files excluded by the source distribution (at least until we
// have files generated in the source dist -> wheel build step).
for exclude in &settings.source_exclude {
// Avoid duplicate entries.
if !excludes.contains(exclude) {
excludes.push(exclude.clone());
}
}
debug!("Wheel excludes: {:?}", excludes);
let exclude_matcher = build_exclude_matcher(excludes)?;
debug!("Adding content files to wheel");
let (src_root, module_relative) = find_roots(
source_tree,
pyproject_toml,
&settings.module_root,
settings.module_name.as_ref(),
settings.namespace,
show_warnings,
)?;
let mut files_visited = 0;
let mut prefix_directories = FxHashSet::default();
for module_relative in module_relative {
// For convenience, have directories for the whole tree in the wheel
for ancestor in module_relative.ancestors().skip(1) {
if ancestor == Path::new("") {
continue;
}
// Avoid duplicate directories in the zip.
if prefix_directories.insert(ancestor.to_path_buf()) {
wheel_writer.write_directory(&ancestor.portable_display().to_string())?;
}
}
for entry in WalkDir::new(src_root.join(module_relative))
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| !exclude_matcher.is_match(entry.path()))
{
let entry = entry.map_err(|err| Error::WalkDir {
root: source_tree.to_path_buf(),
err,
})?;
files_visited += 1;
if files_visited > 10000 {
warn_user_once!(
"Visited more than 10,000 files for wheel build. \
Consider using more constrained includes or more excludes."
);
}
// We only want to take the module root, but since excludes start at the source tree root,
// we strip higher than we iterate.
let match_path = entry
.path()
.strip_prefix(source_tree)
.expect("walkdir starts with root");
let entry_path = entry
.path()
.strip_prefix(&src_root)
.expect("walkdir starts with root");
if exclude_matcher.is_match(match_path) {
trace!("Excluding from module: {}", match_path.user_display());
continue;
}
error_on_venv(entry.file_name(), entry.path())?;
let entry_path = entry_path.portable_display().to_string();
debug!("Adding to wheel: {entry_path}");
wheel_writer.write_dir_entry(&entry, &entry_path)?;
}
}
debug!("Visited {files_visited} files for wheel build");
// Add the license files
if pyproject_toml.license_files_wheel().next().is_some() {
debug!("Adding license files");
let license_dir = format!(
"{}-{}.dist-info/licenses/",
pyproject_toml.name().as_dist_info_name(),
pyproject_toml.version()
);
wheel_subdir_from_globs(
source_tree,
&license_dir,
pyproject_toml.license_files_wheel(),
&mut wheel_writer,
"project.license-files",
)?;
}
// Add the data files
for (name, directory) in settings.data.iter() {
debug!(
"Adding {name} data files from: {}",
directory.user_display()
);
if directory
.components()
.next()
.is_some_and(|component| !matches!(component, Component::CurDir | Component::Normal(_)))
{
return Err(Error::InvalidDataRoot {
name: name.to_string(),
path: directory.to_path_buf(),
});
}
let data_dir = format!(
"{}-{}.data/{}/",
pyproject_toml.name().as_dist_info_name(),
pyproject_toml.version(),
name
);
wheel_subdir_from_globs(
&source_tree.join(directory),
&data_dir,
&["**".to_string()],
&mut wheel_writer,
&format!("tool.uv.build-backend.data.{name}"),
)?;
}
debug!("Adding metadata files to wheel");
let dist_info_dir = write_dist_info(
&mut wheel_writer,
pyproject_toml,
filename,
source_tree,
uv_version,
)?;
wheel_writer.close(&dist_info_dir)?;
Ok(())
}
/// Build a wheel from the source tree and place it in the output directory.
pub fn build_editable(
source_tree: &Path,
wheel_dir: &Path,
metadata_directory: Option<&Path>,
uv_version: &str,
show_warnings: bool,
) -> Result<WheelFilename, Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
for warning in pyproject_toml.check_build_system(uv_version) {
warn_user_once!("{warning}");
}
let settings = pyproject_toml
.settings()
.cloned()
.unwrap_or_else(BuildBackendSettings::default);
crate::check_metadata_directory(source_tree, metadata_directory, &pyproject_toml)?;
let filename = WheelFilename::new(
pyproject_toml.name().clone(),
pyproject_toml.version().clone(),
LanguageTag::Python {
major: 3,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
);
let wheel_path = wheel_dir.join(filename.to_string());
debug!("Writing wheel at {}", wheel_path.user_display());
let mut wheel_writer = ZipDirectoryWriter::new_wheel(File::create(&wheel_path)?);
debug!("Adding pth file to {}", wheel_path.user_display());
// Check that a module root exists in the directory we're linking from the `.pth` file
let (src_root, _module_relative) = find_roots(
source_tree,
&pyproject_toml,
&settings.module_root,
settings.module_name.as_ref(),
settings.namespace,
show_warnings,
)?;
wheel_writer.write_bytes(
&format!("{}.pth", pyproject_toml.name().as_dist_info_name()),
src_root.as_os_str().as_encoded_bytes(),
)?;
debug!("Adding metadata files to: {}", wheel_path.user_display());
let dist_info_dir = write_dist_info(
&mut wheel_writer,
&pyproject_toml,
&filename,
source_tree,
uv_version,
)?;
wheel_writer.close(&dist_info_dir)?;
Ok(filename)
}
/// Write the dist-info directory to the output directory without building the wheel.
pub fn metadata(
source_tree: &Path,
metadata_directory: &Path,
uv_version: &str,
) -> Result<String, Error> {
let pyproject_toml = PyProjectToml::parse(&source_tree.join("pyproject.toml"))?;
for warning in pyproject_toml.check_build_system(uv_version) {
warn_user_once!("{warning}");
}
let filename = WheelFilename::new(
pyproject_toml.name().clone(),
pyproject_toml.version().clone(),
LanguageTag::Python {
major: 3,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
);
debug!(
"Writing metadata files to {}",
metadata_directory.user_display()
);
let mut wheel_writer = FilesystemWriter::new(metadata_directory);
let dist_info_dir = write_dist_info(
&mut wheel_writer,
&pyproject_toml,
&filename,
source_tree,
uv_version,
)?;
wheel_writer.close(&dist_info_dir)?;
Ok(dist_info_dir)
}
/// An entry in the `RECORD` file.
///
/// <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-record-file>
struct RecordEntry {
/// The path to the file relative to the package root.
///
/// While the spec would allow backslashes, we always use portable paths with forward slashes.
path: String,
/// The urlsafe-base64-nopad encoded SHA256 of the files.
hash: String,
/// The size of the file in bytes.
size: usize,
}
/// Read the input file and write it both to the hasher and the target file.
///
/// We're implementing this tee-ing manually since there is no sync `InspectReader` or std tee
/// function.
fn write_hashed(
path: &str,
reader: &mut dyn Read,
writer: &mut dyn Write,
) -> Result<RecordEntry, io::Error> {
let mut hasher = Sha256::new();
let mut size = 0;
// 8KB is the default defined in `std::sys_common::io`.
let mut buffer = vec![0; 8 * 1024];
loop {
let read = match reader.read(&mut buffer) {
Ok(read) => read,
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
};
if read == 0 {
// End of file
break;
}
hasher.update(&buffer[..read]);
writer.write_all(&buffer[..read])?;
size += read;
}
Ok(RecordEntry {
path: path.to_string(),
hash: base64.encode(hasher.finalize()),
size,
})
}
/// Write the `RECORD` file.
///
/// <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-record-file>
fn write_record(
writer: &mut dyn Write,
dist_info_dir: &str,
record: Vec<RecordEntry>,
) -> Result<(), Error> {
let mut record_writer = csv::Writer::from_writer(writer);
for entry in record {
record_writer.write_record(&[
entry.path,
format!("sha256={}", entry.hash),
entry.size.to_string(),
])?;
}
// We can't compute the hash or size for RECORD without modifying it at the same time.
record_writer.write_record(&[
format!("{dist_info_dir}/RECORD"),
String::new(),
String::new(),
])?;
record_writer.flush()?;
Ok(())
}
/// Build a globset matcher for excludes.
pub(crate) fn build_exclude_matcher(
excludes: impl IntoIterator<Item = impl AsRef<str>>,
) -> Result<GlobSet, Error> {
let mut exclude_builder = GlobSetBuilder::new();
for exclude in excludes {
let exclude = exclude.as_ref();
// Excludes are unanchored
let exclude = if let Some(exclude) = exclude.strip_prefix("/") {
exclude.to_string()
} else {
format!("**/{exclude}").to_string()
};
let glob = PortableGlobParser::Uv
.parse(&exclude)
.map_err(|err| Error::PortableGlob {
field: "tool.uv.build-backend.*-exclude".to_string(),
source: err,
})?;
exclude_builder.add(glob);
}
let exclude_matcher = exclude_builder
.build()
.map_err(|err| Error::GlobSetTooLarge {
field: "tool.uv.build-backend.*-exclude".to_string(),
source: err,
})?;
Ok(exclude_matcher)
}
/// Add the files and directories matching from the source tree matching any of the globs in the
/// wheel subdirectory.
fn wheel_subdir_from_globs(
src: &Path,
target: &str,
globs: impl IntoIterator<Item = impl AsRef<str>>,
wheel_writer: &mut impl DirectoryWriter,
// For error messages
globs_field: &str,
) -> Result<(), Error> {
let license_files_globs: Vec<_> = globs
.into_iter()
.map(|license_files| {
let license_files = license_files.as_ref();
trace!(
"Including {} at `{}` with `{}`",
globs_field,
src.user_display(),
license_files
);
PortableGlobParser::Pep639.parse(license_files)
})
.collect::<Result<_, _>>()
.map_err(|err| Error::PortableGlob {
field: globs_field.to_string(),
source: err,
})?;
let matcher =
GlobDirFilter::from_globs(&license_files_globs).map_err(|err| Error::GlobSetTooLarge {
field: globs_field.to_string(),
source: err,
})?;
wheel_writer.write_directory(target)?;
for entry in WalkDir::new(src)
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| {
// TODO(konsti): This should be prettier.
let relative = entry
.path()
.strip_prefix(src)
.expect("walkdir starts with root");
// Fast path: Don't descend into a directory that can't be included.
matcher.match_directory(relative)
})
{
let entry = entry.map_err(|err| Error::WalkDir {
root: src.to_path_buf(),
err,
})?;
// Skip the root path, which is already included as `target` prior to the loop.
// (If `entry.path() == src`, then `relative` is empty, and `relative_licenses` is
// `target`.)
if entry.path() == src {
continue;
}
// TODO(konsti): This should be prettier.
let relative = entry
.path()
.strip_prefix(src)
.expect("walkdir starts with root");
if !matcher.match_path(relative) {
trace!("Excluding {}: {}", globs_field, relative.user_display());
continue;
}
error_on_venv(entry.file_name(), entry.path())?;
let license_path = Path::new(target)
.join(relative)
.portable_display()
.to_string();
debug!("Adding for {}: {}", globs_field, relative.user_display());
wheel_writer.write_dir_entry(&entry, &license_path)?;
}
Ok(())
}
/// Add `METADATA` and `entry_points.txt` to the dist-info directory.
///
/// Returns the name of the dist-info directory.
fn write_dist_info(
writer: &mut dyn DirectoryWriter,
pyproject_toml: &PyProjectToml,
filename: &WheelFilename,
root: &Path,
uv_version: &str,
) -> Result<String, Error> {
let dist_info_dir = format!(
"{}-{}.dist-info",
pyproject_toml.name().as_dist_info_name(),
pyproject_toml.version()
);
writer.write_directory(&dist_info_dir)?;
// Add `WHEEL`.
let wheel_info = wheel_info(filename, uv_version);
writer.write_bytes(&format!("{dist_info_dir}/WHEEL"), wheel_info.as_bytes())?;
// Add `entry_points.txt`.
if let Some(entrypoint) = pyproject_toml.to_entry_points()? {
writer.write_bytes(
&format!("{dist_info_dir}/entry_points.txt"),
entrypoint.as_bytes(),
)?;
}
// Add `METADATA`.
let metadata = pyproject_toml.to_metadata(root)?.core_metadata_format();
writer.write_bytes(&format!("{dist_info_dir}/METADATA"), metadata.as_bytes())?;
// `RECORD` is added on closing.
Ok(dist_info_dir)
}
/// Returns the `WHEEL` file contents.
fn wheel_info(filename: &WheelFilename, uv_version: &str) -> String {
// https://packaging.python.org/en/latest/specifications/binary-distribution-format/#file-contents
let mut wheel_info = vec![
("Wheel-Version", "1.0".to_string()),
("Generator", format!("uv {uv_version}")),
("Root-Is-Purelib", "true".to_string()),
];
for python_tag in filename.python_tags() {
for abi_tag in filename.abi_tags() {
for platform_tag in filename.platform_tags() {
wheel_info.push(("Tag", format!("{python_tag}-{abi_tag}-{platform_tag}")));
}
}
}
wheel_info
.into_iter()
.map(|(key, value)| format!("{key}: {value}"))
.join("\n")
}
/// Zip archive (wheel) writer.
struct ZipDirectoryWriter {
writer: ZipWriter<File>,
compression: CompressionMethod,
/// The entries in the `RECORD` file.
record: Vec<RecordEntry>,
}
impl ZipDirectoryWriter {
/// A wheel writer with deflate compression.
fn new_wheel(file: File) -> Self {
Self {
writer: ZipWriter::new(file),
compression: CompressionMethod::Deflated,
record: Vec::new(),
}
}
/// A wheel writer with no (stored) compression.
///
/// Since editables are temporary, we save time be skipping compression and decompression.
#[expect(dead_code)]
fn new_editable(file: File) -> Self {
Self {
writer: ZipWriter::new(file),
compression: CompressionMethod::Stored,
record: Vec::new(),
}
}
/// Add a file with the given name and return a writer for it.
fn new_writer<'slf>(
&'slf mut self,
path: &str,
executable_bit: bool,
) -> Result<Box<dyn Write + 'slf>, Error> {
// Set file permissions: 644 (rw-r--r--) for regular files, 755 (rwxr-xr-x) for executables
let permissions = if executable_bit { 0o755 } else { 0o644 };
let options = zip::write::SimpleFileOptions::default()
.unix_permissions(permissions)
.compression_method(self.compression);
self.writer.start_file(path, options)?;
Ok(Box::new(&mut self.writer))
}
}
impl DirectoryWriter for ZipDirectoryWriter {
fn write_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
trace!("Adding {}", path);
// Set appropriate permissions for metadata files (644 = rw-r--r--)
let options = zip::write::SimpleFileOptions::default()
.unix_permissions(0o644)
.compression_method(self.compression);
self.writer.start_file(path, options)?;
self.writer.write_all(bytes)?;
let hash = base64.encode(Sha256::new().chain_update(bytes).finalize());
self.record.push(RecordEntry {
path: path.to_string(),
hash,
size: bytes.len(),
});
Ok(())
}
fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error> {
trace!("Adding {} from {}", path, file.user_display());
let mut reader = BufReader::new(File::open(file)?);
// Preserve the executable bit, especially for scripts
#[cfg(unix)]
let executable_bit = {
use std::os::unix::fs::PermissionsExt;
file.metadata()?.permissions().mode() & 0o111 != 0
};
// Windows has no executable bit
#[cfg(not(unix))]
let executable_bit = false;
let mut writer = self.new_writer(path, executable_bit)?;
let record = write_hashed(path, &mut reader, &mut writer)?;
drop(writer);
self.record.push(record);
Ok(())
}
fn write_directory(&mut self, directory: &str) -> Result<(), Error> {
trace!("Adding directory {}", directory);
let options = zip::write::SimpleFileOptions::default().compression_method(self.compression);
Ok(self.writer.add_directory(directory, options)?)
}
/// Write the `RECORD` file and the central directory.
fn close(mut self, dist_info_dir: &str) -> Result<(), Error> {
let record_path = format!("{dist_info_dir}/RECORD");
trace!("Adding {record_path}");
let record = mem::take(&mut self.record);
write_record(
&mut self.new_writer(&record_path, false)?,
dist_info_dir,
record,
)?;
trace!("Adding central directory");
self.writer.finish()?;
Ok(())
}
}
struct FilesystemWriter {
/// The virtualenv or metadata directory that add file paths are relative to.
root: PathBuf,
/// The entries in the `RECORD` file.
record: Vec<RecordEntry>,
}
impl FilesystemWriter {
fn new(root: &Path) -> Self {
Self {
root: root.to_owned(),
record: Vec::new(),
}
}
/// Add a file with the given name and return a writer for it.
fn new_writer<'slf>(&'slf mut self, path: &str) -> Result<Box<dyn Write + 'slf>, Error> {
trace!("Adding {}", path);
Ok(Box::new(File::create(self.root.join(path))?))
}
}
/// File system writer.
impl DirectoryWriter for FilesystemWriter {
fn write_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
trace!("Adding {}", path);
let hash = base64.encode(Sha256::new().chain_update(bytes).finalize());
self.record.push(RecordEntry {
path: path.to_string(),
hash,
size: bytes.len(),
});
Ok(fs_err::write(self.root.join(path), bytes)?)
}
fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error> {
trace!("Adding {} from {}", path, file.user_display());
let mut reader = BufReader::new(File::open(file)?);
let mut writer = self.new_writer(path)?;
let record = write_hashed(path, &mut reader, &mut writer)?;
drop(writer);
self.record.push(record);
Ok(())
}
fn write_directory(&mut self, directory: &str) -> Result<(), Error> {
trace!("Adding directory {}", directory);
Ok(fs_err::create_dir(self.root.join(directory))?)
}
/// Write the `RECORD` file.
fn close(mut self, dist_info_dir: &str) -> Result<(), Error> {
let record = mem::take(&mut self.record);
write_record(
&mut self.new_writer(&format!("{dist_info_dir}/RECORD"))?,
dist_info_dir,
record,
)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use insta::assert_snapshot;
use std::path::Path;
use std::str::FromStr;
use tempfile::TempDir;
use uv_distribution_filename::WheelFilename;
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_platform_tags::{AbiTag, PlatformTag};
use walkdir::WalkDir;
#[test]
fn test_wheel() {
let filename = WheelFilename::new(
PackageName::from_str("foo").unwrap(),
Version::from_str("1.2.3").unwrap(),
LanguageTag::Python {
major: 3,
minor: None,
},
AbiTag::None,
PlatformTag::Any,
);
assert_snapshot!(wheel_info(&filename, "1.0.0+test"), @r"
Wheel-Version: 1.0
Generator: uv 1.0.0+test
Root-Is-Purelib: true
Tag: py3-none-any
");
}
#[test]
fn test_record() {
let record = vec![RecordEntry {
path: "built_by_uv/__init__.py".to_string(),
hash: "ifhp5To6AGGlLAIz5kQtTXLegKii00BtnqC_05fteGU".to_string(),
size: 37,
}];
let mut writer = Vec::new();
write_record(&mut writer, "built_by_uv-0.1.0", record).unwrap();
assert_snapshot!(String::from_utf8(writer).unwrap(), @r"
built_by_uv/__init__.py,sha256=ifhp5To6AGGlLAIz5kQtTXLegKii00BtnqC_05fteGU,37
built_by_uv-0.1.0/RECORD,,
");
}
/// Snapshot all files from the prepare metadata hook.
#[test]
fn test_prepare_metadata() {
let metadata_dir = TempDir::new().unwrap();
let built_by_uv = Path::new("../../test/packages/built-by-uv");
metadata(built_by_uv, metadata_dir.path(), "1.0.0+test").unwrap();
let mut files: Vec<_> = WalkDir::new(metadata_dir.path())
.sort_by_file_name()
.into_iter()
.map(|entry| {
entry
.unwrap()
.path()
.strip_prefix(metadata_dir.path())
.expect("walkdir starts with root")
.portable_display()
.to_string()
})
.filter(|path| !path.is_empty())
.collect();
files.sort();
assert_snapshot!(files.join("\n"), @r###"
built_by_uv-0.1.0.dist-info
built_by_uv-0.1.0.dist-info/METADATA
built_by_uv-0.1.0.dist-info/RECORD
built_by_uv-0.1.0.dist-info/WHEEL
built_by_uv-0.1.0.dist-info/entry_points.txt
"###);
let metadata_file = metadata_dir
.path()
.join("built_by_uv-0.1.0.dist-info/METADATA");
assert_snapshot!(fs_err::read_to_string(metadata_file).unwrap(), @r###"
Metadata-Version: 2.4
Name: built-by-uv
Version: 0.1.0
Summary: A package to be built with the uv build backend that uses all features exposed by the build backend
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: third-party-licenses/PEP-401.txt
Requires-Dist: anyio>=4,<5
Requires-Python: >=3.12
Description-Content-Type: text/markdown
# built_by_uv
A package to be built with the uv build backend that uses all features exposed by the build backend.
"###);
let record_file = metadata_dir
.path()
.join("built_by_uv-0.1.0.dist-info/RECORD");
assert_snapshot!(fs_err::read_to_string(record_file).unwrap(), @r###"
built_by_uv-0.1.0.dist-info/WHEEL,sha256=PaG_oOj9G2zCRqoLK0SjWBVZbGAMtIXDmm-MEGw9Wo0,83
built_by_uv-0.1.0.dist-info/entry_points.txt,sha256=-IO6yaq6x6HSl-zWH96rZmgYvfyHlH00L5WQoCpz-YI,50
built_by_uv-0.1.0.dist-info/METADATA,sha256=m6EkVvKrGmqx43b_VR45LHD37IZxPYC0NI6Qx9_UXLE,474
built_by_uv-0.1.0.dist-info/RECORD,,
"###);
let wheel_file = metadata_dir
.path()
.join("built_by_uv-0.1.0.dist-info/WHEEL");
assert_snapshot!(fs_err::read_to_string(wheel_file).unwrap(), @r###"
Wheel-Version: 1.0
Generator: uv 1.0.0+test
Root-Is-Purelib: true
Tag: py3-none-any
"###);
}
}
| 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-build-backend/src/metadata.rs | crates/uv-build-backend/src/metadata.rs | use std::collections::{BTreeMap, Bound};
use std::ffi::OsStr;
use std::fmt::Display;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::str::{self, FromStr};
use itertools::Itertools;
use serde::{Deserialize, Deserializer};
use tracing::{debug, trace, warn};
use version_ranges::Ranges;
use walkdir::WalkDir;
use uv_fs::Simplified;
use uv_globfilter::{GlobDirFilter, PortableGlobParser};
use uv_normalize::{ExtraName, PackageName};
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::{
ExtraOperator, MarkerExpression, MarkerTree, MarkerValueExtra, Requirement, VersionOrUrl,
};
use uv_pypi_types::{Metadata23, VerbatimParsedUrl};
use crate::serde_verbatim::SerdeVerbatim;
use crate::{BuildBackendSettings, Error, error_on_venv};
/// By default, we ignore generated python files.
pub(crate) const DEFAULT_EXCLUDES: &[&str] = &["__pycache__", "*.pyc", "*.pyo"];
#[derive(Debug, Error)]
pub enum ValidationError {
/// The spec isn't clear about what the values in that field would be, and we only support the
/// default value (UTF-8).
#[error(
"Charsets other than UTF-8 are not supported. Please convert your README to UTF-8 and remove `project.readme.charset`."
)]
ReadmeCharset,
#[error(
"Unknown Readme extension `{0}`, can't determine content type. Please use a support extension (`.md`, `.rst`, `.txt`) or set the content type manually."
)]
UnknownExtension(String),
#[error("Can't infer content type because `{}` does not have an extension. Please use a support extension (`.md`, `.rst`, `.txt`) or set the content type manually.", _0.user_display())]
MissingExtension(PathBuf),
#[error("Unsupported content type: {0}")]
UnsupportedContentType(String),
#[error("`project.description` must be a single line")]
DescriptionNewlines,
#[error("Dynamic metadata is not supported")]
Dynamic,
#[error(
"When `project.license-files` is defined, `project.license` must be an SPDX expression string"
)]
MixedLicenseGenerations,
#[error(
"Entrypoint groups must consist of letters and numbers separated by dots, invalid group: {0}"
)]
InvalidGroup(String),
#[error("Use `project.scripts` instead of `project.entry-points.console_scripts`")]
ReservedScripts,
#[error("Use `project.gui-scripts` instead of `project.entry-points.gui_scripts`")]
ReservedGuiScripts,
#[error("`project.license` is not a valid SPDX expression: {0}")]
InvalidSpdx(String, #[source] spdx::error::ParseError),
#[error("`{field}` glob `{glob}` did not match any files")]
LicenseGlobNoMatches { field: String, glob: String },
#[error("License file `{}` must be UTF-8 encoded", _0)]
LicenseFileNotUtf8(String),
}
/// Check if the build backend is matching the currently running uv version.
pub fn check_direct_build(source_tree: &Path, name: impl Display) -> bool {
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct PyProjectToml {
build_system: BuildSystem,
}
let pyproject_toml: PyProjectToml =
match fs_err::read_to_string(source_tree.join("pyproject.toml"))
.map_err(|err| err.to_string())
.and_then(|pyproject_toml| {
toml::from_str(&pyproject_toml).map_err(|err| err.to_string())
}) {
Ok(pyproject_toml) => pyproject_toml,
Err(err) => {
debug!(
"Not using uv build backend direct build for source tree `{name}`, \
failed to parse pyproject.toml: {err}"
);
return false;
}
};
match pyproject_toml
.build_system
.check_build_system(uv_version::version())
.as_slice()
{
// No warnings -> match
[] => true,
// Any warning -> no match
[first, others @ ..] => {
debug!(
"Not using uv build backend direct build of `{name}`, pyproject.toml does not match: {first}"
);
for other in others {
trace!("Further uv build backend direct build of `{name}` mismatch: {other}");
}
false
}
}
}
/// A package name as provided in a `pyproject.toml`.
#[derive(Debug, Clone)]
struct VerbatimPackageName {
/// The package name as given in the `pyproject.toml`.
given: String,
/// The normalized package name.
normalized: PackageName,
}
impl<'de> Deserialize<'de> for VerbatimPackageName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let given = String::deserialize(deserializer)?;
let normalized = PackageName::from_str(&given).map_err(serde::de::Error::custom)?;
Ok(Self { given, normalized })
}
}
/// A `pyproject.toml` as specified in PEP 517.
#[derive(Deserialize, Debug, Clone)]
#[serde(
rename_all = "kebab-case",
expecting = "The project table needs to follow \
https://packaging.python.org/en/latest/guides/writing-pyproject-toml"
)]
pub struct PyProjectToml {
/// Project metadata
project: Project,
/// uv-specific configuration
tool: Option<Tool>,
/// Build-related data
build_system: BuildSystem,
}
impl PyProjectToml {
pub(crate) fn name(&self) -> &PackageName {
&self.project.name.normalized
}
pub(crate) fn version(&self) -> &Version {
&self.project.version
}
pub(crate) fn parse(path: &Path) -> Result<Self, Error> {
let contents = fs_err::read_to_string(path)?;
let pyproject_toml =
toml::from_str(&contents).map_err(|err| Error::Toml(path.to_path_buf(), err))?;
Ok(pyproject_toml)
}
pub(crate) fn readme(&self) -> Option<&Readme> {
self.project.readme.as_ref()
}
/// The license files that need to be included in the source distribution.
pub(crate) fn license_files_source_dist(&self) -> impl Iterator<Item = &str> {
let license_file = self
.project
.license
.as_ref()
.and_then(|license| license.file())
.into_iter();
let license_files = self
.project
.license_files
.iter()
.flatten()
.map(String::as_str);
license_files.chain(license_file)
}
/// The license files that need to be included in the wheel.
pub(crate) fn license_files_wheel(&self) -> impl Iterator<Item = &str> {
// The pre-PEP 639 `license = { file = "..." }` is included inline in `METADATA`.
self.project
.license_files
.iter()
.flatten()
.map(String::as_str)
}
pub(crate) fn settings(&self) -> Option<&BuildBackendSettings> {
self.tool.as_ref()?.uv.as_ref()?.build_backend.as_ref()
}
/// See [`BuildSystem::check_build_system`].
pub fn check_build_system(&self, uv_version: &str) -> Vec<String> {
self.build_system.check_build_system(uv_version)
}
/// Validate and convert a `pyproject.toml` to core metadata.
///
/// <https://packaging.python.org/en/latest/guides/writing-pyproject-toml/>
/// <https://packaging.python.org/en/latest/specifications/pyproject-toml/>
/// <https://packaging.python.org/en/latest/specifications/core-metadata/>
pub(crate) fn to_metadata(&self, root: &Path) -> Result<Metadata23, Error> {
let summary = if let Some(description) = &self.project.description {
if description.contains('\n') {
return Err(ValidationError::DescriptionNewlines.into());
}
Some(description.clone())
} else {
None
};
let supported_content_types = ["text/plain", "text/x-rst", "text/markdown"];
let (description, description_content_type) = match &self.project.readme {
Some(Readme::String(path)) => {
let content = fs_err::read_to_string(root.join(path))?;
let content_type = match path.extension().and_then(OsStr::to_str) {
Some("txt") => "text/plain",
Some("rst") => "text/x-rst",
Some("md") => "text/markdown",
Some(unknown) => {
return Err(ValidationError::UnknownExtension(unknown.to_owned()).into());
}
None => return Err(ValidationError::MissingExtension(path.clone()).into()),
}
.to_string();
(Some(content), Some(content_type))
}
Some(Readme::File {
file,
content_type,
charset,
}) => {
let content = fs_err::read_to_string(root.join(file))?;
if !supported_content_types.contains(&content_type.as_str()) {
return Err(
ValidationError::UnsupportedContentType(content_type.clone()).into(),
);
}
if charset.as_ref().is_some_and(|charset| charset != "UTF-8") {
return Err(ValidationError::ReadmeCharset.into());
}
(Some(content), Some(content_type.clone()))
}
Some(Readme::Text {
text,
content_type,
charset,
}) => {
if !supported_content_types.contains(&content_type.as_str()) {
return Err(
ValidationError::UnsupportedContentType(content_type.clone()).into(),
);
}
if charset.as_ref().is_some_and(|charset| charset != "UTF-8") {
return Err(ValidationError::ReadmeCharset.into());
}
(Some(text.clone()), Some(content_type.clone()))
}
None => (None, None),
};
if self
.project
.dynamic
.as_ref()
.is_some_and(|dynamic| !dynamic.is_empty())
{
return Err(ValidationError::Dynamic.into());
}
let author = self
.project
.authors
.as_ref()
.map(|authors| {
authors
.iter()
.filter_map(|author| match author {
Contact::Name { name } => Some(name),
Contact::Email { .. } => None,
Contact::NameEmail { name, .. } => Some(name),
})
.join(", ")
})
.filter(|author| !author.is_empty());
let author_email = self
.project
.authors
.as_ref()
.map(|authors| {
authors
.iter()
.filter_map(|author| match author {
Contact::Name { .. } => None,
Contact::Email { email } => Some(email.clone()),
Contact::NameEmail { name, email } => Some(format!("{name} <{email}>")),
})
.join(", ")
})
.filter(|author_email| !author_email.is_empty());
let maintainer = self
.project
.maintainers
.as_ref()
.map(|maintainers| {
maintainers
.iter()
.filter_map(|maintainer| match maintainer {
Contact::Name { name } => Some(name),
Contact::Email { .. } => None,
Contact::NameEmail { name, .. } => Some(name),
})
.join(", ")
})
.filter(|maintainer| !maintainer.is_empty());
let maintainer_email = self
.project
.maintainers
.as_ref()
.map(|maintainers| {
maintainers
.iter()
.filter_map(|maintainer| match maintainer {
Contact::Name { .. } => None,
Contact::Email { email } => Some(email.clone()),
Contact::NameEmail { name, email } => Some(format!("{name} <{email}>")),
})
.join(", ")
})
.filter(|maintainer_email| !maintainer_email.is_empty());
// Using PEP 639 bumps the METADATA version
let metadata_version = if self.project.license_files.is_some()
|| matches!(self.project.license, Some(License::Spdx(_)))
{
debug!("Found PEP 639 license declarations, using METADATA 2.4");
"2.4"
} else {
"2.3"
};
let (license, license_expression, license_files) = self.license_metadata(root)?;
// TODO(konsti): https://peps.python.org/pep-0753/#label-normalization (Draft)
let project_urls = self
.project
.urls
.iter()
.flatten()
.map(|(key, value)| format!("{key}, {value}"))
.collect();
let extras = self
.project
.optional_dependencies
.iter()
.flat_map(|optional_dependencies| optional_dependencies.keys())
.collect::<Vec<_>>();
let requires_dist =
self.project
.dependencies
.iter()
.flatten()
.cloned()
.chain(self.project.optional_dependencies.iter().flat_map(
|optional_dependencies| {
optional_dependencies
.iter()
.flat_map(|(extra, requirements)| {
requirements.iter().cloned().map(|mut requirement| {
requirement.marker.and(MarkerTree::expression(
MarkerExpression::Extra {
operator: ExtraOperator::Equal,
name: MarkerValueExtra::Extra(extra.clone()),
},
));
requirement
})
})
},
))
.collect::<Vec<_>>();
Ok(Metadata23 {
metadata_version: metadata_version.to_string(),
name: self.project.name.given.clone(),
version: self.project.version.to_string(),
// Not supported.
platforms: vec![],
// Not supported.
supported_platforms: vec![],
summary,
description,
description_content_type,
keywords: self
.project
.keywords
.as_ref()
.map(|keywords| keywords.join(",")),
home_page: None,
download_url: None,
author,
author_email,
maintainer,
maintainer_email,
license,
license_expression,
license_files,
classifiers: self.project.classifiers.clone().unwrap_or_default(),
requires_dist: requires_dist.iter().map(ToString::to_string).collect(),
provides_extra: extras.iter().map(ToString::to_string).collect(),
// Not commonly set.
provides_dist: vec![],
// Not supported.
obsoletes_dist: vec![],
requires_python: self
.project
.requires_python
.as_ref()
.map(ToString::to_string),
// Not used by other tools, not supported.
requires_external: vec![],
project_urls,
dynamic: vec![],
})
}
/// Parse and validate the old (PEP 621) and new (PEP 639) license files.
#[allow(clippy::type_complexity)]
fn license_metadata(
&self,
root: &Path,
) -> Result<(Option<String>, Option<String>, Vec<String>), Error> {
// TODO(konsti): Issue a warning on old license metadata once PEP 639 is universal.
let (license, license_expression, license_files) = if let Some(license_globs) =
&self.project.license_files
{
let license_expression = match &self.project.license {
None => None,
Some(License::Spdx(license_expression)) => Some(license_expression.clone()),
Some(License::Text { .. } | License::File { .. }) => {
return Err(ValidationError::MixedLicenseGenerations.into());
}
};
let mut license_files = Vec::new();
let mut license_globs_parsed = Vec::with_capacity(license_globs.len());
let mut license_glob_matchers = Vec::with_capacity(license_globs.len());
for license_glob in license_globs {
let pep639_glob =
PortableGlobParser::Pep639
.parse(license_glob)
.map_err(|err| Error::PortableGlob {
field: license_glob.to_owned(),
source: err,
})?;
license_glob_matchers.push(pep639_glob.compile_matcher());
license_globs_parsed.push(pep639_glob);
}
// Track whether each user-specified glob matched so we can flag the unmatched ones.
let mut license_globs_matched = vec![false; license_globs_parsed.len()];
let license_globs =
GlobDirFilter::from_globs(&license_globs_parsed).map_err(|err| {
Error::GlobSetTooLarge {
field: "project.license-files".to_string(),
source: err,
}
})?;
for entry in WalkDir::new(root)
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| {
license_globs.match_directory(
entry
.path()
.strip_prefix(root)
.expect("walkdir starts with root"),
)
})
{
let entry = entry.map_err(|err| Error::WalkDir {
root: root.to_path_buf(),
err,
})?;
let relative = entry
.path()
.strip_prefix(root)
.expect("walkdir starts with root");
if !license_globs.match_path(relative) {
trace!("Not a license files match: {}", relative.user_display());
continue;
}
let file_type = entry.file_type();
if !(file_type.is_file() || file_type.is_symlink()) {
trace!(
"Not a file or symlink in license files match: {}",
relative.user_display()
);
continue;
}
error_on_venv(entry.file_name(), entry.path())?;
debug!("License files match: {}", relative.user_display());
for (matched, matcher) in license_globs_matched
.iter_mut()
.zip(license_glob_matchers.iter())
{
if *matched {
continue;
}
if matcher.is_match(relative) {
*matched = true;
}
}
license_files.push(relative.portable_display().to_string());
}
if let Some((pattern, _)) = license_globs_parsed
.into_iter()
.zip(license_globs_matched)
.find(|(_, matched)| !matched)
{
return Err(ValidationError::LicenseGlobNoMatches {
field: "project.license-files".to_string(),
glob: pattern.to_string(),
}
.into());
}
for license_file in &license_files {
let file_path = root.join(license_file);
let bytes = fs_err::read(&file_path)?;
if str::from_utf8(&bytes).is_err() {
return Err(ValidationError::LicenseFileNotUtf8(license_file.clone()).into());
}
}
// The glob order may be unstable
license_files.sort();
(None, license_expression, license_files)
} else {
match &self.project.license {
None => (None, None, Vec::new()),
Some(License::Spdx(license_expression)) => {
(None, Some(license_expression.clone()), Vec::new())
}
Some(License::Text { text }) => (Some(text.clone()), None, Vec::new()),
Some(License::File { file }) => {
let text = fs_err::read_to_string(root.join(file))?;
(Some(text), None, Vec::new())
}
}
};
// Check that the license expression is a valid SPDX identifier.
if let Some(license_expression) = &license_expression {
if let Err(err) = spdx::Expression::parse(license_expression) {
return Err(ValidationError::InvalidSpdx(license_expression.clone(), err).into());
}
}
Ok((license, license_expression, license_files))
}
/// Validate and convert the entrypoints in `pyproject.toml`, including console and GUI scripts,
/// to an `entry_points.txt`.
///
/// <https://packaging.python.org/en/latest/specifications/entry-points/>
///
/// Returns `None` if no entrypoints were defined.
pub(crate) fn to_entry_points(&self) -> Result<Option<String>, ValidationError> {
let mut writer = String::new();
if self.project.scripts.is_none()
&& self.project.gui_scripts.is_none()
&& self.project.entry_points.is_none()
{
return Ok(None);
}
if let Some(scripts) = &self.project.scripts {
Self::write_group(&mut writer, "console_scripts", scripts)?;
}
if let Some(gui_scripts) = &self.project.gui_scripts {
Self::write_group(&mut writer, "gui_scripts", gui_scripts)?;
}
for (group, entries) in self.project.entry_points.iter().flatten() {
if group == "console_scripts" {
return Err(ValidationError::ReservedScripts);
}
if group == "gui_scripts" {
return Err(ValidationError::ReservedGuiScripts);
}
Self::write_group(&mut writer, group, entries)?;
}
Ok(Some(writer))
}
/// Write a group to `entry_points.txt`.
fn write_group<'a>(
writer: &mut String,
group: &str,
entries: impl IntoIterator<Item = (&'a String, &'a String)>,
) -> Result<(), ValidationError> {
if !group
.chars()
.next()
.map(|c| c.is_alphanumeric() || c == '_')
.unwrap_or(false)
|| !group
.chars()
.all(|c| c.is_alphanumeric() || c == '.' || c == '_')
{
return Err(ValidationError::InvalidGroup(group.to_string()));
}
let _ = writeln!(writer, "[{group}]");
for (name, object_reference) in entries {
if !name
.chars()
.all(|c| c.is_alphanumeric() || c == '.' || c == '-' || c == '_')
{
warn!(
"Entrypoint names should consist of letters, numbers, dots, underscores and \
dashes; non-compliant name: {name}"
);
}
// TODO(konsti): Validate that the object references are valid Python identifiers.
let _ = writeln!(writer, "{name} = {object_reference}");
}
writer.push('\n');
Ok(())
}
}
/// The `[project]` section of a pyproject.toml as specified in
/// <https://packaging.python.org/en/latest/specifications/pyproject-toml>.
///
/// This struct does not have schema export; the schema is shared between all Python tools, and we
/// should update the shared schema instead.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
struct Project {
/// The name of the project.
name: VerbatimPackageName,
/// The version of the project.
version: Version,
/// The summary description of the project in one line.
description: Option<String>,
/// The full description of the project (i.e. the README).
readme: Option<Readme>,
/// The Python version requirements of the project.
requires_python: Option<VersionSpecifiers>,
/// The license under which the project is distributed.
///
/// Supports both the current standard and the provisional PEP 639.
license: Option<License>,
/// The paths to files containing licenses and other legal notices to be distributed with the
/// project.
///
/// From the provisional PEP 639
license_files: Option<Vec<String>>,
/// The people or organizations considered to be the "authors" of the project.
authors: Option<Vec<Contact>>,
/// The people or organizations considered to be the "maintainers" of the project.
maintainers: Option<Vec<Contact>>,
/// The keywords for the project.
keywords: Option<Vec<String>>,
/// Trove classifiers which apply to the project.
classifiers: Option<Vec<String>>,
/// A table of URLs where the key is the URL label and the value is the URL itself.
///
/// PyPI shows all URLs with their name. For some known patterns, they add favicons.
/// main: <https://github.com/pypi/warehouse/blob/main/warehouse/templates/packaging/detail.html>
/// archived: <https://github.com/pypi/warehouse/blob/e3bd3c3805ff47fff32b67a899c1ce11c16f3c31/warehouse/templates/packaging/detail.html>
urls: Option<BTreeMap<String, String>>,
/// The console entrypoints of the project.
///
/// The key of the table is the name of the entry point and the value is the object reference.
scripts: Option<BTreeMap<String, String>>,
/// The GUI entrypoints of the project.
///
/// The key of the table is the name of the entry point and the value is the object reference.
gui_scripts: Option<BTreeMap<String, String>>,
/// Entrypoints groups of the project.
///
/// The key of the table is the name of the entry point and the value is the object reference.
entry_points: Option<BTreeMap<String, BTreeMap<String, String>>>,
/// The dependencies of the project.
dependencies: Option<Vec<Requirement>>,
/// The optional dependencies of the project.
optional_dependencies: Option<BTreeMap<ExtraName, Vec<Requirement>>>,
/// Specifies which fields listed by PEP 621 were intentionally unspecified so another tool
/// can/will provide such metadata dynamically.
///
/// Not supported, an error if anything but the default empty list.
dynamic: Option<Vec<String>>,
}
/// The optional `project.readme` key in a pyproject.toml as specified in
/// <https://packaging.python.org/en/latest/specifications/pyproject-toml/#readme>.
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged, rename_all_fields = "kebab-case")]
pub(crate) enum Readme {
/// Relative path to the README.
String(PathBuf),
/// Relative path to the README.
File {
file: PathBuf,
content_type: String,
charset: Option<String>,
},
/// The full description of the project as an inline value.
Text {
text: String,
content_type: String,
charset: Option<String>,
},
}
impl Readme {
/// If the readme is a file, return the path to the file.
pub(crate) fn path(&self) -> Option<&Path> {
match self {
Self::String(path) => Some(path),
Self::File { file, .. } => Some(file),
Self::Text { .. } => None,
}
}
}
/// The optional `project.license` key in a pyproject.toml as specified in
/// <https://packaging.python.org/en/latest/specifications/pyproject-toml/#license>.
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub(crate) enum License {
/// An SPDX Expression.
///
/// From the provisional PEP 639.
Spdx(String),
Text {
/// The full text of the license.
text: String,
},
File {
/// The file containing the license text.
file: String,
},
}
impl License {
fn file(&self) -> Option<&str> {
if let Self::File { file } = self {
Some(file)
} else {
None
}
}
}
/// A `project.authors` or `project.maintainers` entry as specified in
/// <https://packaging.python.org/en/latest/specifications/pyproject-toml/#authors-maintainers>.
///
/// The entry is derived from the email format of `John Doe <john.doe@example.net>`. You need to
/// provide at least name or email.
#[derive(Deserialize, Debug, Clone)]
// deny_unknown_fields prevents using the name field when the email is not a string.
#[serde(
untagged,
deny_unknown_fields,
expecting = "a table with 'name' and/or 'email' keys"
)]
pub(crate) enum Contact {
/// TODO(konsti): RFC 822 validation.
NameEmail { name: String, email: String },
/// TODO(konsti): RFC 822 validation.
Name { name: String },
/// TODO(konsti): RFC 822 validation.
Email { email: String },
}
/// The `tool` section as specified in PEP 517.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct Tool {
/// uv-specific configuration
uv: Option<ToolUv>,
}
/// The `tool.uv` section with build configuration.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct ToolUv {
/// Configuration for building source distributions and wheels with the uv build backend
build_backend: Option<BuildBackendSettings>,
}
/// The `[build-system]` section of a pyproject.toml as specified in PEP 517.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
struct BuildSystem {
/// PEP 508 dependencies required to execute the build system.
requires: Vec<SerdeVerbatim<Requirement<VerbatimParsedUrl>>>,
/// A string naming a Python object that will be used to perform the build.
build_backend: Option<String>,
/// <https://peps.python.org/pep-0517/#in-tree-build-backends>
backend_path: Option<Vec<String>>,
}
impl BuildSystem {
/// Check if the `[build-system]` table matches the uv build backend expectations and return
/// a list of warnings if it looks suspicious.
///
/// Example of a valid table:
///
/// ```toml
/// [build-system]
/// requires = ["uv_build>=0.4.15,<0.5.0"]
/// build-backend = "uv_build"
/// ```
pub(crate) fn check_build_system(&self, uv_version: &str) -> Vec<String> {
let mut warnings = Vec::new();
if self.build_backend.as_deref() != Some("uv_build") {
warnings.push(format!(
r#"The value for `build_system.build-backend` should be `"uv_build"`, not `"{}"`"#,
self.build_backend.clone().unwrap_or_default()
));
}
let uv_version =
Version::from_str(uv_version).expect("uv's own version is not PEP 440 compliant");
let next_minor = uv_version.release().get(1).copied().unwrap_or_default() + 1;
let next_breaking = Version::new([0, next_minor]);
let expected = || {
format!(
"Expected a single uv requirement in `build-system.requires`, found `{}`",
toml::to_string(&self.requires).unwrap_or_default()
)
};
let [uv_requirement] = &self.requires.as_slice() else {
warnings.push(expected());
return warnings;
};
if uv_requirement.name.as_str() != "uv-build" {
warnings.push(expected());
return warnings;
}
let bounded = match &uv_requirement.version_or_url {
None => false,
| 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-build-backend/src/serde_verbatim.rs | crates/uv-build-backend/src/serde_verbatim.rs | use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::str::FromStr;
/// Preserves the verbatim string representation when deserializing `T`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct SerdeVerbatim<T> {
verbatim: String,
inner: T,
}
impl<T> SerdeVerbatim<T> {
pub(crate) fn verbatim(&self) -> &str {
&self.verbatim
}
}
impl<T> Deref for SerdeVerbatim<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Display> Display for SerdeVerbatim<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl<'de, T: FromStr> Deserialize<'de> for SerdeVerbatim<T>
where
<T as FromStr>::Err: Display,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let verbatim = String::deserialize(deserializer)?;
let inner = T::from_str(&verbatim).map_err(serde::de::Error::custom)?;
Ok(Self { verbatim, inner })
}
}
impl<T: Serialize> Serialize for SerdeVerbatim<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.inner.serialize(serializer)
}
}
| 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-version/src/lib.rs | crates/uv-version/src/lib.rs | /// Return the application version.
///
/// This should be in sync with uv's version based on the Crate version.
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_version() {
assert_eq!(version().to_string(), env!("CARGO_PKG_VERSION").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-workspace/src/pyproject.rs | crates/uv-workspace/src/pyproject.rs | //! Reads the following fields from `pyproject.toml`:
//!
//! * `project.{dependencies,optional-dependencies}`
//! * `tool.uv.sources`
//! * `tool.uv.workspace`
//!
//! Then lowers them into a dependency specification.
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Formatter;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use glob::Pattern;
use owo_colors::OwoColorize;
use rustc_hash::{FxBuildHasher, FxHashSet};
use serde::de::{IntoDeserializer, SeqAccess};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use uv_build_backend::BuildBackendSettings;
use uv_configuration::GitLfsSetting;
use uv_distribution_types::{Index, IndexName, RequirementSource};
use uv_fs::{PortablePathBuf, relative_to};
use uv_git_types::GitReference;
use uv_macros::OptionsMetadata;
use uv_normalize::{DefaultGroups, ExtraName, GroupName, PackageName};
use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::MarkerTree;
use uv_pypi_types::{
Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments, VerbatimParsedUrl,
};
use uv_redacted::DisplaySafeUrl;
#[derive(Error, Debug)]
pub enum PyprojectTomlError {
#[error(transparent)]
TomlSyntax(#[from] toml_edit::TomlError),
#[error(transparent)]
TomlSchema(#[from] toml_edit::de::Error),
#[error(
"`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
)]
MissingName,
#[error(
"`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
)]
MissingVersion,
}
/// Helper function to deserialize a map while ensuring all keys are unique.
fn deserialize_unique_map<'de, D, K, V, F>(
deserializer: D,
error_msg: F,
) -> Result<BTreeMap<K, V>, D::Error>
where
D: Deserializer<'de>,
K: Deserialize<'de> + Ord + std::fmt::Display,
V: Deserialize<'de>,
F: FnOnce(&K) -> String,
{
struct Visitor<K, V, F>(F, std::marker::PhantomData<(K, V)>);
impl<'de, K, V, F> serde::de::Visitor<'de> for Visitor<K, V, F>
where
K: Deserialize<'de> + Ord + std::fmt::Display,
V: Deserialize<'de>,
F: FnOnce(&K) -> String,
{
type Value = BTreeMap<K, V>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a map with unique keys")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
use std::collections::btree_map::Entry;
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry::<K, V>()? {
match map.entry(key) {
Entry::Occupied(entry) => {
return Err(serde::de::Error::custom((self.0)(entry.key())));
}
Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
Ok(map)
}
}
deserializer.deserialize_map(Visitor(error_msg, std::marker::PhantomData))
}
/// A `pyproject.toml` as specified in PEP 517.
#[derive(Deserialize, Debug, Clone)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case")]
pub struct PyProjectToml {
/// PEP 621-compliant project metadata.
pub project: Option<Project>,
/// Tool-specific metadata.
pub tool: Option<Tool>,
/// Non-project dependency groups, as defined in PEP 735.
pub dependency_groups: Option<DependencyGroups>,
/// The raw unserialized document.
#[serde(skip)]
pub raw: String,
/// Used to determine whether a `build-system` section is present.
#[serde(default, skip_serializing)]
pub build_system: Option<serde::de::IgnoredAny>,
}
impl PyProjectToml {
/// Parse a `PyProjectToml` from a raw TOML string.
pub fn from_string(raw: String) -> Result<Self, PyprojectTomlError> {
let pyproject =
toml_edit::Document::from_str(&raw).map_err(PyprojectTomlError::TomlSyntax)?;
let pyproject = Self::deserialize(pyproject.into_deserializer())
.map_err(PyprojectTomlError::TomlSchema)?;
Ok(Self { raw, ..pyproject })
}
/// Returns `true` if the project should be considered a Python package, as opposed to a
/// non-package ("virtual") project.
pub fn is_package(&self, require_build_system: bool) -> bool {
// If `tool.uv.package` is set, defer to that explicit setting.
if let Some(is_package) = self.tool_uv_package() {
return is_package;
}
// Otherwise, a project is assumed to be a package if `build-system` is present.
self.build_system.is_some() || !require_build_system
}
/// Returns the value of `tool.uv.package` if set.
fn tool_uv_package(&self) -> Option<bool> {
self.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.package)
}
/// Returns `true` if the project uses a dynamic version.
pub fn is_dynamic(&self) -> bool {
self.project
.as_ref()
.is_some_and(|project| project.version.is_none())
}
/// Returns whether the project manifest contains any script table.
pub fn has_scripts(&self) -> bool {
if let Some(ref project) = self.project {
project.gui_scripts.is_some() || project.scripts.is_some()
} else {
false
}
}
/// Returns the set of conflicts for the project.
pub fn conflicts(&self) -> Conflicts {
let empty = Conflicts::empty();
let Some(project) = self.project.as_ref() else {
return empty;
};
let Some(tool) = self.tool.as_ref() else {
return empty;
};
let Some(tooluv) = tool.uv.as_ref() else {
return empty;
};
let Some(conflicting) = tooluv.conflicts.as_ref() else {
return empty;
};
conflicting.to_conflicts_with_package_name(&project.name)
}
}
// Ignore raw document in comparison.
impl PartialEq for PyProjectToml {
fn eq(&self, other: &Self) -> bool {
self.project.eq(&other.project) && self.tool.eq(&other.tool)
}
}
impl Eq for PyProjectToml {}
impl AsRef<[u8]> for PyProjectToml {
fn as_ref(&self) -> &[u8] {
self.raw.as_bytes()
}
}
/// PEP 621 project metadata (`project`).
///
/// See <https://packaging.python.org/en/latest/specifications/pyproject-toml>.
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
pub struct Project {
/// The name of the project
pub name: PackageName,
/// The version of the project
pub version: Option<Version>,
/// The Python versions this project is compatible with.
pub requires_python: Option<VersionSpecifiers>,
/// The dependencies of the project.
pub dependencies: Option<Vec<String>>,
/// The optional dependencies of the project.
pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
/// Used to determine whether a `gui-scripts` section is present.
#[serde(default, skip_serializing)]
pub(crate) gui_scripts: Option<serde::de::IgnoredAny>,
/// Used to determine whether a `scripts` section is present.
#[serde(default, skip_serializing)]
pub(crate) scripts: Option<serde::de::IgnoredAny>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct ProjectWire {
name: Option<PackageName>,
version: Option<Version>,
dynamic: Option<Vec<String>>,
requires_python: Option<VersionSpecifiers>,
dependencies: Option<Vec<String>>,
optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
gui_scripts: Option<serde::de::IgnoredAny>,
scripts: Option<serde::de::IgnoredAny>,
}
impl TryFrom<ProjectWire> for Project {
type Error = PyprojectTomlError;
fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
// If `[project.name]` is not present, show a dedicated error message.
let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
// If `[project.version]` is not present (or listed in `[project.dynamic]`), show a dedicated error message.
if value.version.is_none()
&& !value
.dynamic
.as_ref()
.is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
{
return Err(PyprojectTomlError::MissingVersion);
}
Ok(Self {
name,
version: value.version,
requires_python: value.requires_python,
dependencies: value.dependencies,
optional_dependencies: value.optional_dependencies,
gui_scripts: value.gui_scripts,
scripts: value.scripts,
})
}
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Tool {
pub uv: Option<ToolUv>,
}
/// Validates that index names in the `tool.uv.index` field are unique.
///
/// This custom deserializer function checks for duplicate index names
/// and returns an error if any duplicates are found.
fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
where
D: Deserializer<'de>,
{
let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
if let Some(indexes) = indexes.as_ref() {
let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
for index in indexes {
if let Some(name) = index.name.as_ref() {
if !seen_names.insert(name) {
return Err(serde::de::Error::custom(format!(
"duplicate index name `{name}`"
)));
}
}
}
}
Ok(indexes)
}
// NOTE(charlie): When adding fields to this struct, mark them as ignored on `Options` in
// `crates/uv-settings/src/settings.rs`.
#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUv {
/// The sources to use when resolving dependencies.
///
/// `tool.uv.sources` enriches the dependency metadata with additional sources, incorporated
/// during development. A dependency source can be a Git repository, a URL, a local path, or an
/// alternative registry.
///
/// See [Dependencies](../concepts/projects/dependencies.md) for more.
#[option(
default = "{}",
value_type = "dict",
example = r#"
[tool.uv.sources]
httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
pydantic = { path = "/path/to/pydantic", editable = true }
"#
)]
pub sources: Option<ToolUvSources>,
/// The indexes to use when resolving dependencies.
///
/// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
/// (the simple repository API), or a local directory laid out in the same format.
///
/// Indexes are considered in the order in which they're defined, such that the first-defined
/// index has the highest priority. Further, the indexes provided by this setting are given
/// higher priority than any indexes specified via [`index_url`](#index-url) or
/// [`extra_index_url`](#extra-index-url). uv will only consider the first index that contains
/// a given package, unless an alternative [index strategy](#index-strategy) is specified.
///
/// If an index is marked as `explicit = true`, it will be used exclusively for the
/// dependencies that select it explicitly via `[tool.uv.sources]`, as in:
///
/// ```toml
/// [[tool.uv.index]]
/// name = "pytorch"
/// url = "https://download.pytorch.org/whl/cu121"
/// explicit = true
///
/// [tool.uv.sources]
/// torch = { index = "pytorch" }
/// ```
///
/// If an index is marked as `default = true`, it will be moved to the end of the prioritized list, such that it is
/// given the lowest priority when resolving packages. Additionally, marking an index as default will disable the
/// PyPI default index.
#[option(
default = "[]",
value_type = "dict",
example = r#"
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cu121"
"#
)]
#[serde(deserialize_with = "deserialize_index_vec", default)]
pub index: Option<Vec<Index>>,
/// The workspace definition for the project, if any.
#[option_group]
pub workspace: Option<ToolUvWorkspace>,
/// Whether the project is managed by uv. If `false`, uv will ignore the project when
/// `uv run` is invoked.
#[option(
default = r#"true"#,
value_type = "bool",
example = r#"
managed = false
"#
)]
pub managed: Option<bool>,
/// Whether the project should be considered a Python package, or a non-package ("virtual")
/// project.
///
/// Packages are built and installed into the virtual environment in editable mode and thus
/// require a build backend, while virtual projects are _not_ built or installed; instead, only
/// their dependencies are included in the virtual environment.
///
/// Creating a package requires that a `build-system` is present in the `pyproject.toml`, and
/// that the project adheres to a structure that adheres to the build backend's expectations
/// (e.g., a `src` layout).
#[option(
default = r#"true"#,
value_type = "bool",
example = r#"
package = false
"#
)]
pub package: Option<bool>,
/// The list of `dependency-groups` to install by default.
///
/// Can also be the literal `"all"` to default enable all groups.
#[option(
default = r#"["dev"]"#,
value_type = r#"str | list[str]"#,
example = r#"
default-groups = ["docs"]
"#
)]
pub default_groups: Option<DefaultGroups>,
/// Additional settings for `dependency-groups`.
///
/// Currently this can only be used to add `requires-python` constraints
/// to dependency groups (typically to inform uv that your dev tooling
/// has a higher python requirement than your actual project).
///
/// This cannot be used to define dependency groups, use the top-level
/// `[dependency-groups]` table for that.
#[option(
default = "[]",
value_type = "dict",
example = r#"
[tool.uv.dependency-groups]
my-group = {requires-python = ">=3.12"}
"#
)]
pub dependency_groups: Option<ToolUvDependencyGroups>,
/// The project's development dependencies.
///
/// Development dependencies will be installed by default in `uv run` and `uv sync`, but will
/// not appear in the project's published metadata.
///
/// Use of this field is not recommend anymore. Instead, use the `dependency-groups.dev` field
/// which is a standardized way to declare development dependencies. The contents of
/// `tool.uv.dev-dependencies` and `dependency-groups.dev` are combined to determine the final
/// requirements of the `dev` dependency group.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
dev-dependencies = ["ruff==0.5.0"]
"#
)]
pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Overrides to apply when resolving the project's dependencies.
///
/// Overrides are used to force selection of a specific version of a package, regardless of the
/// version requested by any other package, and regardless of whether choosing that version
/// would typically constitute an invalid resolution.
///
/// While constraints are _additive_, in that they're combined with the requirements of the
/// constituent packages, overrides are _absolute_, in that they completely replace the
/// requirements of any constituent packages.
///
/// Including a package as an override will _not_ trigger installation of the package on its
/// own; instead, the package must be requested elsewhere in the project's first-party or
/// transitive dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `override-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Always install Werkzeug 2.3.0, regardless of whether transitive dependencies request
# a different version.
override-dependencies = ["werkzeug==2.3.0"]
"#
)]
pub override_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Dependencies to exclude when resolving the project's dependencies.
///
/// Excludes are used to prevent a package from being selected during resolution,
/// regardless of whether it's requested by any other package. When a package is excluded,
/// it will be omitted from the dependency list entirely.
///
/// Including a package as an exclusion will prevent it from being installed, even if
/// it's requested by transitive dependencies. This can be useful for removing optional
/// dependencies or working around packages with broken dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `exclude-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "Package names to exclude, e.g., `werkzeug`, `numpy`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Exclude Werkzeug from being installed, even if transitive dependencies request it.
exclude-dependencies = ["werkzeug"]
"#
)]
pub exclude_dependencies: Option<Vec<PackageName>>,
/// Constraints to apply when resolving the project's dependencies.
///
/// Constraints are used to restrict the versions of dependencies that are selected during
/// resolution.
///
/// Including a package as a constraint will _not_ trigger installation of the package on its
/// own; instead, the package must be requested elsewhere in the project's first-party or
/// transitive dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `constraint-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Ensure that the grpcio version is always less than 1.65, if it's requested by a
# direct or transitive dependency.
constraint-dependencies = ["grpcio<1.65"]
"#
)]
pub constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Constraints to apply when solving build dependencies.
///
/// Build constraints are used to restrict the versions of build dependencies that are selected
/// when building a package during resolution or installation.
///
/// Including a package as a constraint will _not_ trigger installation of the package during
/// a build; instead, the package must be requested elsewhere in the project's build dependency
/// graph.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `build-constraint-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
# on setuptools.
build-constraint-dependencies = ["setuptools==60.0.0"]
"#
)]
pub build_constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// A list of supported environments against which to resolve dependencies.
///
/// By default, uv will resolve for all possible environments during a `uv lock` operation.
/// However, you can restrict the set of supported environments to improve performance and avoid
/// unsatisfiable branches in the solution space.
///
/// These environments will also be respected when `uv pip compile` is invoked with the
/// `--universal` flag.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "A list of environment markers, e.g., `python_version >= '3.6'`."
)
)]
#[option(
default = "[]",
value_type = "str | list[str]",
example = r#"
# Resolve for macOS, but not for Linux or Windows.
environments = ["sys_platform == 'darwin'"]
"#
)]
pub environments: Option<SupportedEnvironments>,
/// A list of required platforms, for packages that lack source distributions.
///
/// When a package does not have a source distribution, it's availability will be limited to
/// the platforms supported by its built distributions (wheels). For example, if a package only
/// publishes wheels for Linux, then it won't be installable on macOS or Windows.
///
/// By default, uv requires each package to include at least one wheel that is compatible with
/// the designated Python version. The `required-environments` setting can be used to ensure that
/// the resulting resolution contains wheels for specific platforms, or fails if no such wheels
/// are available.
///
/// While the `environments` setting _limits_ the set of environments that uv will consider when
/// resolving dependencies, `required-environments` _expands_ the set of platforms that uv _must_
/// support when resolving dependencies.
///
/// For example, `environments = ["sys_platform == 'darwin'"]` would limit uv to solving for
/// macOS (and ignoring Linux and Windows). On the other hand, `required-environments = ["sys_platform == 'darwin'"]`
/// would _require_ that any package without a source distribution include a wheel for macOS in
/// order to be installable.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
)
)]
#[option(
default = "[]",
value_type = "str | list[str]",
example = r#"
# Require that the package is available for macOS ARM and x86 (Intel).
required-environments = [
"sys_platform == 'darwin' and platform_machine == 'arm64'",
"sys_platform == 'darwin' and platform_machine == 'x86_64'",
]
"#
)]
pub required_environments: Option<SupportedEnvironments>,
/// Declare collections of extras or dependency groups that are conflicting
/// (i.e., mutually exclusive).
///
/// It's useful to declare conflicts when two or more extras have mutually
/// incompatible dependencies. For example, extra `foo` might depend
/// on `numpy==2.0.0` while extra `bar` depends on `numpy==2.1.0`. While these
/// dependencies conflict, it may be the case that users are not expected to
/// activate both `foo` and `bar` at the same time, making it possible to
/// generate a universal resolution for the project despite the incompatibility.
///
/// By making such conflicts explicit, uv can generate a universal resolution
/// for a project, taking into account that certain combinations of extras and
/// groups are mutually exclusive. In exchange, installation will fail if a
/// user attempts to activate both conflicting extras.
#[cfg_attr(
feature = "schemars",
schemars(description = "A list of sets of conflicting groups or extras.")
)]
#[option(
default = r#"[]"#,
value_type = "list[list[dict]]",
example = r#"
# Require that `package[extra1]` and `package[extra2]` are resolved
# in different forks so that they cannot conflict with one another.
conflicts = [
[
{ extra = "extra1" },
{ extra = "extra2" },
]
]
# Require that the dependency groups `group1` and `group2`
# are resolved in different forks so that they cannot conflict
# with one another.
conflicts = [
[
{ group = "group1" },
{ group = "group2" },
]
]
"#
)]
pub conflicts: Option<SchemaConflicts>,
// Only exists on this type for schema and docs generation, the build backend settings are
// never merged in a workspace and read separately by the backend code.
/// Configuration for the uv build backend.
///
/// Note that those settings only apply when using the `uv_build` backend, other build backends
/// (such as hatchling) have their own configuration.
#[option_group]
pub build_backend: Option<BuildBackendSettingsSchema>,
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
impl ToolUvSources {
/// Returns the underlying `BTreeMap` of package names to sources.
pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
&self.0
}
/// Convert the [`ToolUvSources`] into its inner `BTreeMap`.
#[must_use]
pub fn into_inner(self) -> BTreeMap<PackageName, Sources> {
self.0
}
}
/// Ensure that all keys in the TOML table are unique.
impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_unique_map(deserializer, |key: &PackageName| {
format!("duplicate sources for package `{key}`")
})
.map(ToolUvSources)
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
impl ToolUvDependencyGroups {
/// Returns the underlying `BTreeMap` of group names to settings.
pub fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
&self.0
}
/// Convert the [`ToolUvDependencyGroups`] into its inner `BTreeMap`.
#[must_use]
pub fn into_inner(self) -> BTreeMap<GroupName, DependencyGroupSettings> {
self.0
}
}
/// Ensure that all keys in the TOML table are unique.
impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_unique_map(deserializer, |key: &GroupName| {
format!("duplicate settings for dependency group `{key}`")
})
.map(ToolUvDependencyGroups)
}
}
#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub struct DependencyGroupSettings {
/// Version of python to require when installing this group
#[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
pub requires_python: Option<VersionSpecifiers>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ExtraBuildDependencyWire {
Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
#[serde(rename_all = "kebab-case")]
Annotated {
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
match_runtime: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
deny_unknown_fields,
from = "ExtraBuildDependencyWire",
into = "ExtraBuildDependencyWire"
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ExtraBuildDependency {
pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
pub match_runtime: bool,
}
impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
fn from(value: ExtraBuildDependency) -> Self {
value.requirement
}
}
impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
fn from(wire: ExtraBuildDependencyWire) -> Self {
match wire {
ExtraBuildDependencyWire::Unannotated(requirement) => Self {
requirement,
match_runtime: false,
},
ExtraBuildDependencyWire::Annotated {
requirement,
match_runtime,
} => Self {
requirement,
match_runtime,
},
}
}
}
impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
fn from(item: ExtraBuildDependency) -> Self {
Self::Annotated {
requirement: item.requirement,
match_runtime: item.match_runtime,
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
impl std::ops::Deref for ExtraBuildDependencies {
type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ExtraBuildDependencies {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for ExtraBuildDependencies {
type Item = (PackageName, Vec<ExtraBuildDependency>);
type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
iter: T,
) -> Self {
| 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-workspace/src/workspace.rs | crates/uv-workspace/src/workspace.rs | //! Resolve the current [`ProjectWorkspace`] or [`Workspace`].
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use glob::{GlobError, PatternError, glob};
use itertools::Itertools;
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::{debug, trace, warn};
use uv_configuration::DependencyGroupsWithDefaults;
use uv_distribution_types::{Index, Requirement, RequirementSource};
use uv_fs::{CWD, Simplified};
use uv_normalize::{DEV_DEPENDENCIES, GroupName, PackageName};
use uv_pep440::VersionSpecifiers;
use uv_pep508::{MarkerTree, VerbatimUrl};
use uv_pypi_types::{Conflicts, SupportedEnvironments, VerbatimParsedUrl};
use uv_static::EnvVars;
use uv_warnings::warn_user_once;
use crate::dependency_groups::{DependencyGroupError, FlatDependencyGroup, FlatDependencyGroups};
use crate::pyproject::{
Project, PyProjectToml, PyprojectTomlError, Source, Sources, ToolUvSources, ToolUvWorkspace,
};
type WorkspaceMembers = Arc<BTreeMap<PackageName, WorkspaceMember>>;
/// Cache key for workspace discovery.
///
/// Given this key, the discovered workspace member list is the same.
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
struct WorkspaceCacheKey {
workspace_root: PathBuf,
discovery_options: DiscoveryOptions,
}
/// Cache for workspace discovery.
///
/// Avoid re-reading the `pyproject.toml` files in a workspace for each member by caching the
/// workspace members by their workspace root.
#[derive(Debug, Default, Clone)]
pub struct WorkspaceCache(Arc<Mutex<FxHashMap<WorkspaceCacheKey, WorkspaceMembers>>>);
#[derive(thiserror::Error, Debug)]
pub enum WorkspaceError {
// Workspace structure errors.
#[error("No `pyproject.toml` found in current directory or any parent directory")]
MissingPyprojectToml,
#[error("Workspace member `{}` is missing a `pyproject.toml` (matches: `{}`)", _0.simplified_display(), _1)]
MissingPyprojectTomlMember(PathBuf, String),
#[error("No `project` table found in: `{}`", _0.simplified_display())]
MissingProject(PathBuf),
#[error("No workspace found for: `{}`", _0.simplified_display())]
MissingWorkspace(PathBuf),
#[error("The project is marked as unmanaged: `{}`", _0.simplified_display())]
NonWorkspace(PathBuf),
#[error("Nested workspaces are not supported, but workspace member (`{}`) has a `uv.workspace` table", _0.simplified_display())]
NestedWorkspace(PathBuf),
#[error("Two workspace members are both named `{name}`: `{}` and `{}`", first.simplified_display(), second.simplified_display())]
DuplicatePackage {
name: PackageName,
first: PathBuf,
second: PathBuf,
},
#[error("pyproject.toml section is declared as dynamic, but must be static: `{0}`")]
DynamicNotAllowed(&'static str),
#[error(
"Workspace member `{}` was requested as both `editable = true` and `editable = false`",
_0
)]
EditableConflict(PackageName),
#[error("Failed to find directories for glob: `{0}`")]
Pattern(String, #[source] PatternError),
// Syntax and other errors.
#[error("Directory walking failed for `tool.uv.workspace.members` glob: `{0}`")]
GlobWalk(String, #[source] GlobError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("Failed to parse: `{}`", _0.user_display())]
Toml(PathBuf, #[source] Box<PyprojectTomlError>),
#[error("Failed to normalize workspace member path")]
Normalize(#[source] std::io::Error),
}
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
pub enum MemberDiscovery {
/// Discover all workspace members.
#[default]
All,
/// Don't discover any workspace members.
None,
/// Discover workspace members, but ignore the given paths.
Ignore(BTreeSet<PathBuf>),
}
/// Whether a "project" must be defined via a `[project]` table.
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
pub enum ProjectDiscovery {
/// The `[project]` table is optional; when missing, the target is treated as virtual.
#[default]
Optional,
/// A `[project]` table must be defined, unless `[tool.uv.workspace]` is present indicating a
/// legacy non-project workspace root.
///
/// If neither is defined, discovery will fail.
Legacy,
/// A `[project]` table must be defined.
///
/// If not defined, discovery will fail.
Required,
}
impl ProjectDiscovery {
/// Whether a `[project]` table is required.
pub fn allows_implicit_workspace(&self) -> bool {
match self {
Self::Optional => true,
Self::Legacy => false,
Self::Required => false,
}
}
/// Whether a legacy workspace root is allowed.
pub fn allows_legacy_workspace(&self) -> bool {
match self {
Self::Optional => true,
Self::Legacy => true,
Self::Required => false,
}
}
}
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
pub struct DiscoveryOptions {
/// The path to stop discovery at.
pub stop_discovery_at: Option<PathBuf>,
/// The strategy to use when discovering workspace members.
pub members: MemberDiscovery,
/// The strategy to use when discovering the project.
pub project: ProjectDiscovery,
}
pub type RequiresPythonSources = BTreeMap<(PackageName, Option<GroupName>), VersionSpecifiers>;
pub type Editability = Option<bool>;
/// A workspace, consisting of a root directory and members. See [`ProjectWorkspace`].
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(serde::Serialize))]
pub struct Workspace {
/// The path to the workspace root.
///
/// The workspace root is the directory containing the top level `pyproject.toml` with
/// the `uv.tool.workspace`, or the `pyproject.toml` in an implicit single workspace project.
install_path: PathBuf,
/// The members of the workspace.
packages: WorkspaceMembers,
/// The workspace members that are required by other members, and whether they were requested
/// as editable.
required_members: BTreeMap<PackageName, Editability>,
/// The sources table from the workspace `pyproject.toml`.
///
/// This table is overridden by the project sources.
sources: BTreeMap<PackageName, Sources>,
/// The index table from the workspace `pyproject.toml`.
///
/// This table is overridden by the project indexes.
indexes: Vec<Index>,
/// The `pyproject.toml` of the workspace root.
pyproject_toml: PyProjectToml,
}
impl Workspace {
/// Find the workspace containing the given path.
///
/// Unlike the [`ProjectWorkspace`] discovery, this does not require a current project. It also
/// always uses absolute path, i.e., this method only supports discovering the main workspace.
///
/// Steps of workspace discovery: Start by looking at the closest `pyproject.toml`:
/// * If it's an explicit workspace root: Collect workspace from this root, we're done.
/// * If it's also not a project: Error, must be either a workspace root or a project.
/// * Otherwise, try to find an explicit workspace root above:
/// * If an explicit workspace root exists: Collect workspace from this root, we're done.
/// * If there is no explicit workspace: We have a single project workspace, we're done.
///
/// Note that there are two kinds of workspace roots: projects, and (legacy) non-project roots.
/// The non-project roots lack a `[project]` table, and so are not themselves projects, as in:
/// ```toml
/// [tool.uv.workspace]
/// members = ["packages/*"]
///
/// [tool.uv]
/// dev-dependencies = ["ruff"]
/// ```
pub async fn discover(
path: &Path,
options: &DiscoveryOptions,
cache: &WorkspaceCache,
) -> Result<Self, WorkspaceError> {
let path = std::path::absolute(path)
.map_err(WorkspaceError::Normalize)?
.clone();
// Remove `.` and `..`
let path = uv_fs::normalize_path(&path);
// Trim trailing slashes.
let path = path.components().collect::<PathBuf>();
let project_path = path
.ancestors()
.find(|path| path.join("pyproject.toml").is_file())
.ok_or(WorkspaceError::MissingPyprojectToml)?
.to_path_buf();
let pyproject_path = project_path.join("pyproject.toml");
let contents = fs_err::tokio::read_to_string(&pyproject_path).await?;
let pyproject_toml = PyProjectToml::from_string(contents)
.map_err(|err| WorkspaceError::Toml(pyproject_path.clone(), Box::new(err)))?;
// Check if the project is explicitly marked as unmanaged.
if pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.managed)
== Some(false)
{
debug!(
"Project `{}` is marked as unmanaged",
project_path.simplified_display()
);
return Err(WorkspaceError::NonWorkspace(project_path));
}
// Check if the current project is also an explicit workspace root.
let explicit_root = pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.workspace.as_ref())
.map(|workspace| {
(
project_path.clone(),
workspace.clone(),
pyproject_toml.clone(),
)
});
let (workspace_root, workspace_definition, workspace_pyproject_toml) =
if let Some(workspace) = explicit_root {
// We have found the explicit root immediately.
workspace
} else if pyproject_toml.project.is_none() {
// Without a project, it can't be an implicit root
return Err(WorkspaceError::MissingProject(pyproject_path));
} else if let Some(workspace) = find_workspace(&project_path, options).await? {
// We have found an explicit root above.
workspace
} else {
// Support implicit single project workspaces.
(
project_path.clone(),
ToolUvWorkspace::default(),
pyproject_toml.clone(),
)
};
debug!(
"Found workspace root: `{}`",
workspace_root.simplified_display()
);
// Unlike in `ProjectWorkspace` discovery, we might be in a legacy non-project root without
// being in any specific project.
let current_project = pyproject_toml
.project
.clone()
.map(|project| WorkspaceMember {
root: project_path,
project,
pyproject_toml,
});
Self::collect_members(
workspace_root.clone(),
workspace_definition,
workspace_pyproject_toml,
current_project,
options,
cache,
)
.await
}
/// Set the current project to the given workspace member.
///
/// Returns `None` if the package is not part of the workspace.
pub fn with_current_project(self, package_name: PackageName) -> Option<ProjectWorkspace> {
let member = self.packages.get(&package_name)?;
Some(ProjectWorkspace {
project_root: member.root().clone(),
project_name: package_name,
workspace: self,
})
}
/// Set the [`ProjectWorkspace`] for a given workspace member.
///
/// Assumes that the project name is unchanged in the updated [`PyProjectToml`].
pub fn with_pyproject_toml(
self,
package_name: &PackageName,
pyproject_toml: PyProjectToml,
) -> Result<Option<Self>, WorkspaceError> {
let mut packages = self.packages;
let Some(member) = Arc::make_mut(&mut packages).get_mut(package_name) else {
return Ok(None);
};
if member.root == self.install_path {
// If the member is also the workspace root, update _both_ the member entry and the
// root `pyproject.toml`.
let workspace_pyproject_toml = pyproject_toml.clone();
// Refresh the workspace sources.
let workspace_sources = workspace_pyproject_toml
.tool
.clone()
.and_then(|tool| tool.uv)
.and_then(|uv| uv.sources)
.map(ToolUvSources::into_inner)
.unwrap_or_default();
// Set the `pyproject.toml` for the member.
member.pyproject_toml = pyproject_toml;
// Recompute required_members with the updated data
let required_members = Self::collect_required_members(
&packages,
&workspace_sources,
&workspace_pyproject_toml,
)?;
Ok(Some(Self {
pyproject_toml: workspace_pyproject_toml,
sources: workspace_sources,
packages,
required_members,
..self
}))
} else {
// Set the `pyproject.toml` for the member.
member.pyproject_toml = pyproject_toml;
// Recompute required_members with the updated member data
let required_members =
Self::collect_required_members(&packages, &self.sources, &self.pyproject_toml)?;
Ok(Some(Self {
packages,
required_members,
..self
}))
}
}
/// Returns `true` if the workspace has a (legacy) non-project root.
pub fn is_non_project(&self) -> bool {
!self
.packages
.values()
.any(|member| *member.root() == self.install_path)
}
/// Returns the set of all workspace members.
pub fn members_requirements(&self) -> impl Iterator<Item = Requirement> + '_ {
self.packages.iter().filter_map(|(name, member)| {
let url = VerbatimUrl::from_absolute_path(&member.root)
.expect("path is valid URL")
.with_given(member.root.to_string_lossy());
Some(Requirement {
name: member.pyproject_toml.project.as_ref()?.name.clone(),
extras: Box::new([]),
groups: Box::new([]),
marker: MarkerTree::TRUE,
source: if member
.pyproject_toml()
.is_package(!self.is_required_member(name))
{
RequirementSource::Directory {
install_path: member.root.clone().into_boxed_path(),
editable: Some(
self.required_members
.get(name)
.copied()
.flatten()
.unwrap_or(true),
),
r#virtual: Some(false),
url,
}
} else {
RequirementSource::Directory {
install_path: member.root.clone().into_boxed_path(),
editable: Some(false),
r#virtual: Some(true),
url,
}
},
origin: None,
})
})
}
/// The workspace members that are required my another member of the workspace.
pub fn required_members(&self) -> &BTreeMap<PackageName, Editability> {
&self.required_members
}
/// Compute the workspace members that are required by another member of the workspace, and
/// determine whether they should be installed as editable or non-editable.
///
/// N.B. this checks if a workspace member is required by inspecting `tool.uv.source` entries,
/// but does not actually check if the source is _used_, which could result in false positives
/// but is easier to compute.
fn collect_required_members(
packages: &BTreeMap<PackageName, WorkspaceMember>,
sources: &BTreeMap<PackageName, Sources>,
pyproject_toml: &PyProjectToml,
) -> Result<BTreeMap<PackageName, Editability>, WorkspaceError> {
let mut required_members = BTreeMap::new();
for (package, sources) in sources
.iter()
.filter(|(name, _)| {
pyproject_toml
.project
.as_ref()
.is_none_or(|project| project.name != **name)
})
.chain(
packages
.iter()
.filter_map(|(name, member)| {
member
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.map(move |sources| {
sources
.iter()
.filter(move |(source_name, _)| name != *source_name)
})
})
.flatten(),
)
{
for source in sources.iter() {
let Source::Workspace { editable, .. } = &source else {
continue;
};
let existing = required_members.insert(package.clone(), *editable);
if let Some(Some(existing)) = existing {
if let Some(editable) = editable {
// If there are conflicting `editable` values, raise an error.
if existing != *editable {
return Err(WorkspaceError::EditableConflict(package.clone()));
}
}
}
}
}
Ok(required_members)
}
/// Whether a given workspace member is required by another member.
pub fn is_required_member(&self, name: &PackageName) -> bool {
self.required_members().contains_key(name)
}
/// Returns the set of all workspace member dependency groups.
pub fn group_requirements(&self) -> impl Iterator<Item = Requirement> + '_ {
self.packages.iter().filter_map(|(name, member)| {
let url = VerbatimUrl::from_absolute_path(&member.root)
.expect("path is valid URL")
.with_given(member.root.to_string_lossy());
let groups = {
let mut groups = member
.pyproject_toml
.dependency_groups
.as_ref()
.map(|groups| groups.keys().cloned().collect::<Vec<_>>())
.unwrap_or_default();
if member
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.dev_dependencies.as_ref())
.is_some()
{
groups.push(DEV_DEPENDENCIES.clone());
groups.sort_unstable();
}
groups
};
if groups.is_empty() {
return None;
}
let value = self.required_members.get(name);
let is_required_member = value.is_some();
let editability = value.copied().flatten();
Some(Requirement {
name: member.pyproject_toml.project.as_ref()?.name.clone(),
extras: Box::new([]),
groups: groups.into_boxed_slice(),
marker: MarkerTree::TRUE,
source: if member.pyproject_toml().is_package(!is_required_member) {
RequirementSource::Directory {
install_path: member.root.clone().into_boxed_path(),
editable: Some(editability.unwrap_or(true)),
r#virtual: Some(false),
url,
}
} else {
RequirementSource::Directory {
install_path: member.root.clone().into_boxed_path(),
editable: Some(false),
r#virtual: Some(true),
url,
}
},
origin: None,
})
})
}
/// Returns the set of supported environments for the workspace.
pub fn environments(&self) -> Option<&SupportedEnvironments> {
self.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.environments.as_ref())
}
/// Returns the set of required platforms for the workspace.
pub fn required_environments(&self) -> Option<&SupportedEnvironments> {
self.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.required_environments.as_ref())
}
/// Returns the set of conflicts for the workspace.
pub fn conflicts(&self) -> Conflicts {
let mut conflicting = Conflicts::empty();
for member in self.packages.values() {
conflicting.append(&mut member.pyproject_toml.conflicts());
}
conflicting
}
/// Returns an iterator over the `requires-python` values for each member of the workspace.
pub fn requires_python(
&self,
groups: &DependencyGroupsWithDefaults,
) -> Result<RequiresPythonSources, DependencyGroupError> {
let mut requires = RequiresPythonSources::new();
for (name, member) in self.packages() {
// Get the top-level requires-python for this package, which is always active
//
// Arguably we could check groups.prod() to disable this, since, the requires-python
// of the project is *technically* not relevant if you're doing `--only-group`, but,
// that would be a big surprising change so let's *not* do that until someone asks!
let top_requires = member
.pyproject_toml()
.project
.as_ref()
.and_then(|project| project.requires_python.as_ref())
.map(|requires_python| ((name.to_owned(), None), requires_python.clone()));
requires.extend(top_requires);
// Get the requires-python for each enabled group on this package
// We need to do full flattening here because include-group can transfer requires-python
let dependency_groups =
FlatDependencyGroups::from_pyproject_toml(member.root(), &member.pyproject_toml)?;
let group_requires =
dependency_groups
.into_iter()
.filter_map(move |(group_name, flat_group)| {
if groups.contains(&group_name) {
flat_group.requires_python.map(|requires_python| {
((name.to_owned(), Some(group_name)), requires_python)
})
} else {
None
}
});
requires.extend(group_requires);
}
Ok(requires)
}
/// Returns any requirements that are exclusive to the workspace root, i.e., not included in
/// any of the workspace members.
///
/// For now, there are no such requirements.
pub fn requirements(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
Vec::new()
}
/// Returns any dependency groups that are exclusive to the workspace root, i.e., not included
/// in any of the workspace members.
///
/// For workspaces with non-`[project]` roots, returns the dependency groups defined in the
/// corresponding `pyproject.toml`.
///
/// Otherwise, returns an empty list.
pub fn workspace_dependency_groups(
&self,
) -> Result<BTreeMap<GroupName, FlatDependencyGroup>, DependencyGroupError> {
if self
.packages
.values()
.any(|member| *member.root() == self.install_path)
{
// If the workspace has an explicit root, the root is a member, so we don't need to
// include any root-only requirements.
Ok(BTreeMap::default())
} else {
// Otherwise, return the dependency groups in the non-project workspace root.
let dependency_groups = FlatDependencyGroups::from_pyproject_toml(
&self.install_path,
&self.pyproject_toml,
)?;
Ok(dependency_groups.into_inner())
}
}
/// Returns the set of overrides for the workspace.
pub fn overrides(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
let Some(overrides) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.override_dependencies.as_ref())
else {
return vec![];
};
overrides.clone()
}
/// Returns the set of dependency exclusions for the workspace.
pub fn exclude_dependencies(&self) -> Vec<uv_normalize::PackageName> {
let Some(excludes) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.exclude_dependencies.as_ref())
else {
return vec![];
};
excludes.clone()
}
/// Returns the set of constraints for the workspace.
pub fn constraints(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
let Some(constraints) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.constraint_dependencies.as_ref())
else {
return vec![];
};
constraints.clone()
}
/// Returns the set of build constraints for the workspace.
pub fn build_constraints(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
let Some(build_constraints) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.build_constraint_dependencies.as_ref())
else {
return vec![];
};
build_constraints.clone()
}
/// The path to the workspace root, the directory containing the top level `pyproject.toml` with
/// the `uv.tool.workspace`, or the `pyproject.toml` in an implicit single workspace project.
pub fn install_path(&self) -> &PathBuf {
&self.install_path
}
/// The path to the workspace virtual environment.
///
/// Uses `.venv` in the install path directory by default.
///
/// If `UV_PROJECT_ENVIRONMENT` is set, it will take precedence. If a relative path is provided,
/// it is resolved relative to the install path.
///
/// If `active` is `true`, the `VIRTUAL_ENV` variable will be preferred. If it is `false`, any
/// warnings about mismatch between the active environment and the project environment will be
/// silenced.
pub fn venv(&self, active: Option<bool>) -> PathBuf {
/// Resolve the `UV_PROJECT_ENVIRONMENT` value, if any.
fn from_project_environment_variable(workspace: &Workspace) -> Option<PathBuf> {
let value = std::env::var_os(EnvVars::UV_PROJECT_ENVIRONMENT)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() {
return Some(path);
}
// Resolve the path relative to the install path.
Some(workspace.install_path.join(path))
}
/// Resolve the `VIRTUAL_ENV` variable, if any.
fn from_virtual_env_variable() -> Option<PathBuf> {
let value = std::env::var_os(EnvVars::VIRTUAL_ENV)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() {
return Some(path);
}
// Resolve the path relative to current directory.
// Note this differs from `UV_PROJECT_ENVIRONMENT`
Some(CWD.join(path))
}
// Determine the default value
let project_env = from_project_environment_variable(self)
.unwrap_or_else(|| self.install_path.join(".venv"));
// Warn if it conflicts with `VIRTUAL_ENV`
if let Some(from_virtual_env) = from_virtual_env_variable() {
if !uv_fs::is_same_file_allow_missing(&from_virtual_env, &project_env).unwrap_or(false)
{
match active {
Some(true) => {
debug!(
"Using active virtual environment `{}` instead of project environment `{}`",
from_virtual_env.user_display(),
project_env.user_display()
);
return from_virtual_env;
}
Some(false) => {}
None => {
warn_user_once!(
"`VIRTUAL_ENV={}` does not match the project environment path `{}` and will be ignored; use `--active` to target the active environment instead",
from_virtual_env.user_display(),
project_env.user_display()
);
}
}
}
} else {
if active.unwrap_or_default() {
debug!(
"Use of the active virtual environment was requested, but `VIRTUAL_ENV` is not set"
);
}
}
project_env
}
/// The members of the workspace.
pub fn packages(&self) -> &BTreeMap<PackageName, WorkspaceMember> {
&self.packages
}
/// The sources table from the workspace `pyproject.toml`.
pub fn sources(&self) -> &BTreeMap<PackageName, Sources> {
&self.sources
}
/// The index table from the workspace `pyproject.toml`.
pub fn indexes(&self) -> &[Index] {
&self.indexes
}
/// The `pyproject.toml` of the workspace.
pub fn pyproject_toml(&self) -> &PyProjectToml {
&self.pyproject_toml
}
/// Returns `true` if the path is excluded by the workspace.
pub fn excludes(&self, project_path: &Path) -> Result<bool, WorkspaceError> {
if let Some(workspace) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.workspace.as_ref())
{
is_excluded_from_workspace(project_path, &self.install_path, workspace)
} else {
Ok(false)
}
}
/// Returns `true` if the path is included by the workspace.
pub fn includes(&self, project_path: &Path) -> Result<bool, WorkspaceError> {
if let Some(workspace) = self
.pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.workspace.as_ref())
{
is_included_in_workspace(project_path, &self.install_path, workspace)
} else {
Ok(false)
}
}
/// Collect the workspace member projects from the `members` and `excludes` entries.
async fn collect_members(
workspace_root: PathBuf,
workspace_definition: ToolUvWorkspace,
workspace_pyproject_toml: PyProjectToml,
current_project: Option<WorkspaceMember>,
options: &DiscoveryOptions,
cache: &WorkspaceCache,
) -> Result<Self, WorkspaceError> {
let cache_key = WorkspaceCacheKey {
workspace_root: workspace_root.clone(),
discovery_options: options.clone(),
};
| 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-workspace/src/lib.rs | crates/uv-workspace/src/lib.rs | pub use workspace::{
DiscoveryOptions, Editability, MemberDiscovery, ProjectDiscovery, ProjectWorkspace,
RequiresPythonSources, VirtualProject, Workspace, WorkspaceCache, WorkspaceError,
WorkspaceMember,
};
pub mod dependency_groups;
pub mod pyproject;
pub mod pyproject_mut;
mod workspace;
| 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-workspace/src/pyproject_mut.rs | crates/uv-workspace/src/pyproject_mut.rs | use std::fmt::{Display, Formatter};
use std::path::Path;
use std::str::FromStr;
use std::{fmt, iter, mem};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use toml_edit::{
Array, ArrayOfTables, DocumentMut, Formatted, Item, RawString, Table, TomlError, Value,
};
use uv_cache_key::CanonicalUrl;
use uv_distribution_types::Index;
use uv_fs::PortablePath;
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_pep440::{Version, VersionParseError, VersionSpecifier, VersionSpecifiers};
use uv_pep508::{MarkerTree, Requirement, VersionOrUrl};
use uv_redacted::DisplaySafeUrl;
use crate::pyproject::{DependencyType, Source};
/// Raw and mutable representation of a `pyproject.toml`.
///
/// This is useful for operations that require editing an existing `pyproject.toml` while
/// preserving comments and other structure, such as `uv add` and `uv remove`.
pub struct PyProjectTomlMut {
doc: DocumentMut,
target: DependencyTarget,
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Failed to parse `pyproject.toml`")]
Parse(#[from] Box<TomlError>),
#[error("Failed to serialize `pyproject.toml`")]
Serialize(#[from] Box<toml::ser::Error>),
#[error("Failed to deserialize `pyproject.toml`")]
Deserialize(#[from] Box<toml::de::Error>),
#[error("Dependencies in `pyproject.toml` are malformed")]
MalformedDependencies,
#[error("Sources in `pyproject.toml` are malformed")]
MalformedSources,
#[error("Workspace in `pyproject.toml` is malformed")]
MalformedWorkspace,
#[error("Expected a dependency at index {0}")]
MissingDependency(usize),
#[error("Failed to parse `version` field of `pyproject.toml`")]
VersionParse(#[from] VersionParseError),
#[error("Cannot perform ambiguous update; found multiple entries for `{}`:\n{}", package_name, requirements.iter().map(|requirement| format!("- `{requirement}`")).join("\n"))]
Ambiguous {
package_name: PackageName,
requirements: Vec<Requirement>,
},
#[error("Unknown bound king {0}")]
UnknownBoundKind(String),
}
/// The result of editing an array in a TOML document.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ArrayEdit {
/// An existing entry (at the given index) was updated.
Update(usize),
/// A new entry was added at the given index (typically, the end of the array).
Add(usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum CommentType {
/// A comment that appears on its own line.
OwnLine,
/// A comment that appears at the end of a line.
EndOfLine { leading_whitespace: String },
}
#[derive(Debug, Clone)]
struct Comment {
text: String,
kind: CommentType,
}
impl ArrayEdit {
pub fn index(&self) -> usize {
match self {
Self::Update(i) | Self::Add(i) => *i,
}
}
}
/// The default version specifier when adding a dependency.
// While PEP 440 allows an arbitrary number of version digits, the `major` and `minor` build on
// most projects sticking to two or three components and a SemVer-ish versioning system, so can
// bump the major or minor version of a major.minor or major.minor.patch input version.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum AddBoundsKind {
/// Only a lower bound, e.g., `>=1.2.3`.
#[default]
Lower,
/// Allow the same major version, similar to the semver caret, e.g., `>=1.2.3, <2.0.0`.
///
/// Leading zeroes are skipped, e.g. `>=0.1.2, <0.2.0`.
Major,
/// Allow the same minor version, similar to the semver tilde, e.g., `>=1.2.3, <1.3.0`.
///
/// Leading zeroes are skipped, e.g. `>=0.1.2, <0.1.3`.
Minor,
/// Pin the exact version, e.g., `==1.2.3`.
///
/// This option is not recommended, as versions are already pinned in the uv lockfile.
Exact,
}
impl Display for AddBoundsKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Lower => write!(f, "lower"),
Self::Major => write!(f, "major"),
Self::Minor => write!(f, "minor"),
Self::Exact => write!(f, "exact"),
}
}
}
impl AddBoundsKind {
fn specifiers(self, version: Version) -> VersionSpecifiers {
// Nomenclature: "major" is the most significant component of the version, "minor" is the
// second most significant component, so most versions are either major.minor.patch or
// 0.major.minor.
match self {
Self::Lower => {
VersionSpecifiers::from(VersionSpecifier::greater_than_equal_version(version))
}
Self::Major => {
let leading_zeroes = version
.release()
.iter()
.take_while(|digit| **digit == 0)
.count();
// Special case: The version is 0.
if leading_zeroes == version.release().len() {
let upper_bound = Version::new(
[0, 1]
.into_iter()
.chain(iter::repeat_n(0, version.release().iter().skip(2).len())),
);
return VersionSpecifiers::from_iter([
VersionSpecifier::greater_than_equal_version(version),
VersionSpecifier::less_than_version(upper_bound),
]);
}
// Compute the new major version and pad it to the same length:
// 1.2.3 -> 2.0.0
// 1.2 -> 2.0
// 1 -> 2
// We ignore leading zeroes, adding Semver-style semantics to 0.x versions, too:
// 0.1.2 -> 0.2.0
// 0.0.1 -> 0.0.2
let major = version.release().get(leading_zeroes).copied().unwrap_or(0);
// The length of the lower bound minus the leading zero and bumped component.
let trailing_zeros = version.release().iter().skip(leading_zeroes + 1).len();
let upper_bound = Version::new(
iter::repeat_n(0, leading_zeroes)
.chain(iter::once(major + 1))
.chain(iter::repeat_n(0, trailing_zeros)),
);
VersionSpecifiers::from_iter([
VersionSpecifier::greater_than_equal_version(version),
VersionSpecifier::less_than_version(upper_bound),
])
}
Self::Minor => {
let leading_zeroes = version
.release()
.iter()
.take_while(|digit| **digit == 0)
.count();
// Special case: The version is 0.
if leading_zeroes == version.release().len() {
let upper_bound = [0, 0, 1]
.into_iter()
.chain(iter::repeat_n(0, version.release().iter().skip(3).len()));
return VersionSpecifiers::from_iter([
VersionSpecifier::greater_than_equal_version(version),
VersionSpecifier::less_than_version(Version::new(upper_bound)),
]);
}
// If both major and minor version are 0, the concept of bumping the minor version
// instead of the major version is not useful. Instead, we bump the next
// non-zero part of the version. This avoids extending the three components of 0.0.1
// to the four components of 0.0.1.1.
if leading_zeroes >= 2 {
let most_significant =
version.release().get(leading_zeroes).copied().unwrap_or(0);
// The length of the lower bound minus the leading zero and bumped component.
let trailing_zeros = version.release().iter().skip(leading_zeroes + 1).len();
let upper_bound = Version::new(
iter::repeat_n(0, leading_zeroes)
.chain(iter::once(most_significant + 1))
.chain(iter::repeat_n(0, trailing_zeros)),
);
return VersionSpecifiers::from_iter([
VersionSpecifier::greater_than_equal_version(version),
VersionSpecifier::less_than_version(upper_bound),
]);
}
// Compute the new minor version and pad it to the same length where possible:
// 1.2.3 -> 1.3.0
// 1.2 -> 1.3
// 1 -> 1.1
// We ignore leading zero, adding Semver-style semantics to 0.x versions, too:
// 0.1.2 -> 0.1.3
// 0.0.1 -> 0.0.2
// If the version has only one digit, say `1`, or if there are only leading zeroes,
// pad with zeroes.
let major = version.release().get(leading_zeroes).copied().unwrap_or(0);
let minor = version
.release()
.get(leading_zeroes + 1)
.copied()
.unwrap_or(0);
let upper_bound = Version::new(
iter::repeat_n(0, leading_zeroes)
.chain(iter::once(major))
.chain(iter::once(minor + 1))
.chain(iter::repeat_n(
0,
version.release().iter().skip(leading_zeroes + 2).len(),
)),
);
VersionSpecifiers::from_iter([
VersionSpecifier::greater_than_equal_version(version),
VersionSpecifier::less_than_version(upper_bound),
])
}
Self::Exact => {
VersionSpecifiers::from_iter([VersionSpecifier::equals_version(version)])
}
}
}
}
/// Specifies whether dependencies are added to a script file or a `pyproject.toml` file.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DependencyTarget {
/// A PEP 723 script, with inline metadata.
Script,
/// A project with a `pyproject.toml`.
PyProjectToml,
}
impl PyProjectTomlMut {
/// Initialize a [`PyProjectTomlMut`] from a [`str`].
pub fn from_toml(raw: &str, target: DependencyTarget) -> Result<Self, Error> {
Ok(Self {
doc: raw.parse().map_err(Box::new)?,
target,
})
}
/// Adds a project to the workspace.
pub fn add_workspace(&mut self, path: impl AsRef<Path>) -> Result<(), Error> {
// Get or create `tool.uv.workspace.members`.
let members = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("workspace")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("members")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedWorkspace)?;
// Add the path to the workspace.
members.push(PortablePath::from(path.as_ref()).to_string());
reformat_array_multiline(members);
Ok(())
}
/// Retrieves a mutable reference to the `project` [`Table`] of the TOML document, creating the
/// table if necessary.
///
/// For a script, this returns the root table.
fn project(&mut self) -> Result<&mut Table, Error> {
let doc = match self.target {
DependencyTarget::Script => self.doc.as_table_mut(),
DependencyTarget::PyProjectToml => self
.doc
.entry("project")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedDependencies)?,
};
Ok(doc)
}
/// Retrieves an optional mutable reference to the `project` [`Table`], returning `None` if it
/// doesn't exist.
///
/// For a script, this returns the root table.
fn project_mut(&mut self) -> Result<Option<&mut Table>, Error> {
let doc = match self.target {
DependencyTarget::Script => Some(self.doc.as_table_mut()),
DependencyTarget::PyProjectToml => self
.doc
.get_mut("project")
.map(|project| project.as_table_mut().ok_or(Error::MalformedSources))
.transpose()?,
};
Ok(doc)
}
/// Adds a dependency to `project.dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dependency(
&mut self,
req: &Requirement,
source: Option<&Source>,
raw: bool,
) -> Result<ArrayEdit, Error> {
// Get or create `project.dependencies`.
let dependencies = self
.project()?
.entry("dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let edit = add_dependency(req, dependencies, source.is_some(), raw)?;
if let Some(source) = source {
self.add_source(&req.name, source)?;
}
Ok(edit)
}
/// Adds a development dependency to `tool.uv.dev-dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dev_dependency(
&mut self,
req: &Requirement,
source: Option<&Source>,
raw: bool,
) -> Result<ArrayEdit, Error> {
// Get or create `tool.uv.dev-dependencies`.
let dev_dependencies = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("dev-dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let edit = add_dependency(req, dev_dependencies, source.is_some(), raw)?;
if let Some(source) = source {
self.add_source(&req.name, source)?;
}
Ok(edit)
}
/// Add an [`Index`] to `tool.uv.index`.
pub fn add_index(&mut self, index: &Index) -> Result<(), Error> {
let size = self.doc.len();
let existing = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("index")
.or_insert(Item::ArrayOfTables(ArrayOfTables::new()))
.as_array_of_tables_mut()
.ok_or(Error::MalformedSources)?;
// If there's already an index with the same name or URL, update it (and move it to the top).
let mut table = existing
.iter()
.find(|table| {
// If the index has the same name, reuse it.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_some_and(|name| name == index)
{
return true;
}
}
// If the index is the default, and there's another default index, reuse it.
if index.default
&& table
.get("default")
.is_some_and(|default| default.as_bool() == Some(true))
{
return true;
}
// If there's another index with the same URL, reuse it.
if table
.get("url")
.and_then(|item| item.as_str())
.and_then(|url| DisplaySafeUrl::parse(url).ok())
.is_some_and(|url| {
CanonicalUrl::new(&url) == CanonicalUrl::new(index.url.url())
})
{
return true;
}
false
})
.cloned()
.unwrap_or_default();
// If necessary, update the name.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_none_or(|name| name != index)
{
let mut formatted = Formatted::new(index.to_string());
if let Some(value) = table.get("name").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("name", Value::String(formatted).into());
}
}
// If necessary, update the URL.
if table
.get("url")
.and_then(|item| item.as_str())
.is_none_or(|url| url != index.url.without_credentials().as_str())
{
let mut formatted = Formatted::new(index.url.without_credentials().to_string());
if let Some(value) = table.get("url").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("url", Value::String(formatted).into());
}
// If necessary, update the default.
if index.default {
if !table
.get("default")
.and_then(Item::as_bool)
.is_some_and(|default| default)
{
let mut formatted = Formatted::new(true);
if let Some(value) = table.get("default").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("default", Value::Boolean(formatted).into());
}
}
// Remove any replaced tables.
existing.retain(|table| {
// If the index has the same name, skip it.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_some_and(|name| name == index)
{
return false;
}
}
// If there's another default index, skip it.
if index.default
&& table
.get("default")
.is_some_and(|default| default.as_bool() == Some(true))
{
return false;
}
// If there's another index with the same URL, skip it.
if table
.get("url")
.and_then(|item| item.as_str())
.and_then(|url| DisplaySafeUrl::parse(url).ok())
.is_some_and(|url| CanonicalUrl::new(&url) == CanonicalUrl::new(index.url.url()))
{
return false;
}
true
});
// Set the position to the minimum, if it's not already the first element.
if let Some(min) = existing.iter().filter_map(Table::position).min() {
table.set_position(min);
// Increment the position of all existing elements.
for table in existing.iter_mut() {
if let Some(position) = table.position() {
table.set_position(position + 1);
}
}
} else {
let position = isize::try_from(size).expect("TOML table size fits in `isize`");
table.set_position(position);
}
// Push the item to the table.
existing.push(table);
Ok(())
}
/// Adds a dependency to `project.optional-dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_optional_dependency(
&mut self,
group: &ExtraName,
req: &Requirement,
source: Option<&Source>,
raw: bool,
) -> Result<ArrayEdit, Error> {
// Get or create `project.optional-dependencies`.
let optional_dependencies = self
.project()?
.entry("optional-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
// Try to find the existing group.
let existing_group = optional_dependencies.iter_mut().find_map(|(key, value)| {
if ExtraName::from_str(key.get()).is_ok_and(|g| g == *group) {
Some(value)
} else {
None
}
});
// If the group doesn't exist, create it.
let group = match existing_group {
Some(value) => value,
None => optional_dependencies
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new()))),
}
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let added = add_dependency(req, group, source.is_some(), raw)?;
// If `project.optional-dependencies` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(optional_dependencies) = self
.project()?
.get_mut("optional-dependencies")
.and_then(Item::as_inline_table_mut)
{
optional_dependencies.fmt();
}
if let Some(source) = source {
self.add_source(&req.name, source)?;
}
Ok(added)
}
/// Ensure that an optional dependency group exists, creating an empty group if it doesn't.
pub fn ensure_optional_dependency(&mut self, extra: &ExtraName) -> Result<(), Error> {
// Get or create `project.optional-dependencies`.
let optional_dependencies = self
.project()?
.entry("optional-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
// Check if the extra already exists.
let extra_exists = optional_dependencies
.iter()
.any(|(key, _value)| ExtraName::from_str(key).is_ok_and(|e| e == *extra));
// If the extra doesn't exist, create it.
if !extra_exists {
optional_dependencies.insert(extra.as_ref(), Item::Value(Value::Array(Array::new())));
}
// If `project.optional-dependencies` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(optional_dependencies) = self
.project()?
.get_mut("optional-dependencies")
.and_then(Item::as_inline_table_mut)
{
optional_dependencies.fmt();
}
Ok(())
}
/// Adds a dependency to `dependency-groups`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dependency_group_requirement(
&mut self,
group: &GroupName,
req: &Requirement,
source: Option<&Source>,
raw: bool,
) -> Result<ArrayEdit, Error> {
// Get or create `dependency-groups`.
let dependency_groups = self
.doc
.entry("dependency-groups")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let was_sorted = dependency_groups
.get_values()
.iter()
.filter_map(|(dotted_ks, _)| dotted_ks.first())
.map(|k| k.get())
.is_sorted();
// Try to find the existing group.
let existing_group = dependency_groups.iter_mut().find_map(|(key, value)| {
if GroupName::from_str(key.get()).is_ok_and(|g| g == *group) {
Some(value)
} else {
None
}
});
// If the group doesn't exist, create it.
let group = match existing_group {
Some(value) => value,
None => dependency_groups
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new()))),
}
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let added = add_dependency(req, group, source.is_some(), raw)?;
// To avoid churn in pyproject.toml, we only sort new group keys if the
// existing keys were sorted.
if was_sorted {
dependency_groups.sort_values();
}
// If `dependency-groups` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(dependency_groups) = self
.doc
.get_mut("dependency-groups")
.and_then(Item::as_inline_table_mut)
{
dependency_groups.fmt();
}
if let Some(source) = source {
self.add_source(&req.name, source)?;
}
Ok(added)
}
/// Ensure that a dependency group exists, creating an empty group if it doesn't.
pub fn ensure_dependency_group(&mut self, group: &GroupName) -> Result<(), Error> {
// Get or create `dependency-groups`.
let dependency_groups = self
.doc
.entry("dependency-groups")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let was_sorted = dependency_groups
.get_values()
.iter()
.filter_map(|(dotted_ks, _)| dotted_ks.first())
.map(|k| k.get())
.is_sorted();
// Check if the group already exists.
let group_exists = dependency_groups
.iter()
.any(|(key, _value)| GroupName::from_str(key).is_ok_and(|g| g == *group));
// If the group doesn't exist, create it.
if !group_exists {
dependency_groups.insert(group.as_ref(), Item::Value(Value::Array(Array::new())));
// To avoid churn in pyproject.toml, we only sort new group keys if the
// existing keys were sorted.
if was_sorted {
dependency_groups.sort_values();
}
}
// If `dependency-groups` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(dependency_groups) = self
.doc
.get_mut("dependency-groups")
.and_then(Item::as_inline_table_mut)
{
dependency_groups.fmt();
}
Ok(())
}
/// Set the constraint for a requirement for an existing dependency.
pub fn set_dependency_bound(
&mut self,
dependency_type: &DependencyType,
index: usize,
version: Version,
bound_kind: AddBoundsKind,
) -> Result<(), Error> {
let group = match dependency_type {
DependencyType::Production => self.dependencies_array()?,
DependencyType::Dev => self.dev_dependencies_array()?,
DependencyType::Optional(extra) => self.optional_dependencies_array(extra)?,
DependencyType::Group(group) => self.dependency_groups_array(group)?,
};
let Some(req) = group.get(index) else {
return Err(Error::MissingDependency(index));
};
let mut req = req
.as_str()
.and_then(try_parse_requirement)
.ok_or(Error::MalformedDependencies)?;
req.version_or_url = Some(VersionOrUrl::VersionSpecifier(
bound_kind.specifiers(version),
));
group.replace(index, req.to_string());
Ok(())
}
/// Get the TOML array for `project.dependencies`.
fn dependencies_array(&mut self) -> Result<&mut Array, Error> {
// Get or create `project.dependencies`.
let dependencies = self
.project()?
.entry("dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
Ok(dependencies)
}
/// Get the TOML array for `tool.uv.dev-dependencies`.
fn dev_dependencies_array(&mut self) -> Result<&mut Array, Error> {
// Get or create `tool.uv.dev-dependencies`.
let dev_dependencies = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("dev-dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
Ok(dev_dependencies)
}
/// Get the TOML array for a `project.optional-dependencies` entry.
fn optional_dependencies_array(&mut self, group: &ExtraName) -> Result<&mut Array, Error> {
// Get or create `project.optional-dependencies`.
let optional_dependencies = self
.project()?
.entry("optional-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
// Try to find the existing extra.
let existing_key = optional_dependencies.iter().find_map(|(key, _value)| {
if ExtraName::from_str(key).is_ok_and(|g| g == *group) {
Some(key.to_string())
} else {
None
}
});
// If the group doesn't exist, create it.
let group = optional_dependencies
.entry(existing_key.as_deref().unwrap_or(group.as_ref()))
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
Ok(group)
}
/// Get the TOML array for a `dependency-groups` entry.
fn dependency_groups_array(&mut self, group: &GroupName) -> Result<&mut Array, Error> {
// Get or create `dependency-groups`.
let dependency_groups = self
.doc
.entry("dependency-groups")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
// Try to find the existing group.
let existing_key = dependency_groups.iter().find_map(|(key, _value)| {
if GroupName::from_str(key).is_ok_and(|g| g == *group) {
Some(key.to_string())
| 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-workspace/src/dependency_groups.rs | crates/uv-workspace/src/dependency_groups.rs | use std::collections::btree_map::Entry;
use std::str::FromStr;
use std::{collections::BTreeMap, path::Path};
use thiserror::Error;
use tracing::error;
use uv_distribution_types::RequiresPython;
use uv_fs::Simplified;
use uv_normalize::{DEV_DEPENDENCIES, GroupName};
use uv_pep440::VersionSpecifiers;
use uv_pep508::Pep508Error;
use uv_pypi_types::{DependencyGroupSpecifier, VerbatimParsedUrl};
use crate::pyproject::{DependencyGroupSettings, PyProjectToml, ToolUvDependencyGroups};
/// PEP 735 dependency groups, with any `include-group` entries resolved.
#[derive(Debug, Default, Clone)]
pub struct FlatDependencyGroups(BTreeMap<GroupName, FlatDependencyGroup>);
#[derive(Debug, Default, Clone)]
pub struct FlatDependencyGroup {
pub requirements: Vec<uv_pep508::Requirement<VerbatimParsedUrl>>,
pub requires_python: Option<VersionSpecifiers>,
}
impl FlatDependencyGroups {
/// Gather and flatten all the dependency-groups defined in the given pyproject.toml
///
/// The path is only used in diagnostics.
pub fn from_pyproject_toml(
path: &Path,
pyproject_toml: &PyProjectToml,
) -> Result<Self, DependencyGroupError> {
// First, collect `tool.uv.dev_dependencies`
let dev_dependencies = pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.dev_dependencies.as_ref());
// Then, collect `dependency-groups`
let dependency_groups = pyproject_toml
.dependency_groups
.iter()
.flatten()
.collect::<BTreeMap<_, _>>();
// Get additional settings
let empty_settings = ToolUvDependencyGroups::default();
let group_settings = pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.dependency_groups.as_ref())
.unwrap_or(&empty_settings);
// Flatten the dependency groups.
let mut dependency_groups =
Self::from_dependency_groups(&dependency_groups, group_settings.inner()).map_err(
|err| DependencyGroupError {
package: pyproject_toml
.project
.as_ref()
.map(|project| project.name.to_string())
.unwrap_or_default(),
path: path.user_display().to_string(),
error: err.with_dev_dependencies(dev_dependencies),
},
)?;
// Add the `dev` group, if the legacy `dev-dependencies` is defined.
//
// NOTE: the fact that we do this out here means that nothing can inherit from
// the legacy dev-dependencies group (or define a group requires-python for it).
// This is intentional, we want groups to be defined in a standard interoperable
// way, and letting things include-group a group that isn't defined would be a
// mess for other python tools.
if let Some(dev_dependencies) = dev_dependencies {
dependency_groups
.entry(DEV_DEPENDENCIES.clone())
.or_insert_with(FlatDependencyGroup::default)
.requirements
.extend(dev_dependencies.clone());
}
Ok(dependency_groups)
}
/// Resolve the dependency groups (which may contain references to other groups) into concrete
/// lists of requirements.
fn from_dependency_groups(
groups: &BTreeMap<&GroupName, &Vec<DependencyGroupSpecifier>>,
settings: &BTreeMap<GroupName, DependencyGroupSettings>,
) -> Result<Self, DependencyGroupErrorInner> {
fn resolve_group<'data>(
resolved: &mut BTreeMap<GroupName, FlatDependencyGroup>,
groups: &'data BTreeMap<&GroupName, &Vec<DependencyGroupSpecifier>>,
settings: &BTreeMap<GroupName, DependencyGroupSettings>,
name: &'data GroupName,
parents: &mut Vec<&'data GroupName>,
) -> Result<(), DependencyGroupErrorInner> {
let Some(specifiers) = groups.get(name) else {
// Missing group
let parent_name = parents
.iter()
.last()
.copied()
.expect("parent when group is missing");
return Err(DependencyGroupErrorInner::GroupNotFound(
name.clone(),
parent_name.clone(),
));
};
// "Dependency Group Includes MUST NOT include cycles, and tools SHOULD report an error if they detect a cycle."
if parents.contains(&name) {
return Err(DependencyGroupErrorInner::DependencyGroupCycle(Cycle(
parents.iter().copied().cloned().collect(),
)));
}
// If we already resolved this group, short-circuit.
if resolved.contains_key(name) {
return Ok(());
}
parents.push(name);
let mut requirements = Vec::with_capacity(specifiers.len());
let mut requires_python_intersection = VersionSpecifiers::empty();
for specifier in *specifiers {
match specifier {
DependencyGroupSpecifier::Requirement(requirement) => {
match uv_pep508::Requirement::<VerbatimParsedUrl>::from_str(requirement) {
Ok(requirement) => requirements.push(requirement),
Err(err) => {
return Err(DependencyGroupErrorInner::GroupParseError(
name.clone(),
requirement.clone(),
Box::new(err),
));
}
}
}
DependencyGroupSpecifier::IncludeGroup { include_group } => {
resolve_group(resolved, groups, settings, include_group, parents)?;
if let Some(included) = resolved.get(include_group) {
requirements.extend(included.requirements.iter().cloned());
// Intersect the requires-python for this group with the included group's
requires_python_intersection = requires_python_intersection
.into_iter()
.chain(included.requires_python.clone().into_iter().flatten())
.collect();
}
}
DependencyGroupSpecifier::Object(map) => {
return Err(
DependencyGroupErrorInner::DependencyObjectSpecifierNotSupported(
name.clone(),
map.clone(),
),
);
}
}
}
let empty_settings = DependencyGroupSettings::default();
let DependencyGroupSettings { requires_python } =
settings.get(name).unwrap_or(&empty_settings);
if let Some(requires_python) = requires_python {
// Intersect the requires-python for this group to get the final requires-python
// that will be used by interpreter discovery and checking.
requires_python_intersection = requires_python_intersection
.into_iter()
.chain(requires_python.clone())
.collect();
// Add the group requires-python as a marker to each requirement
// We don't use `requires_python_intersection` because each `include-group`
// should already have its markers applied to these.
for requirement in &mut requirements {
let extra_markers =
RequiresPython::from_specifiers(requires_python).to_marker_tree();
requirement.marker.and(extra_markers);
}
}
parents.pop();
resolved.insert(
name.clone(),
FlatDependencyGroup {
requirements,
requires_python: if requires_python_intersection.is_empty() {
None
} else {
Some(requires_python_intersection)
},
},
);
Ok(())
}
// Validate the settings
for (group_name, ..) in settings {
if !groups.contains_key(group_name) {
return Err(DependencyGroupErrorInner::SettingsGroupNotFound(
group_name.clone(),
));
}
}
let mut resolved = BTreeMap::new();
for name in groups.keys() {
let mut parents = Vec::new();
resolve_group(&mut resolved, groups, settings, name, &mut parents)?;
}
Ok(Self(resolved))
}
/// Return the requirements for a given group, if any.
pub fn get(&self, group: &GroupName) -> Option<&FlatDependencyGroup> {
self.0.get(group)
}
/// Return the entry for a given group, if any.
pub fn entry(&mut self, group: GroupName) -> Entry<'_, GroupName, FlatDependencyGroup> {
self.0.entry(group)
}
/// Consume the [`FlatDependencyGroups`] and return the inner map.
pub fn into_inner(self) -> BTreeMap<GroupName, FlatDependencyGroup> {
self.0
}
}
impl FromIterator<(GroupName, FlatDependencyGroup)> for FlatDependencyGroups {
fn from_iter<T: IntoIterator<Item = (GroupName, FlatDependencyGroup)>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl IntoIterator for FlatDependencyGroups {
type Item = (GroupName, FlatDependencyGroup);
type IntoIter = std::collections::btree_map::IntoIter<GroupName, FlatDependencyGroup>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[derive(Debug, Error)]
#[error("{} has malformed dependency groups", if path.is_empty() && package.is_empty() {
"Project".to_string()
} else if path.is_empty() || path == "." {
format!("Project `{package}`")
} else if package.is_empty() {
format!("`{path}`")
} else {
format!("Project `{package} @ {path}`")
})]
pub struct DependencyGroupError {
package: String,
path: String,
#[source]
error: DependencyGroupErrorInner,
}
#[derive(Debug, Error)]
pub enum DependencyGroupErrorInner {
#[error("Failed to parse entry in group `{0}`: `{1}`")]
GroupParseError(
GroupName,
String,
#[source] Box<Pep508Error<VerbatimParsedUrl>>,
),
#[error("Failed to find group `{0}` included by `{1}`")]
GroupNotFound(GroupName, GroupName),
#[error(
"Group `{0}` includes the `dev` group (`include = \"dev\"`), but only `tool.uv.dev-dependencies` was found. To reference the `dev` group via an `include`, remove the `tool.uv.dev-dependencies` section and add any development dependencies to the `dev` entry in the `[dependency-groups]` table instead."
)]
DevGroupInclude(GroupName),
#[error("Detected a cycle in `dependency-groups`: {0}")]
DependencyGroupCycle(Cycle),
#[error("Group `{0}` contains an unknown dependency object specifier: {1:?}")]
DependencyObjectSpecifierNotSupported(GroupName, BTreeMap<String, String>),
#[error("Failed to find group `{0}` specified in `[tool.uv.dependency-groups]`")]
SettingsGroupNotFound(GroupName),
#[error(
"`[tool.uv.dependency-groups]` specifies the `dev` group, but only `tool.uv.dev-dependencies` was found. To reference the `dev` group, remove the `tool.uv.dev-dependencies` section and add any development dependencies to the `dev` entry in the `[dependency-groups]` table instead."
)]
SettingsDevGroupInclude,
}
impl DependencyGroupErrorInner {
/// Enrich a [`DependencyGroupError`] with the `tool.uv.dev-dependencies` metadata, if applicable.
#[must_use]
pub fn with_dev_dependencies(
self,
dev_dependencies: Option<&Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
) -> Self {
match self {
Self::GroupNotFound(group, parent)
if dev_dependencies.is_some() && group == *DEV_DEPENDENCIES =>
{
Self::DevGroupInclude(parent)
}
Self::SettingsGroupNotFound(group)
if dev_dependencies.is_some() && group == *DEV_DEPENDENCIES =>
{
Self::SettingsDevGroupInclude
}
_ => self,
}
}
}
/// A cycle in the `dependency-groups` table.
#[derive(Debug)]
pub struct Cycle(Vec<GroupName>);
/// Display a cycle, e.g., `a -> b -> c -> a`.
impl std::fmt::Display for Cycle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let [first, rest @ ..] = self.0.as_slice() else {
return Ok(());
};
write!(f, "`{first}`")?;
for group in rest {
write!(f, " -> `{group}`")?;
}
write!(f, " -> `{first}`")?;
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-cache-info/src/lib.rs | crates/uv-cache-info/src/lib.rs | pub use crate::cache_info::*;
pub use crate::timestamp::*;
mod cache_info;
mod git_info;
mod glob;
mod timestamp;
| 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-info/src/timestamp.rs | crates/uv-cache-info/src/timestamp.rs | use serde::{Deserialize, Serialize};
use std::path::Path;
/// A timestamp used to measure changes to a file.
///
/// On Unix, this uses `ctime` as a conservative approach. `ctime` should detect all
/// modifications, including some that we don't care about, like hardlink modifications.
/// On other platforms, it uses `mtime`.
///
/// See: <https://github.com/restic/restic/issues/2179>
/// See: <https://apenwarr.ca/log/20181113>
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct Timestamp(std::time::SystemTime);
impl Timestamp {
/// Return the [`Timestamp`] for the given path.
pub fn from_path(path: impl AsRef<Path>) -> std::io::Result<Self> {
let metadata = fs_err::metadata(path.as_ref())?;
Ok(Self::from_metadata(&metadata))
}
/// Return the [`Timestamp`] for the given metadata.
pub fn from_metadata(metadata: &std::fs::Metadata) -> Self {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let ctime = u64::try_from(metadata.ctime()).expect("ctime to be representable as u64");
let ctime_nsec = u32::try_from(metadata.ctime_nsec())
.expect("ctime_nsec to be representable as u32");
let duration = std::time::Duration::new(ctime, ctime_nsec);
Self(std::time::UNIX_EPOCH + duration)
}
#[cfg(not(unix))]
{
let modified = metadata.modified().expect("modified time to be available");
Self(modified)
}
}
/// Return the current [`Timestamp`].
pub fn now() -> Self {
Self(std::time::SystemTime::now())
}
}
impl From<std::time::SystemTime> for Timestamp {
fn from(system_time: std::time::SystemTime) -> Self {
Self(system_time)
}
}
| 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-info/src/git_info.rs | crates/uv-cache-info/src/git_info.rs | use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tracing::warn;
use walkdir::WalkDir;
#[derive(Debug, thiserror::Error)]
pub(crate) enum GitInfoError {
#[error("The repository at {0} is missing a `.git` directory")]
MissingGitDir(PathBuf),
#[error("The repository at {0} is missing a `HEAD` file")]
MissingHead(PathBuf),
#[error("The repository at {0} is missing a `refs` directory")]
MissingRefs(PathBuf),
#[error("The repository at {0} has an invalid reference: `{1}`")]
InvalidRef(PathBuf, String),
#[error("The discovered commit has an invalid length (expected 40 characters): `{0}`")]
WrongLength(String),
#[error("The discovered commit has an invalid character (expected hexadecimal): `{0}`")]
WrongDigit(String),
#[error(transparent)]
Io(#[from] std::io::Error),
}
/// The current commit for a repository (i.e., a 40-character hexadecimal string).
#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub(crate) struct Commit(String);
impl Commit {
/// Return the [`Commit`] for the repository at the given path.
pub(crate) fn from_repository(path: &Path) -> Result<Self, GitInfoError> {
// Find the `.git` directory, searching through parent directories if necessary.
let git_dir = path
.ancestors()
.map(|ancestor| ancestor.join(".git"))
.find(|git_dir| git_dir.exists())
.ok_or_else(|| GitInfoError::MissingGitDir(path.to_path_buf()))?;
let git_head_path =
git_head(&git_dir).ok_or_else(|| GitInfoError::MissingHead(git_dir.clone()))?;
let git_head_contents = fs_err::read_to_string(git_head_path)?;
// The contents are either a commit or a reference in the following formats
// - "<commit>" when the head is detached
// - "ref <ref>" when working on a branch
// If a commit, checking if the HEAD file has changed is sufficient
// If a ref, we need to add the head file for that ref to rebuild on commit
let mut git_ref_parts = git_head_contents.split_whitespace();
let commit_or_ref = git_ref_parts
.next()
.ok_or_else(|| GitInfoError::InvalidRef(git_dir.clone(), git_head_contents.clone()))?;
let commit = if let Some(git_ref) = git_ref_parts.next() {
let git_ref_path = git_dir.join(git_ref);
let commit = fs_err::read_to_string(git_ref_path)?;
commit.trim().to_string()
} else {
commit_or_ref.to_string()
};
// The commit should be 40 hexadecimal characters.
if commit.len() != 40 {
return Err(GitInfoError::WrongLength(commit));
}
if commit.chars().any(|c| !c.is_ascii_hexdigit()) {
return Err(GitInfoError::WrongDigit(commit));
}
Ok(Self(commit))
}
}
/// The set of tags visible in a repository.
#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub(crate) struct Tags(BTreeMap<String, String>);
impl Tags {
/// Return the [`Tags`] for the repository at the given path.
pub(crate) fn from_repository(path: &Path) -> Result<Self, GitInfoError> {
// Find the `.git` directory, searching through parent directories if necessary.
let git_dir = path
.ancestors()
.map(|ancestor| ancestor.join(".git"))
.find(|git_dir| git_dir.exists())
.ok_or_else(|| GitInfoError::MissingGitDir(path.to_path_buf()))?;
let git_tags_path = git_refs(&git_dir)
.ok_or_else(|| GitInfoError::MissingRefs(git_dir.clone()))?
.join("tags");
let mut tags = BTreeMap::new();
// Map each tag to its commit.
for entry in WalkDir::new(&git_tags_path).contents_first(true) {
let entry = match entry {
Ok(entry) => entry,
Err(err) => {
warn!("Failed to read Git tags: {err}");
continue;
}
};
let path = entry.path();
if !entry.file_type().is_file() {
continue;
}
if let Ok(Some(tag)) = path.strip_prefix(&git_tags_path).map(|name| name.to_str()) {
let commit = fs_err::read_to_string(path)?.trim().to_string();
// The commit should be 40 hexadecimal characters.
if commit.len() != 40 {
return Err(GitInfoError::WrongLength(commit));
}
if commit.chars().any(|c| !c.is_ascii_hexdigit()) {
return Err(GitInfoError::WrongDigit(commit));
}
tags.insert(tag.to_string(), commit);
}
}
Ok(Self(tags))
}
}
/// Return the path to the `HEAD` file of a Git repository, taking worktrees into account.
fn git_head(git_dir: &Path) -> Option<PathBuf> {
// The typical case is a standard git repository.
let git_head_path = git_dir.join("HEAD");
if git_head_path.exists() {
return Some(git_head_path);
}
if !git_dir.is_file() {
return None;
}
// If `.git/HEAD` doesn't exist and `.git` is actually a file,
// then let's try to attempt to read it as a worktree. If it's
// a worktree, then its contents will look like this, e.g.:
//
// gitdir: /home/andrew/astral/uv/main/.git/worktrees/pr2
//
// And the HEAD file we want to watch will be at:
//
// /home/andrew/astral/uv/main/.git/worktrees/pr2/HEAD
let contents = fs_err::read_to_string(git_dir).ok()?;
let (label, worktree_path) = contents.split_once(':')?;
if label != "gitdir" {
return None;
}
let worktree_path = worktree_path.trim();
Some(PathBuf::from(worktree_path))
}
/// Return the path to the `refs` directory of a Git repository, taking worktrees into account.
fn git_refs(git_dir: &Path) -> Option<PathBuf> {
// The typical case is a standard git repository.
let git_head_path = git_dir.join("refs");
if git_head_path.exists() {
return Some(git_head_path);
}
if !git_dir.is_file() {
return None;
}
// If `.git/refs` doesn't exist and `.git` is actually a file,
// then let's try to attempt to read it as a worktree. If it's
// a worktree, then its contents will look like this, e.g.:
//
// gitdir: /home/andrew/astral/uv/main/.git/worktrees/pr2
//
// And the HEAD refs we want to watch will be at:
//
// /home/andrew/astral/uv/main/.git/refs
let contents = fs_err::read_to_string(git_dir).ok()?;
let (label, worktree_path) = contents.split_once(':')?;
if label != "gitdir" {
return None;
}
let worktree_path = PathBuf::from(worktree_path.trim());
let refs_path = worktree_path.parent()?.parent()?.join("refs");
Some(refs_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-cache-info/src/glob.rs | crates/uv-cache-info/src/glob.rs | use std::{
collections::BTreeMap,
path::{Component, Components, Path, PathBuf},
};
/// Check if a component of the path looks like it may be a glob pattern.
///
/// Note: this function is being used when splitting a glob pattern into a long possible
/// base and the glob remainder (scanning through components until we hit the first component
/// for which this function returns true). It is acceptable for this function to return
/// false positives (e.g. patterns like 'foo[bar' or 'foo{bar') in which case correctness
/// will not be affected but efficiency might be (because we'll traverse more than we should),
/// however it should not return false negatives.
fn is_glob_like(part: Component) -> bool {
matches!(part, Component::Normal(_))
&& part.as_os_str().to_str().is_some_and(|part| {
["*", "{", "}", "?", "[", "]"]
.into_iter()
.any(|c| part.contains(c))
})
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct GlobParts {
base: PathBuf,
pattern: PathBuf,
}
/// Split a glob into longest possible base + shortest possible glob pattern.
fn split_glob(pattern: impl AsRef<str>) -> GlobParts {
let pattern: &Path = pattern.as_ref().as_ref();
let mut glob = GlobParts::default();
let mut globbing = false;
let mut last = None;
for part in pattern.components() {
if let Some(last) = last {
if last != Component::CurDir {
if globbing {
glob.pattern.push(last);
} else {
glob.base.push(last);
}
}
}
if !globbing {
globbing = is_glob_like(part);
}
// we don't know if this part is the last one, defer handling it by one iteration
last = Some(part);
}
if let Some(last) = last {
// defer handling the last component to prevent draining entire pattern into base
if globbing || matches!(last, Component::Normal(_)) {
glob.pattern.push(last);
} else {
glob.base.push(last);
}
}
glob
}
/// Classic trie with edges being path components and values being glob patterns.
#[derive(Default)]
struct Trie<'a> {
children: BTreeMap<Component<'a>, Trie<'a>>,
patterns: Vec<&'a Path>,
}
impl<'a> Trie<'a> {
fn insert(&mut self, mut components: Components<'a>, pattern: &'a Path) {
if let Some(part) = components.next() {
self.children
.entry(part)
.or_default()
.insert(components, pattern);
} else {
self.patterns.push(pattern);
}
}
#[allow(clippy::needless_pass_by_value)]
fn collect_patterns(
&self,
pattern_prefix: PathBuf,
group_prefix: PathBuf,
patterns: &mut Vec<PathBuf>,
groups: &mut Vec<(PathBuf, Vec<PathBuf>)>,
) {
// collect all patterns beneath and including this node
for pattern in &self.patterns {
patterns.push(pattern_prefix.join(pattern));
}
for (part, child) in &self.children {
if let Component::Normal(_) = part {
// for normal components, collect all descendant patterns ('normal' edges only)
child.collect_patterns(
pattern_prefix.join(part),
group_prefix.join(part),
patterns,
groups,
);
} else {
// for non-normal component edges, kick off separate group collection at this node
child.collect_groups(group_prefix.join(part), groups);
}
}
}
#[allow(clippy::needless_pass_by_value)]
fn collect_groups(&self, prefix: PathBuf, groups: &mut Vec<(PathBuf, Vec<PathBuf>)>) {
// LCP-style grouping of patterns
if self.patterns.is_empty() {
// no patterns in this node; child nodes can form independent groups
for (part, child) in &self.children {
child.collect_groups(prefix.join(part), groups);
}
} else {
// pivot point, we've hit a pattern node; we have to stop here and form a group
let mut group = Vec::new();
self.collect_patterns(PathBuf::new(), prefix.clone(), &mut group, groups);
groups.push((prefix, group));
}
}
}
/// Given a collection of globs, cluster them into (base, globs) groups so that:
/// - base doesn't contain any glob symbols
/// - each directory would only be walked at most once
/// - base of each group is the longest common prefix of globs in the group
pub(crate) fn cluster_globs(patterns: &[impl AsRef<str>]) -> Vec<(PathBuf, Vec<String>)> {
// split all globs into base/pattern
let globs: Vec<_> = patterns.iter().map(split_glob).collect();
// construct a path trie out of all split globs
let mut trie = Trie::default();
for glob in &globs {
trie.insert(glob.base.components(), &glob.pattern);
}
// run LCP-style aggregation of patterns in the trie into groups
let mut groups = Vec::new();
trie.collect_groups(PathBuf::new(), &mut groups);
// finally, convert resulting patterns to strings
groups
.into_iter()
.map(|(base, patterns)| {
(
base,
patterns
.iter()
// NOTE: this unwrap is ok because input patterns are valid utf-8
.map(|p| p.to_str().unwrap().to_owned())
.collect(),
)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::{GlobParts, cluster_globs, split_glob};
fn windowsify(path: &str) -> String {
if cfg!(windows) {
path.replace('/', "\\")
} else {
path.to_owned()
}
}
#[test]
fn test_split_glob() {
#[track_caller]
fn check(input: &str, base: &str, pattern: &str) {
let result = split_glob(input);
let expected = GlobParts {
base: base.into(),
pattern: pattern.into(),
};
assert_eq!(result, expected, "{input:?} != {base:?} + {pattern:?}");
}
check("", "", "");
check("a", "", "a");
check("a/b", "a", "b");
check("a/b/", "a", "b");
check("a/.//b/", "a", "b");
check("./a/b/c", "a/b", "c");
check("c/d/*", "c/d", "*");
check("c/d/*/../*", "c/d", "*/../*");
check("a/?b/c", "a", "?b/c");
check("/a/b/*", "/a/b", "*");
check("../x/*", "../x", "*");
check("a/{b,c}/d", "a", "{b,c}/d");
check("a/[bc]/d", "a", "[bc]/d");
check("*", "", "*");
check("*/*", "", "*/*");
check("..", "..", "");
check("/", "/", "");
}
#[test]
fn test_cluster_globs() {
#[track_caller]
fn check(input: &[&str], expected: &[(&str, &[&str])]) {
let input = input.iter().map(|s| windowsify(s)).collect::<Vec<_>>();
let mut result_sorted = cluster_globs(&input);
for (_, patterns) in &mut result_sorted {
patterns.sort_unstable();
}
result_sorted.sort_unstable();
let mut expected_sorted = Vec::new();
for (base, patterns) in expected {
let mut patterns_sorted = Vec::new();
for pattern in *patterns {
patterns_sorted.push(windowsify(pattern));
}
patterns_sorted.sort_unstable();
expected_sorted.push((windowsify(base).into(), patterns_sorted));
}
expected_sorted.sort_unstable();
assert_eq!(
result_sorted, expected_sorted,
"{input:?} != {expected_sorted:?} (got: {result_sorted:?})"
);
}
check(&["a/b/*", "a/c/*"], &[("a/b", &["*"]), ("a/c", &["*"])]);
check(&["./a/b/*", "a/c/*"], &[("a/b", &["*"]), ("a/c", &["*"])]);
check(&["/a/b/*", "/a/c/*"], &[("/a/b", &["*"]), ("/a/c", &["*"])]);
check(
&["../a/b/*", "../a/c/*"],
&[("../a/b", &["*"]), ("../a/c", &["*"])],
);
check(&["x/*", "y/*"], &[("x", &["*"]), ("y", &["*"])]);
check(&[], &[]);
check(
&["./*", "a/*", "../foo/*.png"],
&[("", &["*", "a/*"]), ("../foo", &["*.png"])],
);
check(
&[
"?",
"/foo/?",
"/foo/bar/*",
"../bar/*.png",
"../bar/../baz/*.jpg",
],
&[
("", &["?"]),
("/foo", &["?", "bar/*"]),
("../bar", &["*.png"]),
("../bar/../baz", &["*.jpg"]),
],
);
check(&["/abs/path/*"], &[("/abs/path", &["*"])]);
check(&["/abs/*", "rel/*"], &[("/abs", &["*"]), ("rel", &["*"])]);
check(&["a/{b,c}/*", "a/d?/*"], &[("a", &["{b,c}/*", "d?/*"])]);
check(
&[
"../shared/a/[abc].png",
"../shared/a/b/*",
"../shared/b/c/?x/d",
"docs/important/*.{doc,xls}",
"docs/important/very/*",
],
&[
("../shared/a", &["[abc].png", "b/*"]),
("../shared/b/c", &["?x/d"]),
("docs/important", &["*.{doc,xls}", "very/*"]),
],
);
check(&["file.txt"], &[("", &["file.txt"])]);
check(&["/"], &[("/", &[""])]);
check(&[".."], &[("..", &[""])]);
check(
&["file1.txt", "file2.txt"],
&[("", &["file1.txt", "file2.txt"])],
);
check(
&["a/file1.txt", "a/file2.txt"],
&[("a", &["file1.txt", "file2.txt"])],
);
check(
&["*", "a/b/*", "a/../c/*.jpg", "a/../c/*.png", "/a/*", "/b/*"],
&[
("", &["*", "a/b/*"]),
("a/../c", &["*.jpg", "*.png"]),
("/a", &["*"]),
("/b", &["*"]),
],
);
if cfg!(windows) {
check(
&[
r"\\foo\bar\shared/a/[abc].png",
r"\\foo\bar\shared/a/b/*",
r"\\foo\bar/shared/b/c/?x/d",
r"D:\docs\important/*.{doc,xls}",
r"D:\docs/important/very/*",
],
&[
(r"\\foo\bar\shared\a", &["[abc].png", r"b\*"]),
(r"\\foo\bar\shared\b\c", &[r"?x\d"]),
(r"D:\docs\important", &["*.{doc,xls}", r"very\*"]),
],
);
}
}
}
| 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-info/src/cache_info.rs | crates/uv-cache-info/src/cache_info.rs | use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use tracing::{debug, warn};
use uv_fs::Simplified;
use crate::git_info::{Commit, Tags};
use crate::glob::cluster_globs;
use crate::timestamp::Timestamp;
#[derive(Debug, thiserror::Error)]
pub enum CacheInfoError {
#[error("Failed to parse glob patterns for `cache-keys`: {0}")]
Glob(#[from] globwalk::GlobError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
/// The information used to determine whether a built distribution is up-to-date, based on the
/// timestamps of relevant files, the current commit of a repository, etc.
#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct CacheInfo {
/// The timestamp of the most recent `ctime` of any relevant files, at the time of the build.
/// The timestamp will typically be the maximum of the `ctime` values of the `pyproject.toml`,
/// `setup.py`, and `setup.cfg` files, if they exist; however, users can provide additional
/// files to timestamp via the `cache-keys` field.
timestamp: Option<Timestamp>,
/// The commit at which the distribution was built.
commit: Option<Commit>,
/// The Git tags present at the time of the build.
tags: Option<Tags>,
/// Environment variables to include in the cache key.
#[serde(default)]
env: BTreeMap<String, Option<String>>,
/// The timestamp or inode of any directories that should be considered in the cache key.
#[serde(default)]
directories: BTreeMap<Cow<'static, str>, Option<DirectoryTimestamp>>,
}
impl CacheInfo {
/// Return the [`CacheInfo`] for a given timestamp.
pub fn from_timestamp(timestamp: Timestamp) -> Self {
Self {
timestamp: Some(timestamp),
..Self::default()
}
}
/// Compute the cache info for a given path, which may be a file or a directory.
pub fn from_path(path: &Path) -> Result<Self, CacheInfoError> {
let metadata = fs_err::metadata(path)?;
if metadata.is_file() {
Ok(Self::from_file(path)?)
} else {
Self::from_directory(path)
}
}
/// Compute the cache info for a given directory.
pub fn from_directory(directory: &Path) -> Result<Self, CacheInfoError> {
let mut commit = None;
let mut tags = None;
let mut last_changed: Option<(PathBuf, Timestamp)> = None;
let mut directories = BTreeMap::new();
let mut env = BTreeMap::new();
// Read the cache keys.
let cache_keys =
if let Ok(contents) = fs_err::read_to_string(directory.join("pyproject.toml")) {
if let Ok(pyproject_toml) = toml::from_str::<PyProjectToml>(&contents) {
pyproject_toml
.tool
.and_then(|tool| tool.uv)
.and_then(|tool_uv| tool_uv.cache_keys)
} else {
None
}
} else {
None
};
// If no cache keys were defined, use the defaults.
let cache_keys = cache_keys.unwrap_or_else(|| {
vec![
CacheKey::Path(Cow::Borrowed("pyproject.toml")),
CacheKey::Path(Cow::Borrowed("setup.py")),
CacheKey::Path(Cow::Borrowed("setup.cfg")),
CacheKey::Directory {
dir: Cow::Borrowed("src"),
},
]
});
// Incorporate timestamps from any direct filepaths.
let mut globs = vec![];
for cache_key in cache_keys {
match cache_key {
CacheKey::Path(file) | CacheKey::File { file } => {
if file
.as_ref()
.chars()
.any(|c| matches!(c, '*' | '?' | '[' | '{'))
{
// Defer globs to a separate pass.
globs.push(file);
continue;
}
// Treat the path as a file.
let path = directory.join(file.as_ref());
let metadata = match path.metadata() {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
continue;
}
Err(err) => {
warn!("Failed to read metadata for file: {err}");
continue;
}
};
if !metadata.is_file() {
warn!(
"Expected file for cache key, but found directory: `{}`",
path.display()
);
continue;
}
let timestamp = Timestamp::from_metadata(&metadata);
if last_changed.as_ref().is_none_or(|(_, prev_timestamp)| {
*prev_timestamp < Timestamp::from_metadata(&metadata)
}) {
last_changed = Some((path, timestamp));
}
}
CacheKey::Directory { dir } => {
// Treat the path as a directory.
let path = directory.join(dir.as_ref());
let metadata = match path.metadata() {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
directories.insert(dir, None);
continue;
}
Err(err) => {
warn!("Failed to read metadata for directory: {err}");
continue;
}
};
if !metadata.is_dir() {
warn!(
"Expected directory for cache key, but found file: `{}`",
path.display()
);
continue;
}
if let Ok(created) = metadata.created() {
// Prefer the creation time.
directories.insert(
dir,
Some(DirectoryTimestamp::Timestamp(Timestamp::from(created))),
);
} else {
// Fall back to the inode.
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
directories
.insert(dir, Some(DirectoryTimestamp::Inode(metadata.ino())));
}
#[cfg(not(unix))]
{
warn!(
"Failed to read creation time for directory: `{}`",
path.display()
);
}
}
}
CacheKey::Git {
git: GitPattern::Bool(true),
} => match Commit::from_repository(directory) {
Ok(commit_info) => commit = Some(commit_info),
Err(err) => {
debug!("Failed to read the current commit: {err}");
}
},
CacheKey::Git {
git: GitPattern::Set(set),
} => {
if set.commit.unwrap_or(false) {
match Commit::from_repository(directory) {
Ok(commit_info) => commit = Some(commit_info),
Err(err) => {
debug!("Failed to read the current commit: {err}");
}
}
}
if set.tags.unwrap_or(false) {
match Tags::from_repository(directory) {
Ok(tags_info) => tags = Some(tags_info),
Err(err) => {
debug!("Failed to read the current tags: {err}");
}
}
}
}
CacheKey::Git {
git: GitPattern::Bool(false),
} => {}
CacheKey::Environment { env: var } => {
let value = std::env::var(&var).ok();
env.insert(var, value);
}
}
}
// If we have any globs, first cluster them using LCP and then do a single pass on each group.
if !globs.is_empty() {
for (glob_base, glob_patterns) in cluster_globs(&globs) {
let walker = globwalk::GlobWalkerBuilder::from_patterns(
directory.join(glob_base),
&glob_patterns,
)
.file_type(globwalk::FileType::FILE | globwalk::FileType::SYMLINK)
.build()?;
for entry in walker {
let entry = match entry {
Ok(entry) => entry,
Err(err) => {
warn!("Failed to read glob entry: {err}");
continue;
}
};
let metadata = if entry.path_is_symlink() {
// resolve symlinks for leaf entries without following symlinks while globbing
match fs_err::metadata(entry.path()) {
Ok(metadata) => metadata,
Err(err) => {
warn!("Failed to resolve symlink for glob entry: {err}");
continue;
}
}
} else {
match entry.metadata() {
Ok(metadata) => metadata,
Err(err) => {
warn!("Failed to read metadata for glob entry: {err}");
continue;
}
}
};
if !metadata.is_file() {
if !entry.path_is_symlink() {
// don't warn if it was a symlink - it may legitimately resolve to a directory
warn!(
"Expected file for cache key, but found directory: `{}`",
entry.path().display()
);
}
continue;
}
let timestamp = Timestamp::from_metadata(&metadata);
if last_changed.as_ref().is_none_or(|(_, prev_timestamp)| {
*prev_timestamp < Timestamp::from_metadata(&metadata)
}) {
last_changed = Some((entry.into_path(), timestamp));
}
}
}
}
let timestamp = if let Some((path, timestamp)) = last_changed {
debug!(
"Computed cache info: {timestamp:?}, {commit:?}, {tags:?}, {env:?}, {directories:?}. Most recently modified: {}",
path.user_display()
);
Some(timestamp)
} else {
None
};
Ok(Self {
timestamp,
commit,
tags,
env,
directories,
})
}
/// Compute the cache info for a given file, assumed to be a binary or source distribution
/// represented as (e.g.) a `.whl` or `.tar.gz` archive.
pub fn from_file(path: impl AsRef<Path>) -> std::io::Result<Self> {
let metadata = fs_err::metadata(path.as_ref())?;
let timestamp = Timestamp::from_metadata(&metadata);
Ok(Self {
timestamp: Some(timestamp),
..Self::default()
})
}
/// Returns `true` if the cache info is empty.
pub fn is_empty(&self) -> bool {
self.timestamp.is_none()
&& self.commit.is_none()
&& self.tags.is_none()
&& self.env.is_empty()
&& self.directories.is_empty()
}
}
/// A `pyproject.toml` with an (optional) `[tool.uv]` section.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct PyProjectToml {
tool: Option<Tool>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Tool {
uv: Option<ToolUv>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct ToolUv {
cache_keys: Option<Vec<CacheKey>>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
pub enum CacheKey {
/// Ex) `"Cargo.lock"` or `"**/*.toml"`
Path(Cow<'static, str>),
/// Ex) `{ file = "Cargo.lock" }` or `{ file = "**/*.toml" }`
File { file: Cow<'static, str> },
/// Ex) `{ dir = "src" }`
Directory { dir: Cow<'static, str> },
/// Ex) `{ git = true }` or `{ git = { commit = true, tags = false } }`
Git { git: GitPattern },
/// Ex) `{ env = "UV_CACHE_INFO" }`
Environment { env: String },
}
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
pub enum GitPattern {
Bool(bool),
Set(GitSet),
}
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct GitSet {
commit: Option<bool>,
tags: Option<bool>,
}
pub enum FilePattern {
Glob(String),
Path(PathBuf),
}
/// A timestamp used to measure changes to a directory.
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
enum DirectoryTimestamp {
Timestamp(Timestamp),
Inode(u64),
}
#[cfg(all(test, unix))]
mod tests_unix {
use anyhow::Result;
use super::{CacheInfo, Timestamp};
#[test]
fn test_cache_info_symlink_resolve() -> Result<()> {
let dir = tempfile::tempdir()?;
let dir = dir.path().join("dir");
fs_err::create_dir_all(&dir)?;
let write_manifest = |cache_key: &str| {
fs_err::write(
dir.join("pyproject.toml"),
format!(
r#"
[tool.uv]
cache-keys = [
"{cache_key}"
]
"#
),
)
};
let touch = |path: &str| -> Result<_> {
let path = dir.join(path);
fs_err::create_dir_all(path.parent().unwrap())?;
fs_err::write(&path, "")?;
Ok(Timestamp::from_metadata(&path.metadata()?))
};
let cache_timestamp = || -> Result<_> { Ok(CacheInfo::from_directory(&dir)?.timestamp) };
write_manifest("x/**")?;
assert_eq!(cache_timestamp()?, None);
let y = touch("x/y")?;
assert_eq!(cache_timestamp()?, Some(y));
let z = touch("x/z")?;
assert_eq!(cache_timestamp()?, Some(z));
// leaf entry symlink should be resolved
let a = touch("../a")?;
fs_err::os::unix::fs::symlink(dir.join("../a"), dir.join("x/a"))?;
assert_eq!(cache_timestamp()?, Some(a));
// symlink directories should not be followed while globbing
let c = touch("../b/c")?;
fs_err::os::unix::fs::symlink(dir.join("../b"), dir.join("x/b"))?;
assert_eq!(cache_timestamp()?, Some(a));
// no globs, should work as expected
write_manifest("x/y")?;
assert_eq!(cache_timestamp()?, Some(y));
write_manifest("x/a")?;
assert_eq!(cache_timestamp()?, Some(a));
write_manifest("x/b/c")?;
assert_eq!(cache_timestamp()?, Some(c));
// symlink pointing to a directory
write_manifest("x/*b*")?;
assert_eq!(cache_timestamp()?, None);
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-trampoline/build.rs | crates/uv-trampoline/build.rs | // This embeds a "manifest" - a special XML document - into our built binary.
// The main things it does is tell Windows that we want to use the magic
// utf8 codepage, so we can use the *A versions of Windows API functions and
// don't have to mess with utf-16.
use embed_manifest::{embed_manifest, new_manifest};
use uv_static::EnvVars;
fn main() {
if std::env::var_os(EnvVars::CARGO_CFG_WINDOWS).is_some() {
let manifest =
new_manifest("uv.Trampoline").remove_dependency("Microsoft.Windows.Common-Controls");
embed_manifest(manifest).expect("unable to embed manifest");
println!("cargo::rustc-link-lib=ucrt"); // https://github.com/rust-lang/rust/issues/143172
println!("cargo:rerun-if-changed=build.rs");
}
}
| 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/src/diagnostics.rs | crates/uv-trampoline/src/diagnostics.rs | use std::convert::Infallible;
use std::ffi::CString;
use std::io::Write;
use std::os::windows::io::AsRawHandle;
use std::string::String;
use ufmt_write::uWrite;
use windows::Win32::UI::WindowsAndMessaging::{MESSAGEBOX_STYLE, MessageBoxA};
use windows::core::PCSTR;
#[macro_export]
macro_rules! error {
($($tt:tt)*) => {{
$crate::diagnostics::write_diagnostic(&$crate::format!($($tt)*), true);
}}
}
#[macro_export]
macro_rules! warn {
($($tt:tt)*) => {{
$crate::diagnostics::write_diagnostic(&$crate::format!($($tt)*), false);
}}
}
#[macro_export]
macro_rules! format {
($($tt:tt)*) => {{
let mut buffer = $crate::diagnostics::StringBuffer::default();
_ = ufmt::uwriteln!(&mut buffer, $($tt)*);
buffer.0
}}
}
#[derive(Default)]
pub(crate) struct StringBuffer(pub(crate) String);
impl uWrite for StringBuffer {
type Error = Infallible;
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.0.push_str(s);
Ok(())
}
}
#[cold]
pub(crate) fn write_diagnostic(message: &str, is_error: bool) {
let mut stderr = std::io::stderr();
if !stderr.as_raw_handle().is_null() {
let _ = stderr.write_all(message.as_bytes());
} else if is_error {
let nul_terminated = unsafe { CString::new(message.as_bytes()).unwrap_unchecked() };
let pcstr_message = PCSTR::from_raw(nul_terminated.as_ptr() as *const _);
unsafe { MessageBoxA(None, pcstr_message, None, MESSAGEBOX_STYLE(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-trampoline/src/lib.rs | crates/uv-trampoline/src/lib.rs | pub mod bounce;
mod diagnostics;
| 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/src/bounce.rs | crates/uv-trampoline/src/bounce.rs | #![allow(clippy::disallowed_types)]
use std::ffi::{CString, c_void};
use std::path::{Path, PathBuf};
use std::vec::Vec;
use windows::Win32::Foundation::{LPARAM, WPARAM};
use windows::Win32::{
Foundation::{
CloseHandle, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, SetHandleInformation, TRUE,
},
System::Console::{
GetStdHandle, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, SetConsoleCtrlHandler, SetStdHandle,
},
System::Environment::GetCommandLineA,
System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectA, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject,
},
System::LibraryLoader::{FindResourceW, LoadResource, LockResource, SizeofResource},
System::Threading::{
CreateProcessA, GetExitCodeProcess, GetStartupInfoA, INFINITE, PROCESS_CREATION_FLAGS,
PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOA, WaitForInputIdle,
WaitForSingleObject,
},
UI::WindowsAndMessaging::{
CreateWindowExA, DestroyWindow, GetMessageA, HWND_MESSAGE, MSG, PEEK_MESSAGE_REMOVE_TYPE,
PeekMessageA, PostMessageA, WINDOW_EX_STYLE, WINDOW_STYLE,
},
};
use windows::core::{BOOL, PSTR, s};
use uv_static::EnvVars;
use crate::{error, format, warn};
// https://learn.microsoft.com/en-us/windows/win32/menurc/resource-types
const RT_RCDATA: u16 = 10;
/// Resource IDs for the trampoline metadata
const RESOURCE_TRAMPOLINE_KIND: windows::core::PCWSTR = windows::core::w!("UV_TRAMPOLINE_KIND");
const RESOURCE_PYTHON_PATH: windows::core::PCWSTR = windows::core::w!("UV_PYTHON_PATH");
/// The kind of trampoline.
enum TrampolineKind {
/// 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 TrampolineKind {
fn from_resource(data: &[u8]) -> Option<Self> {
match data.first() {
Some(1) => Some(Self::Script),
Some(2) => Some(Self::Python),
_ => None,
}
}
}
/// Safely loads a resource from the current module
fn load_resource(resource_id: windows::core::PCWSTR) -> Option<Vec<u8>> {
// SAFETY: winapi calls; null-terminated strings; all pointers are checked.
unsafe {
// Find the resource
let resource = FindResourceW(
None,
resource_id,
windows::core::PCWSTR(RT_RCDATA as *const _),
);
if resource.is_invalid() {
return None;
}
// Get resource size and data
let size = SizeofResource(None, resource);
if size == 0 {
return None;
}
let data = LoadResource(None, 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())
}
}
/// Transform `<command> <arguments>` to `python <command> <arguments>` or `python <arguments>`
/// depending on the [`TrampolineKind`].
fn make_child_cmdline() -> CString {
let executable_name = std::env::current_exe().unwrap_or_else(|_| {
error_and_exit("Failed to get executable name");
});
// Load trampoline kind
let trampoline_kind = load_resource(RESOURCE_TRAMPOLINE_KIND)
.and_then(|data| TrampolineKind::from_resource(&data))
.unwrap_or_else(|| error_and_exit("Failed to load trampoline kind from resources"));
// Load Python path
let python_path = load_resource(RESOURCE_PYTHON_PATH)
.and_then(|data| String::from_utf8(data).ok())
.map(PathBuf::from)
.unwrap_or_else(|| error_and_exit("Failed to load Python path from resources"));
let python_exe = if python_path.is_absolute() {
python_path
} else {
let parent_dir = match executable_name.parent() {
Some(parent) => parent,
None => {
error_and_exit("Executable path has no parent directory");
}
};
parent_dir.join(python_path)
};
let python_exe =
if !python_exe.is_absolute() || matches!(trampoline_kind, TrampolineKind::Script) {
// NOTICE: dunce adds 5kb~
// TODO(john): In order to avoid resolving junctions and symlinks for relative paths and
// scripts, we can consider reverting https://github.com/astral-sh/uv/pull/5750/files#diff-969979506be03e89476feade2edebb4689a9c261f325988d3c7efc5e51de26d1L273-L277.
dunce::canonicalize(python_exe.as_path()).unwrap_or_else(|_| {
error_and_exit("Failed to canonicalize script path");
})
} else {
// For Python trampolines with absolute paths, we skip `dunce::canonicalize` to
// avoid resolving junctions.
python_exe
};
let mut child_cmdline = Vec::<u8>::new();
push_quoted_path(python_exe.as_ref(), &mut child_cmdline);
child_cmdline.push(b' ');
// Only execute the trampoline again if it's a script, otherwise, just invoke Python.
match trampoline_kind {
TrampolineKind::Python => {
// SAFETY: `std::env::set_var` is safe to call on Windows, and
// this code only ever runs on Windows.
unsafe {
// Setting this env var will cause `getpath.py` to set
// `executable` to the path to this trampoline. This is
// the approach taken by CPython for Python Launchers
// (in `launcher.c`). This allows virtual environments to
// be correctly detected when using trampolines.
std::env::set_var(EnvVars::PYVENV_LAUNCHER, &executable_name);
// If this is not a virtual environment and `PYTHONHOME` has
// not been set, then set `PYTHONHOME` to the parent directory of
// the executable. This ensures that the correct installation
// directories are added to `sys.path` when running with a junction
// trampoline.
let python_home_set =
std::env::var(EnvVars::PYTHONHOME).is_ok_and(|home| !home.is_empty());
if !is_virtualenv(python_exe.as_path()) && !python_home_set {
std::env::set_var(
EnvVars::PYTHONHOME,
python_exe
.parent()
.expect("Python executable should have a parent directory"),
);
}
}
}
TrampolineKind::Script => {
// Use the full executable name because CMD only passes the name of the executable (but not the path)
// when e.g. invoking `black` instead of `<PATH_TO_VENV>/Scripts/black` and Python then fails
// to find the file. Unfortunately, this complicates things because we now need to split the executable
// from the arguments string...
push_quoted_path(executable_name.as_ref(), &mut child_cmdline);
}
}
push_arguments(&mut child_cmdline);
child_cmdline.push(b'\0');
// Helpful when debugging trampoline issues
// warn!(
// "executable_name: '{}'\nnew_cmdline: {}",
// &*executable_name.to_string_lossy(),
// std::str::from_utf8(child_cmdline.as_slice()).unwrap()
// );
CString::from_vec_with_nul(child_cmdline).unwrap_or_else(|_| {
error_and_exit("Child command line is not correctly null terminated");
})
}
fn push_quoted_path(path: &Path, command: &mut Vec<u8>) {
command.push(b'"');
for byte in path.as_os_str().as_encoded_bytes() {
if *byte == b'"' {
// 3 double quotes: one to end the quoted span, one to become a literal double-quote,
// and one to start a new quoted span.
command.extend(br#"""""#);
} else {
command.push(*byte);
}
}
command.extend(br#"""#);
}
/// Checks if the given executable is part of a virtual environment
///
/// Checks if a `pyvenv.cfg` file exists in grandparent directory of the given executable.
/// PEP 405 specifies a more robust procedure (checking both the parent and grandparent
/// directory and then scanning for a `home` key), but in practice we have found this to
/// be unnecessary.
fn is_virtualenv(executable: &Path) -> bool {
executable
.parent()
.and_then(Path::parent)
.map(|path| path.join("pyvenv.cfg").is_file())
.unwrap_or(false)
}
fn push_arguments(output: &mut Vec<u8>) {
// SAFETY: We rely on `GetCommandLineA` to return a valid pointer to a null terminated string.
let arguments_as_str = unsafe { GetCommandLineA() };
let arguments_as_bytes = unsafe { arguments_as_str.as_bytes() };
// Skip over the executable name and then push the rest of the arguments
let after_executable = skip_one_argument(arguments_as_bytes);
output.extend_from_slice(after_executable)
}
fn skip_one_argument(arguments: &[u8]) -> &[u8] {
let mut quoted = false;
let mut offset = 0;
let mut bytes_iter = arguments.iter().peekable();
// Implements https://learn.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments?view=msvc-170
while let Some(byte) = bytes_iter.next().copied() {
match byte {
b'"' => {
quoted = !quoted;
}
b'\\' => {
// Skip over escaped quotes or even number of backslashes.
if matches!(bytes_iter.peek().copied(), Some(&b'\"' | &b'\\')) {
offset += 1;
bytes_iter.next();
}
}
byte => {
if byte.is_ascii_whitespace() && !quoted {
break;
}
}
}
offset += 1;
}
&arguments[offset..]
}
fn make_job_object() -> HANDLE {
let job = unsafe { CreateJobObjectA(None, None) }
.unwrap_or_else(|_| print_last_error_and_exit("Job creation failed"));
let mut job_info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
let mut retlen = 0u32;
if unsafe {
QueryInformationJobObject(
Some(job),
JobObjectExtendedLimitInformation,
&mut job_info as *mut _ as *mut c_void,
size_of_val(&job_info) as u32,
Some(&mut retlen),
)
}
.is_err()
{
print_last_error_and_exit("Job information querying failed");
}
job_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
job_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
if unsafe {
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
&job_info as *const _ as *const c_void,
size_of_val(&job_info) as u32,
)
}
.is_err()
{
print_last_error_and_exit("Job information setting failed");
}
job
}
fn spawn_child(si: &STARTUPINFOA, child_cmdline: CString) -> HANDLE {
// See distlib/PC/launcher.c::run_child
if (si.dwFlags & STARTF_USESTDHANDLES).0 != 0 {
// ignore errors, if the handles are not inheritable/valid, then nothing we can do
unsafe { SetHandleInformation(si.hStdInput, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }
.unwrap_or_else(|_| warn!("Making stdin inheritable failed"));
unsafe { SetHandleInformation(si.hStdOutput, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }
.unwrap_or_else(|_| warn!("Making stdout inheritable failed"));
unsafe { SetHandleInformation(si.hStdError, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }
.unwrap_or_else(|_| warn!("Making stderr inheritable failed"));
}
let mut child_process_info = PROCESS_INFORMATION::default();
unsafe {
CreateProcessA(
None,
// Why does this have to be mutable? Who knows. But it's not a mistake --
// MS explicitly documents that this buffer might be mutated by CreateProcess.
Some(PSTR::from_raw(child_cmdline.as_ptr() as *mut _)),
None,
None,
true,
PROCESS_CREATION_FLAGS(0),
None,
None,
si,
&mut child_process_info,
)
}
.unwrap_or_else(|_| {
print_last_error_and_exit("Failed to spawn the python child process");
});
unsafe { CloseHandle(child_process_info.hThread) }.unwrap_or_else(|_| {
print_last_error_and_exit("Failed to close handle to python child process main thread");
});
// Return handle to child process.
child_process_info.hProcess
}
// Apparently, the Windows C runtime has a secret way to pass file descriptors into child
// processes, by using the .lpReserved2 field. We want to close those file descriptors too.
// The UCRT source code has details on the memory layout (see also initialize_inherited_file_handles_nolock):
// https://github.com/huangqinjin/ucrt/blob/10.0.19041.0/lowio/ioinit.cpp#L190-L223
#[allow(clippy::ptr_eq)]
fn close_handles(si: &STARTUPINFOA) {
// See distlib/PC/launcher.c::cleanup_standard_io()
// Unlike cleanup_standard_io(), we don't close STD_ERROR_HANDLE to retain warn!
for std_handle in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE] {
if let Ok(handle) = unsafe { GetStdHandle(std_handle) } {
unsafe { CloseHandle(handle) }.unwrap_or_else(|_| {
warn!("Failed to close standard device handle {}", handle.0 as u32);
});
unsafe { SetStdHandle(std_handle, INVALID_HANDLE_VALUE) }.unwrap_or_else(|_| {
warn!("Failed to modify standard device handle {}", std_handle.0);
});
}
}
// See distlib/PC/launcher.c::cleanup_fds()
if si.cbReserved2 == 0 || si.lpReserved2.is_null() {
return;
}
let crt_magic = si.lpReserved2 as *const u32;
let handle_count = unsafe { crt_magic.read_unaligned() } as isize;
let handle_start =
unsafe { (crt_magic.offset(1) as *const u8).offset(handle_count) as *const HANDLE };
// Close all fds inherited from the parent, except for the standard I/O fds (skip first 3).
for i in 3..handle_count {
let handle = unsafe { handle_start.offset(i).read_unaligned() };
// Ignore invalid handles, as that means this fd was not inherited.
// -2 is a special value (https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle)
if handle.is_invalid() || handle.0 == -2 as _ {
continue;
}
unsafe { CloseHandle(handle) }.unwrap_or_else(|_| {
warn!("Failed to close child file descriptors at {}", i);
});
}
}
/*
I don't really understand what this function does. It's a straight port from
https://github.com/pypa/distlib/blob/master/PC/launcher.c, which has the following
comment:
End the launcher's "app starting" cursor state.
When Explorer launches a Windows (GUI) application, it displays
the "app starting" (the "pointer + hourglass") cursor for a number
of seconds, or until the app does something UI-ish (eg, creating a
window, or fetching a message). As this launcher doesn't do this
directly, that cursor remains even after the child process does these
things. We avoid that by doing the stuff in here.
See http://bugs.python.org/issue17290 and
https://github.com/pypa/pip/issues/10444#issuecomment-973408601
Why do we call `PostMessage`/`GetMessage` at the start, before waiting for the
child? (Looking at the bpo issue above, this was originally the *whole* fix.)
Is creating a window and calling PeekMessage the best way to do this? idk.
*/
fn clear_app_starting_state(child_handle: HANDLE) {
let mut msg = MSG::default();
unsafe {
// End the launcher's "app starting" cursor state.
PostMessageA(None, 0, WPARAM(0), LPARAM(0)).unwrap_or_else(|_| {
warn!("Failed to post a message to specified window");
});
if GetMessageA(&mut msg, None, 0, 0) != TRUE {
warn!("Failed to retrieve posted window message");
}
// Proxy the child's input idle event.
if WaitForInputIdle(child_handle, INFINITE) != 0 {
warn!("Failed to wait for input from window");
}
// Signal the process input idle event by creating a window and pumping
// sent messages. The window class isn't important, so just use the
// system "STATIC" class.
if let Ok(hwnd) = CreateWindowExA(
WINDOW_EX_STYLE(0),
s!("STATIC"),
s!("uv Python Trampoline"),
WINDOW_STYLE(0),
0,
0,
0,
0,
Some(HWND_MESSAGE),
None,
None,
None,
) {
// Process all sent messages and signal input idle.
let _ = PeekMessageA(&mut msg, Some(hwnd), 0, 0, PEEK_MESSAGE_REMOVE_TYPE(0));
DestroyWindow(hwnd).unwrap_or_else(|_| {
print_last_error_and_exit("Failed to destroy temporary window");
});
}
}
}
pub fn bounce(is_gui: bool) -> ! {
let child_cmdline = make_child_cmdline();
let mut si = STARTUPINFOA::default();
unsafe { GetStartupInfoA(&mut si) }
let child_handle = spawn_child(&si, child_cmdline);
let job = make_job_object();
if unsafe { AssignProcessToJobObject(job, child_handle) }.is_err() {
print_last_error_and_exit("Failed to assign child process to the job")
}
// (best effort) Close all the handles that we can
close_handles(&si);
// (best effort) Switch to some innocuous directory, so we don't hold the original cwd open.
// See distlib/PC/launcher.c::switch_working_directory
if std::env::set_current_dir(std::env::temp_dir()).is_err() {
warn!("Failed to set cwd to temp dir");
}
// We want to ignore control-C/control-Break/logout/etc.; the same event will
// be delivered to the child, so we let them decide whether to exit or not.
unsafe extern "system" fn control_key_handler(_: u32) -> BOOL {
TRUE
}
// See distlib/PC/launcher.c::control_key_handler
unsafe { SetConsoleCtrlHandler(Some(control_key_handler), true) }.unwrap_or_else(|_| {
print_last_error_and_exit("Control handler setting failed");
});
if is_gui {
clear_app_starting_state(child_handle);
}
let _ = unsafe { WaitForSingleObject(child_handle, INFINITE) };
let mut exit_code = 0u32;
if unsafe { GetExitCodeProcess(child_handle, &mut exit_code) }.is_err() {
print_last_error_and_exit("Failed to get exit code of child process");
}
exit_with_status(exit_code);
}
#[cold]
fn error_and_exit(message: &str) -> ! {
error!("{}", message);
exit_with_status(1);
}
#[cold]
fn print_last_error_and_exit(message: &str) -> ! {
let err = std::io::Error::last_os_error();
let err_no_str = err
.raw_os_error()
.map(|raw_error| format!(" (os error {})", raw_error))
.unwrap_or_default();
// we can't access sys::os::error_string directly so err.kind().to_string()
// is the closest we can get to while avoiding bringing in a large chunk of core::fmt
let message = format!(
"(uv internal error) {}: {}.{}",
message,
err.kind().to_string(),
err_no_str
);
error_and_exit(&message);
}
#[cold]
fn exit_with_status(code: u32) -> ! {
// ~5-10kb
// Pulls in core::fmt::{write, Write, getcount}
std::process::exit(code as _)
}
| 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/src/bin/uv-trampoline-gui.rs | crates/uv-trampoline/src/bin/uv-trampoline-gui.rs | #![no_main] // disable all rust entry points, requires enabling compiler-builtins-mem
#![windows_subsystem = "windows"] // configures /SUBSYSTEM:WINDOWS
// Named according to https://docs.microsoft.com/en-us/cpp/build/reference/entry-entry-point-symbol
// This avoids having to define a custom /ENTRY:entry_fn in build.rs
#[unsafe(no_mangle)]
pub extern "C" fn mainCRTStartup() -> ! {
uv_trampoline::bounce::bounce(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-trampoline/src/bin/uv-trampoline-console.rs | crates/uv-trampoline/src/bin/uv-trampoline-console.rs | #![no_main] // disable all rust entry points, requires enabling compiler-builtins-mem
#![windows_subsystem = "console"] // configures /SUBSYSTEM:CONSOLE
// Named according to https://docs.microsoft.com/en-us/cpp/build/reference/entry-entry-point-symbol
// This avoids having to define a custom /ENTRY:entry_fn in build.rs
#[unsafe(no_mangle)]
pub extern "C" fn mainCRTStartup() -> ! {
uv_trampoline::bounce::bounce(false)
}
| 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-once-map/src/lib.rs | crates/uv-once-map/src/lib.rs | use std::borrow::Borrow;
use std::fmt::{Debug, Formatter};
use std::hash::{BuildHasher, Hash, RandomState};
use std::pin::pin;
use std::sync::Arc;
use dashmap::DashMap;
use tokio::sync::Notify;
/// Run tasks only once and store the results in a parallel hash map.
///
/// We often have jobs `Fn(K) -> V` that we only want to run once and memoize, e.g. network
/// requests for metadata. When multiple tasks start the same query in parallel, e.g. through source
/// dist builds, we want to wait until the other task is done and get a reference to the same
/// result.
///
/// Note that this always clones the value out of the underlying map. Because
/// of this, it's common to wrap the `V` in an `Arc<V>` to make cloning cheap.
pub struct OnceMap<K, V, S = RandomState> {
items: DashMap<K, Value<V>, S>,
}
impl<K: Eq + Hash + Debug, V: Debug, S: BuildHasher + Clone> Debug for OnceMap<K, V, S> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.items, f)
}
}
impl<K: Eq + Hash, V: Clone, H: BuildHasher + Clone> OnceMap<K, V, H> {
/// Create a [`OnceMap`] with the specified hasher.
pub fn with_hasher(hasher: H) -> Self {
Self {
items: DashMap::with_hasher(hasher),
}
}
/// Create a [`OnceMap`] with the specified capacity and hasher.
pub fn with_capacity_and_hasher(capacity: usize, hasher: H) -> Self {
Self {
items: DashMap::with_capacity_and_hasher(capacity, hasher),
}
}
/// Register that you want to start a job.
///
/// If this method returns `true`, you need to start a job and call [`OnceMap::done`] eventually
/// or other tasks will hang. If it returns `false`, this job is already in progress and you
/// can [`OnceMap::wait`] for the result.
pub fn register(&self, key: K) -> bool {
let entry = self.items.entry(key);
match entry {
dashmap::mapref::entry::Entry::Occupied(_) => false,
dashmap::mapref::entry::Entry::Vacant(entry) => {
entry.insert(Value::Waiting(Arc::new(Notify::new())));
true
}
}
}
/// Submit the result of a job you registered.
pub fn done(&self, key: K, value: V) {
if let Some(Value::Waiting(notify)) = self.items.insert(key, Value::Filled(value)) {
notify.notify_waiters();
}
}
/// Wait for the result of a job that is running.
///
/// Will hang if [`OnceMap::done`] isn't called for this key.
pub async fn wait(&self, key: &K) -> Option<V> {
let notify = {
let entry = self.items.get(key)?;
match entry.value() {
Value::Filled(value) => return Some(value.clone()),
Value::Waiting(notify) => notify.clone(),
}
};
// Register the waiter for calls to `notify_waiters`.
let notification = pin!(notify.notified());
// Make sure the value wasn't inserted in-between us checking the map and registering the waiter.
if let Value::Filled(value) = self.items.get(key).expect("map is append-only").value() {
return Some(value.clone());
}
// Wait until the value is inserted.
notification.await;
let entry = self.items.get(key).expect("map is append-only");
match entry.value() {
Value::Filled(value) => Some(value.clone()),
Value::Waiting(_) => unreachable!("notify was called"),
}
}
/// Wait for the result of a job that is running, in a blocking context.
///
/// Will hang if [`OnceMap::done`] isn't called for this key.
pub fn wait_blocking(&self, key: &K) -> Option<V> {
futures::executor::block_on(self.wait(key))
}
/// Return the result of a previous job, if any.
pub fn get<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
{
let entry = self.items.get(key)?;
match entry.value() {
Value::Filled(value) => Some(value.clone()),
Value::Waiting(_) => None,
}
}
/// Remove the result of a previous job, if any.
pub fn remove<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
{
let entry = self.items.remove(key)?;
match entry {
(_, Value::Filled(value)) => Some(value),
(_, Value::Waiting(_)) => None,
}
}
}
impl<K: Eq + Hash + Clone, V, H: Default + BuildHasher + Clone> Default for OnceMap<K, V, H> {
fn default() -> Self {
Self {
items: DashMap::with_hasher(H::default()),
}
}
}
impl<K, V, H> FromIterator<(K, V)> for OnceMap<K, V, H>
where
K: Eq + Hash,
H: Default + Clone + BuildHasher,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
Self {
items: iter
.into_iter()
.map(|(k, v)| (k, Value::Filled(v)))
.collect(),
}
}
}
#[derive(Debug)]
enum Value<V> {
Waiting(Arc<Notify>),
Filled(V),
}
| 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-keyring/src/blocking.rs | crates/uv-keyring/src/blocking.rs | use crate::error::{Error as ErrorCode, Result};
pub(crate) async fn spawn_blocking<F, T>(f: F) -> Result<T>
where
F: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
tokio::task::spawn_blocking(f)
.await
.map_err(|e| ErrorCode::PlatformFailure(Box::new(e)))?
}
| 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-keyring/src/lib.rs | crates/uv-keyring/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
/*!
# Keyring
This is a cross-platform library that does storage and retrieval of passwords
(or other secrets) in an underlying platform-specific secure credential store.
A top-level introduction to the library's usage, as well as a small code sample,
may be found in [the library's entry on crates.io](https://crates.io/crates/keyring).
Currently supported platforms are
Linux,
FreeBSD,
OpenBSD,
Windows,
and macOS.
## Design
This crate implements a very simple, platform-independent concrete object called an _entry_.
Each entry is identified by a <_service name_, _user name_> pair of UTF-8 strings.
Entries support setting, getting, and forgetting (aka deleting) passwords (UTF-8 strings)
and binary secrets (byte arrays). Each created entry provides security and persistence
of its secret by wrapping a credential held in a platform-specific, secure credential store.
The cross-platform API for creating an _entry_ supports specifying an (optional)
UTF-8 _target_ attribute on entries, but the meaning of this
attribute is credential-store (and thus platform) specific,
and should not be thought of as part of the credential's identification. See the
documentation of each credential store to understand the
effect of specifying the _target_ attribute on entries in that store,
as well as which values are allowed for _target_ by that store.
The abstract behavior of entries and credential stores are captured
by two types (with associated traits):
- a _credential builder_, represented by the [`CredentialBuilder`] type
(and [`CredentialBuilderApi`](credential::CredentialBuilderApi) trait). Credential
builders are given the identifying information (and target, if any)
provided for an entry and map
it to the identifying information for a platform-specific credential.
- a _credential_, represented by the [`Credential`] type
(and [`CredentialApi`](credential::CredentialApi) trait). The platform-specific credential
identified by the builder for an entry is what provides the secure storage
for that entry's password/secret.
## Crate-provided Credential Stores
This crate runs on several different platforms, and on each one
it provides (by default) an implementation of a default credential store used
on that platform (see [`default_credential_builder`]).
These implementations work by mapping the data used to identify an entry
to data used to identify platform-specific storage objects.
For example, on macOS, the service and user provided for an entry
are mapped to the service and user attributes that identify a
generic credential in the macOS keychain.
Typically, platform-specific credential stores (called _keystores_ in this crate)
have a richer model of a credential than
the one used by this crate to identify entries.
These keystores expose their specific model in the
concrete credential objects they use to implement the Credential trait.
In order to allow clients to access this richer model, the Credential trait
has an [`as_any`](credential::CredentialApi::as_any) method that returns a
reference to the underlying
concrete object typed as [`Any`](std::any::Any), so that it can be downgraded to
its concrete type.
### Credential store features
Each of the platform-specific credential stores is associated a feature.
This feature controls whether that store is included when the crate is built
for its specific platform. For example, the macOS Keychain credential store
implementation is only included if the `"apple-native"` feature is specified and the crate
is built with a macOS target.
The available credential store features, listed here, are all included in the
default feature set:
- `apple-native`: Provides access to the Keychain credential store on macOS.
- `windows-native`: Provides access to the Windows Credential Store on Windows.
- `secret-service`: Provides access to Secret Service.
If you suppress the default feature set when building this crate, and you
don't separately specify one of the included keystore features for your platform,
then no keystore will be built in, and calls to [`Entry::new`] and [`Entry::new_with_target`]
will fail unless the client brings their own keystore (see next section).
## Client-provided Credential Stores
In addition to the keystores implemented by this crate, clients
are free to provide their own keystores and use those. There are
two mechanisms provided for this:
- Clients can give their desired credential builder to the crate
for use by the [`Entry::new`] and [`Entry::new_with_target`] calls.
This is done by making a call to [`set_default_credential_builder`].
The major advantage of this approach is that client code remains
independent of the credential builder being used.
- Clients can construct their concrete credentials directly and
then turn them into entries by using the [`Entry::new_with_credential`]
call. The major advantage of this approach is that credentials
can be identified however clients want, rather than being restricted
to the simple model used by this crate.
## Mock Credential Store
In addition to the platform-specific credential stores, this crate
always provides a mock credential store that clients can use to
test their code in a platform independent way. The mock credential
store allows for pre-setting errors as well as password values to
be returned from [`Entry`] method calls. If you want to use the mock
credential store as your default in tests, make this call:
```
uv_keyring::set_default_credential_builder(uv_keyring::mock::default_credential_builder())
```
## Interoperability with Third Parties
Each of the platform-specific credential stores provided by this crate uses
an underlying store that may also be used by modules written
in other languages. If you want to interoperate with these third party
credential writers, then you will need to understand the details of how the
target, service, and user of this crate's generic model
are used to identify credentials in the platform-specific store.
These details are in the implementation of this crate's keystores,
and are documented in the headers of those modules.
(_N.B._ Since the included credential store implementations are platform-specific,
you may need to use the Platform drop-down on [docs.rs](https://docs.rs/keyring) to
view the storage module documentation for your desired platform.)
## Caveats
This module expects passwords to be UTF-8 encoded strings,
so if a third party has stored an arbitrary byte string
then retrieving that as a password will return a
[`BadEncoding`](Error::BadEncoding) error.
The returned error will have the raw bytes attached,
so you can access them, but you can also just fetch
them directly using [`get_secret`](Entry::get_secret) rather than
[`get_password`](Entry::get_password).
While this crate's code is thread-safe, the underlying credential
stores may not handle access from different threads reliably.
In particular, accessing the same credential
from multiple threads at the same time can fail, especially on
Windows and Linux, because the accesses may not be serialized in the same order
they are made. And for RPC-based credential stores such as the dbus-based Secret
Service, accesses from multiple threads (and even the same thread very quickly)
are not recommended, as they may cause the RPC mechanism to fail.
*/
use std::collections::HashMap;
pub use credential::{Credential, CredentialBuilder};
pub use error::{Error, Result};
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod blocking;
pub mod mock;
//
// pick the *nix keystore
//
#[cfg(all(
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"),
feature = "secret-service"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))
)]
pub mod secret_service;
//
// pick the Apple keystore
//
#[cfg(all(target_os = "macos", feature = "apple-native"))]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub mod macos;
//
// pick the Windows keystore
//
#[cfg(all(target_os = "windows", feature = "windows-native"))]
#[cfg_attr(docsrs, doc(cfg(target_os = "windows")))]
pub mod windows;
pub mod credential;
pub mod error;
#[derive(Default, Debug)]
struct EntryBuilder {
inner: Option<Box<CredentialBuilder>>,
}
static DEFAULT_BUILDER: std::sync::RwLock<EntryBuilder> =
std::sync::RwLock::new(EntryBuilder { inner: None });
/// Set the credential builder used by default to create entries.
///
/// This is really meant for use by clients who bring their own credential
/// store and want to use it everywhere. If you are using multiple credential
/// stores and want precise control over which credential is in which store,
/// then use [`new_with_credential`](Entry::new_with_credential).
///
/// This will block waiting for all other threads currently creating entries
/// to complete what they are doing. It's really meant to be called
/// at app startup before you start creating entries.
pub fn set_default_credential_builder(new: Box<CredentialBuilder>) {
let mut guard = DEFAULT_BUILDER
.write()
.expect("Poisoned RwLock in keyring-rs: please report a bug!");
guard.inner = Some(new);
}
pub fn default_credential_builder() -> Box<CredentialBuilder> {
#[cfg(any(
all(target_os = "linux", feature = "secret-service"),
all(target_os = "freebsd", feature = "secret-service"),
all(target_os = "openbsd", feature = "secret-service")
))]
return secret_service::default_credential_builder();
#[cfg(all(target_os = "macos", feature = "apple-native"))]
return macos::default_credential_builder();
#[cfg(all(target_os = "windows", feature = "windows-native"))]
return windows::default_credential_builder();
#[cfg(not(any(
all(target_os = "linux", feature = "secret-service"),
all(target_os = "freebsd", feature = "secret-service"),
all(target_os = "openbsd", feature = "secret-service"),
all(target_os = "macos", feature = "apple-native"),
all(target_os = "windows", feature = "windows-native"),
)))]
credential::nop_credential_builder()
}
fn build_default_credential(target: Option<&str>, service: &str, user: &str) -> Result<Entry> {
static DEFAULT: std::sync::LazyLock<Box<CredentialBuilder>> =
std::sync::LazyLock::new(default_credential_builder);
let guard = DEFAULT_BUILDER
.read()
.expect("Poisoned RwLock in keyring-rs: please report a bug!");
let builder = guard.inner.as_ref().unwrap_or_else(|| &DEFAULT);
let credential = builder.build(target, service, user)?;
Ok(Entry { inner: credential })
}
#[derive(Debug)]
pub struct Entry {
inner: Box<Credential>,
}
impl Entry {
/// Create an entry for the given service and user.
///
/// The default credential builder is used.
///
/// # Errors
///
/// This function will return an [`Error`] if the `service` or `user` values are invalid.
/// The specific reasons for invalidity are platform-dependent, but include length constraints.
///
/// # Panics
///
/// In the very unlikely event that the internal credential builder's `RwLock` is poisoned, this function
/// will panic. If you encounter this, and especially if you can reproduce it, please report a bug with the
/// details (and preferably a backtrace) so the developers can investigate.
pub fn new(service: &str, user: &str) -> Result<Self> {
let entry = build_default_credential(None, service, user)?;
Ok(entry)
}
/// Create an entry for the given target, service, and user.
///
/// The default credential builder is used.
pub fn new_with_target(target: &str, service: &str, user: &str) -> Result<Self> {
let entry = build_default_credential(Some(target), service, user)?;
Ok(entry)
}
/// Create an entry from a credential that may be in any credential store.
pub fn new_with_credential(credential: Box<Credential>) -> Self {
Self { inner: credential }
}
/// Set the password for this entry.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn set_password(&self, password: &str) -> Result<()> {
self.inner.set_password(password).await
}
/// Set the secret for this entry.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn set_secret(&self, secret: &[u8]) -> Result<()> {
self.inner.set_secret(secret).await
}
/// Retrieve the password saved for this entry.
///
/// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn get_password(&self) -> Result<String> {
self.inner.get_password().await
}
/// Retrieve the secret saved for this entry.
///
/// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn get_secret(&self) -> Result<Vec<u8>> {
self.inner.get_secret().await
}
/// Get the attributes on the underlying credential for this entry.
///
/// Some of the underlying credential stores allow credentials to have named attributes
/// that can be set to string values. See the documentation for each credential store
/// for a list of which attribute names are supported by that store.
///
/// Returns a [`NoEntry`](Error::NoEntry) error if there isn't a credential for this entry.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn get_attributes(&self) -> Result<HashMap<String, String>> {
self.inner.get_attributes().await
}
/// Update the attributes on the underlying credential for this entry.
///
/// Some of the underlying credential stores allow credentials to have named attributes
/// that can be set to string values. See the documentation for each credential store
/// for a list of which attribute names can be given values by this call. To support
/// cross-platform use, each credential store ignores (without error) any specified attributes
/// that aren't supported by that store.
///
/// Returns a [`NoEntry`](Error::NoEntry) error if there isn't a credential for this entry.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
pub async fn update_attributes(&self, attributes: &HashMap<&str, &str>) -> Result<()> {
self.inner.update_attributes(attributes).await
}
/// Delete the underlying credential for this entry.
///
/// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
///
/// Can return an [`Ambiguous`](Error::Ambiguous) error
/// if there is more than one platform credential
/// that matches this entry. This can only happen
/// on some platforms, and then only if a third-party
/// application wrote the ambiguous credential.
///
/// Note: This does _not_ affect the lifetime of the [Entry]
/// structure, which is controlled by Rust. It only
/// affects the underlying credential store.
pub async fn delete_credential(&self) -> Result<()> {
self.inner.delete_credential().await
}
/// Return a reference to this entry's wrapped credential.
///
/// The reference is of the [Any](std::any::Any) type, so it can be
/// downgraded to a concrete credential object. The client must know
/// what type of concrete object to cast to.
pub fn get_credential(&self) -> &dyn std::any::Any {
self.inner.as_any()
}
}
#[cfg(doctest)]
doc_comment::doctest!("../README.md", readme);
#[cfg(test)]
/// There are no actual tests in this module.
/// Instead, it contains generics that each keystore invokes in their tests,
/// passing their store-specific parameters for the generic ones.
mod tests {
use super::{Entry, Error};
#[cfg(feature = "native-auth")]
use super::{Result, credential::CredentialApi};
use std::collections::HashMap;
/// Create a platform-specific credential given the constructor, service, and user
#[cfg(feature = "native-auth")]
pub(crate) fn entry_from_constructor<F, T>(f: F, service: &str, user: &str) -> Entry
where
F: FnOnce(Option<&str>, &str, &str) -> Result<T>,
T: 'static + CredentialApi + Send + Sync,
{
match f(None, service, user) {
Ok(credential) => Entry::new_with_credential(Box::new(credential)),
Err(err) => {
panic!("Couldn't create entry (service: {service}, user: {user}): {err:?}")
}
}
}
async fn test_round_trip_no_delete(case: &str, entry: &Entry, in_pass: &str) {
entry
.set_password(in_pass)
.await
.unwrap_or_else(|err| panic!("Can't set password for {case}: {err:?}"));
let out_pass = entry
.get_password()
.await
.unwrap_or_else(|err| panic!("Can't get password for {case}: {err:?}"));
assert_eq!(
in_pass, out_pass,
"Passwords don't match for {case}: set='{in_pass}', get='{out_pass}'",
);
}
/// A basic round-trip unit test given an entry and a password.
pub(crate) async fn test_round_trip(case: &str, entry: &Entry, in_pass: &str) {
test_round_trip_no_delete(case, entry, in_pass).await;
entry
.delete_credential()
.await
.unwrap_or_else(|err| panic!("Can't delete password for {case}: {err:?}"));
let password = entry.get_password().await;
assert!(
matches!(password, Err(Error::NoEntry)),
"Read deleted password for {case}",
);
}
/// A basic round-trip unit test given an entry and a password.
pub(crate) async fn test_round_trip_secret(case: &str, entry: &Entry, in_secret: &[u8]) {
entry
.set_secret(in_secret)
.await
.unwrap_or_else(|err| panic!("Can't set secret for {case}: {err:?}"));
let out_secret = entry
.get_secret()
.await
.unwrap_or_else(|err| panic!("Can't get secret for {case}: {err:?}"));
assert_eq!(
in_secret, &out_secret,
"Passwords don't match for {case}: set='{in_secret:?}', get='{out_secret:?}'",
);
entry
.delete_credential()
.await
.unwrap_or_else(|err| panic!("Can't delete password for {case}: {err:?}"));
let password = entry.get_secret().await;
assert!(
matches!(password, Err(Error::NoEntry)),
"Read deleted password for {case}",
);
}
/// When tests fail, they leave keys behind, and those keys
/// have to be cleaned up before the tests can be run again
/// in order to avoid bad results. So it's a lot easier just
/// to have tests use a random string for key names to avoid
/// the conflicts, and then do any needed cleanup once everything
/// is working correctly. So we export this function for tests to use.
pub(crate) fn generate_random_string_of_len(len: usize) -> String {
use fastrand;
use std::iter::repeat_with;
repeat_with(fastrand::alphanumeric).take(len).collect()
}
pub(crate) fn generate_random_string() -> String {
generate_random_string_of_len(30)
}
fn generate_random_bytes_of_len(len: usize) -> Vec<u8> {
use fastrand;
use std::iter::repeat_with;
repeat_with(|| fastrand::u8(..)).take(len).collect()
}
pub(crate) async fn test_missing_entry<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Missing entry has password"
);
}
pub(crate) async fn test_empty_password<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
test_round_trip("empty password", &entry, "").await;
}
pub(crate) async fn test_round_trip_ascii_password<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
test_round_trip("ascii password", &entry, "test ascii password").await;
}
pub(crate) async fn test_round_trip_non_ascii_password<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
test_round_trip("non-ascii password", &entry, "このきれいな花は桜です").await;
}
pub(crate) async fn test_round_trip_random_secret<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
let secret = generate_random_bytes_of_len(24);
test_round_trip_secret("non-ascii password", &entry, secret.as_slice()).await;
}
pub(crate) async fn test_update<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
test_round_trip_no_delete("initial ascii password", &entry, "test ascii password").await;
test_round_trip(
"updated non-ascii password",
&entry,
"このきれいな花は桜です",
)
.await;
}
pub(crate) async fn test_noop_get_update_attributes<F>(f: F)
where
F: FnOnce(&str, &str) -> Entry,
{
let name = generate_random_string();
let entry = f(&name, &name);
assert!(
matches!(entry.get_attributes().await, Err(Error::NoEntry)),
"Read missing credential in attribute test",
);
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("test attribute name", "test attribute value");
assert!(
matches!(entry.update_attributes(&map).await, Err(Error::NoEntry)),
"Updated missing credential in attribute test",
);
// create the credential and test again
entry
.set_password("test password for attributes")
.await
.unwrap_or_else(|err| panic!("Can't set password for attribute test: {err:?}"));
match entry.get_attributes().await {
Err(err) => panic!("Couldn't get attributes: {err:?}"),
Ok(attrs) if attrs.is_empty() => {}
Ok(attrs) => panic!("Unexpected attributes: {attrs:?}"),
}
assert!(
matches!(entry.update_attributes(&map).await, Ok(())),
"Couldn't update attributes in attribute test",
);
match entry.get_attributes().await {
Err(err) => panic!("Couldn't get attributes after update: {err:?}"),
Ok(attrs) if attrs.is_empty() => {}
Ok(attrs) => panic!("Unexpected attributes after update: {attrs:?}"),
}
entry
.delete_credential()
.await
.unwrap_or_else(|err| panic!("Can't delete credential for attribute test: {err:?}"));
assert!(
matches!(entry.get_attributes().await, Err(Error::NoEntry)),
"Read deleted credential in attribute test",
);
}
}
| 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-keyring/src/macos.rs | crates/uv-keyring/src/macos.rs | /*!
# macOS Keychain credential store
All credentials on macOS are stored in secure stores called _keychains_.
The OS automatically creates three of them that live on filesystem,
called _User_ (aka login), _Common_, and _System_. In addition, removable
media can contain a keychain which can be registered under the name _Dynamic_.
The target attribute of an [`Entry`](crate::Entry) determines (case-insensitive)
which keychain that entry's credential is created in or searched for.
If the entry has no target, or the specified target doesn't name (case-insensitive)
one of the keychains listed above, the 'User' keychain is used.
For a given service/user pair, this module creates/searches for a credential
in the target keychain whose _account_ attribute holds the user
and whose _name_ attribute holds the service.
Because of a quirk in the Mac keychain services API, neither the _account_
nor the _name_ may be the empty string. (Empty strings are treated as
wildcards when looking up credentials by attribute value.)
In the _Keychain Access_ UI on Mac, credentials created by this module
show up in the passwords area (with their _where_ field equal to their _name_).
What the Keychain Access lists under _Note_ entries on the Mac are
also generic credentials, so existing _notes_ created by third-party
applications can be accessed by this module if you know the value
of their _account_ attribute (which is not displayed by _Keychain Access_).
Credentials on macOS can have a large number of _key/value_ attributes,
but this module controls the _account_ and _name_ attributes and
ignores all the others. so clients can't use it to access or update any attributes.
*/
use crate::credential::{Credential, CredentialApi, CredentialBuilder, CredentialBuilderApi};
use crate::error::{Error as ErrorCode, Result, decode_password};
use security_framework::base::Error;
use security_framework::os::macos::keychain::{SecKeychain, SecPreferencesDomain};
use security_framework::os::macos::passwords::find_generic_password;
/// The representation of a generic Keychain credential.
///
/// The actual credentials can have lots of attributes
/// not represented here. There's no way to use this
/// module to get at those attributes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacCredential {
pub domain: MacKeychainDomain,
pub service: String,
pub account: String,
}
#[async_trait::async_trait]
impl CredentialApi for MacCredential {
/// Create and write a credential with password for this entry.
///
/// The new credential replaces any existing one in the store.
/// Since there is only one credential with a given _account_ and _user_
/// in any given keychain, there is no chance of ambiguity.
async fn set_password(&self, password: &str) -> Result<()> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
let password = password.to_string();
crate::blocking::spawn_blocking(move || {
get_keychain(domain)?
.set_generic_password(&service, &account, password.as_bytes())
.map_err(decode_error)
})
.await?;
Ok(())
}
/// Create and write a credential with secret for this entry.
///
/// The new credential replaces any existing one in the store.
/// Since there is only one credential with a given _account_ and _user_
/// in any given keychain, there is no chance of ambiguity.
async fn set_secret(&self, secret: &[u8]) -> Result<()> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
let secret = secret.to_vec();
crate::blocking::spawn_blocking(move || {
get_keychain(domain)?
.set_generic_password(&service, &account, &secret)
.map_err(decode_error)
})
.await?;
Ok(())
}
/// Look up the password for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn get_password(&self) -> Result<String> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
let password_bytes = crate::blocking::spawn_blocking(move || -> Result<Vec<u8>> {
let keychain = get_keychain(domain)?;
let (password_bytes, _) = find_generic_password(Some(&[keychain]), &service, &account)
.map_err(decode_error)?;
Ok(password_bytes.to_owned())
})
.await?;
decode_password(password_bytes)
}
/// Look up the secret for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn get_secret(&self) -> Result<Vec<u8>> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
let password_bytes = crate::blocking::spawn_blocking(move || -> Result<Vec<u8>> {
let keychain = get_keychain(domain)?;
let (password_bytes, _) = find_generic_password(Some(&[keychain]), &service, &account)
.map_err(decode_error)?;
Ok(password_bytes.to_owned())
})
.await?;
Ok(password_bytes)
}
/// Delete the underlying generic credential for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn delete_credential(&self) -> Result<()> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
crate::blocking::spawn_blocking(move || {
let keychain = get_keychain(domain)?;
let (_, item) = find_generic_password(Some(&[keychain]), &service, &account)
.map_err(decode_error)?;
item.delete();
Ok(())
})
.await?;
Ok(())
}
/// Return the underlying concrete object with an `Any` type so that it can
/// be downgraded to a [`MacCredential`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// Expose the concrete debug formatter for use via the [Credential] trait
fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
impl MacCredential {
/// Construct a credential from the underlying generic credential.
///
/// On Mac, this is basically a no-op, because we represent any attributes
/// other than the ones we use to find the generic credential.
/// But at least this checks whether the underlying credential exists.
pub async fn get_credential(&self) -> Result<Self> {
let service = self.service.clone();
let account = self.account.clone();
let domain = self.domain;
let keychain = get_keychain(domain)?;
crate::blocking::spawn_blocking(move || -> Result<()> {
let (_, _) = find_generic_password(Some(&[keychain]), &service, &account)
.map_err(decode_error)?;
Ok(())
})
.await?;
Ok(self.clone())
}
/// Create a credential representing a Mac keychain entry.
///
/// Creating a credential does not put anything into the keychain.
/// The keychain entry will be created
/// when [`set_password`](MacCredential::set_password) is
/// called.
///
/// This will fail if the service or user strings are empty,
/// because empty attribute values act as wildcards in the
/// Keychain Services API.
pub fn new_with_target(
target: Option<MacKeychainDomain>,
service: &str,
user: &str,
) -> Result<Self> {
if service.is_empty() {
return Err(ErrorCode::Invalid(
"service".to_string(),
"cannot be empty".to_string(),
));
}
if user.is_empty() {
return Err(ErrorCode::Invalid(
"user".to_string(),
"cannot be empty".to_string(),
));
}
let domain = if let Some(target) = target {
target
} else {
MacKeychainDomain::User
};
Ok(Self {
domain,
service: service.to_string(),
account: user.to_string(),
})
}
}
/// The builder for Mac keychain credentials
pub struct MacCredentialBuilder;
/// Returns an instance of the Mac credential builder.
///
/// On Mac, with default features enabled,
/// this is called once when an entry is first created.
pub fn default_credential_builder() -> Box<CredentialBuilder> {
Box::new(MacCredentialBuilder {})
}
impl CredentialBuilderApi for MacCredentialBuilder {
/// Build a [`MacCredential`] for the given target, service, and user.
///
/// If a target is specified but not recognized as a keychain name,
/// the User keychain is selected.
fn build(&self, target: Option<&str>, service: &str, user: &str) -> Result<Box<Credential>> {
let domain: MacKeychainDomain = if let Some(target) = target {
target.parse().unwrap_or(MacKeychainDomain::User)
} else {
MacKeychainDomain::User
};
Ok(Box::new(MacCredential::new_with_target(
Some(domain),
service,
user,
)?))
}
/// Return the underlying builder object with an `Any` type so that it can
/// be downgraded to a [`MacCredentialBuilder`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// The four pre-defined Mac keychains.
pub enum MacKeychainDomain {
User,
System,
Common,
Dynamic,
Protected,
}
impl std::fmt::Display for MacKeychainDomain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::User => "User".fmt(f),
Self::System => "System".fmt(f),
Self::Common => "Common".fmt(f),
Self::Dynamic => "Dynamic".fmt(f),
Self::Protected => "Protected".fmt(f),
}
}
}
impl std::str::FromStr for MacKeychainDomain {
type Err = ErrorCode;
/// Convert a target specification string to a keychain domain.
///
/// We accept any case in the string,
/// but the value has to match a known keychain domain name
/// or else we assume the login keychain is meant.
fn from_str(s: &str) -> Result<Self> {
match s.to_ascii_lowercase().as_str() {
"user" => Ok(Self::User),
"system" => Ok(Self::System),
"common" => Ok(Self::Common),
"dynamic" => Ok(Self::Dynamic),
"protected" => Ok(Self::Protected),
"data protection" => Ok(Self::Protected),
_ => Err(ErrorCode::Invalid(
"target".to_string(),
format!("'{s}' is not User, System, Common, Dynamic, or Protected"),
)),
}
}
}
fn get_keychain(domain: MacKeychainDomain) -> Result<SecKeychain> {
let domain = match domain {
MacKeychainDomain::User => SecPreferencesDomain::User,
MacKeychainDomain::System => SecPreferencesDomain::System,
MacKeychainDomain::Common => SecPreferencesDomain::Common,
MacKeychainDomain::Dynamic => SecPreferencesDomain::Dynamic,
MacKeychainDomain::Protected => panic!("Protected is not a keychain domain on macOS"),
};
match SecKeychain::default_for_domain(domain) {
Ok(keychain) => Ok(keychain),
Err(err) => Err(decode_error(err)),
}
}
/// Map a Mac API error to a crate error with appropriate annotation
///
/// The macOS error code values used here are from
/// [this reference](https://opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-78/lib/SecBase.h.auto.html)
pub fn decode_error(err: Error) -> ErrorCode {
match err.code() {
-25291 => ErrorCode::NoStorageAccess(Box::new(err)), // errSecNotAvailable
-25292 => ErrorCode::NoStorageAccess(Box::new(err)), // errSecReadOnly
-25294 => ErrorCode::NoStorageAccess(Box::new(err)), // errSecNoSuchKeychain
-25295 => ErrorCode::NoStorageAccess(Box::new(err)), // errSecInvalidKeychain
-25300 => ErrorCode::NoEntry, // errSecItemNotFound
_ => ErrorCode::PlatformFailure(Box::new(err)),
}
}
#[cfg(feature = "native-auth")]
#[cfg(not(miri))]
#[cfg(test)]
mod tests {
use crate::credential::CredentialPersistence;
use crate::{Entry, Error, tests::generate_random_string};
use super::{MacCredential, default_credential_builder};
#[test]
fn test_persistence() {
assert!(matches!(
default_credential_builder().persistence(),
CredentialPersistence::UntilDelete
));
}
fn entry_new(service: &str, user: &str) -> Entry {
crate::tests::entry_from_constructor(
|_, s, u| MacCredential::new_with_target(None, s, u),
service,
user,
)
}
#[test]
fn test_invalid_parameter() {
let credential = MacCredential::new_with_target(None, "", "user");
assert!(
matches!(credential, Err(Error::Invalid(_, _))),
"Created credential with empty service"
);
let credential = MacCredential::new_with_target(None, "service", "");
assert!(
matches!(credential, Err(Error::Invalid(_, _))),
"Created entry with empty user"
);
}
#[tokio::test]
async fn test_missing_entry() {
crate::tests::test_missing_entry(entry_new).await;
}
#[tokio::test]
async fn test_empty_password() {
crate::tests::test_empty_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_ascii_password() {
crate::tests::test_round_trip_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_non_ascii_password() {
crate::tests::test_round_trip_non_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_random_secret() {
crate::tests::test_round_trip_random_secret(entry_new).await;
}
#[tokio::test]
async fn test_update() {
crate::tests::test_update(entry_new).await;
}
#[tokio::test]
async fn test_get_credential() {
let name = generate_random_string();
let entry = entry_new(&name, &name);
let credential: &MacCredential = entry
.get_credential()
.downcast_ref()
.expect("Not a mac credential");
assert!(
credential.get_credential().await.is_err(),
"Platform credential shouldn't exist yet!"
);
entry
.set_password("test get_credential")
.await
.expect("Can't set password for get_credential");
assert!(credential.get_credential().await.is_ok());
entry
.delete_credential()
.await
.expect("Couldn't delete after get_credential");
assert!(matches!(entry.get_password().await, Err(Error::NoEntry)));
}
#[tokio::test]
async fn test_get_update_attributes() {
crate::tests::test_noop_get_update_attributes(entry_new).await;
}
#[test]
fn test_select_keychain() {
for name in ["unknown", "user", "common", "system", "dynamic"] {
let cred = Entry::new_with_target(name, name, name)
.expect("couldn't create credential")
.inner;
let mac_cred: &MacCredential = cred
.as_any()
.downcast_ref()
.expect("credential not a MacCredential");
if name == "unknown" {
assert!(
matches!(mac_cred.domain, super::MacKeychainDomain::User),
"wrong domain for unknown specifier"
);
}
}
}
}
| 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-keyring/src/error.rs | crates/uv-keyring/src/error.rs | /*!
Platform-independent error model.
There is an escape hatch here for surfacing platform-specific
error information returned by the platform-specific storage provider,
but the concrete objects returned must be `Send` so they can be
moved from one thread to another. (Since most platform errors
are integer error codes, this requirement
is not much of a burden on the platform-specific store providers.)
*/
use crate::Credential;
#[derive(Debug, thiserror::Error)]
/// Each variant of the `Error` enum provides a summary of the error.
/// More details, if relevant, are contained in the associated value,
/// which may be platform-specific.
///
/// This enum is non-exhaustive so that more values can be added to it
/// without a `SemVer` break. Clients should always have default handling
/// for variants they don't understand.
#[non_exhaustive]
pub enum Error {
/// This indicates runtime failure in the underlying
/// platform storage system. The details of the failure can
/// be retrieved from the attached platform error.
#[error("Platform secure storage failure")]
PlatformFailure(#[source] Box<dyn std::error::Error + Send + Sync>),
/// This indicates that the underlying secure storage
/// holding saved items could not be accessed. Typically, this
/// is because of access rules in the platform; for example, it
/// might be that the credential store is locked. The underlying
/// platform error will typically give the reason.
#[error("Couldn't access platform secure storage")]
NoStorageAccess(#[source] Box<dyn std::error::Error + Send + Sync>),
/// This indicates that there is no underlying credential
/// entry in the platform for this entry. Either one was
/// never set, or it was deleted.
#[error("No matching entry found in secure storage")]
NoEntry,
/// This indicates that the retrieved password blob was not
/// a UTF-8 string. The underlying bytes are available
/// for examination in the attached value.
#[error("Data is not UTF-8 encoded")]
BadEncoding(Vec<u8>),
/// This indicates that one of the entry's credential
/// attributes exceeded a
/// length limit in the underlying platform. The
/// attached values give the name of the attribute and
/// the platform length limit that was exceeded.
#[error("Attribute '{0}' is longer than platform limit of {1} chars")]
TooLong(String, u32),
/// This indicates that one of the entry's required credential
/// attributes was invalid. The
/// attached value gives the name of the attribute
/// and the reason it's invalid.
#[error("Attribute {0} is invalid: {1}")]
Invalid(String, String),
/// This indicates that there is more than one credential found in the store
/// that matches the entry. Its value is a vector of the matching credentials.
#[error("Entry is matched by multiple credentials: {0:?}")]
Ambiguous(Vec<Box<Credential>>),
/// This indicates that there was no default credential builder to use;
/// the client must set one before creating entries.
#[error("No default credential builder is available; set one before creating entries")]
NoDefaultCredentialBuilder,
}
pub type Result<T> = std::result::Result<T, Error>;
/// Try to interpret a byte vector as a password string
pub fn decode_password(bytes: Vec<u8>) -> Result<String> {
String::from_utf8(bytes).map_err(|err| Error::BadEncoding(err.into_bytes()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bad_password() {
// malformed sequences here taken from:
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
for bytes in [b"\x80".to_vec(), b"\xbf".to_vec(), b"\xed\xa0\xa0".to_vec()] {
match decode_password(bytes.clone()) {
Err(Error::BadEncoding(str)) => assert_eq!(str, bytes),
Err(other) => panic!("Bad password ({bytes:?}) decode gave wrong error: {other}"),
Ok(s) => panic!("Bad password ({bytes:?}) decode gave results: {s:?}"),
}
}
}
}
| 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-keyring/src/windows.rs | crates/uv-keyring/src/windows.rs | /*!
# Windows Credential Manager credential store
This module uses Windows Generic credentials to store entries.
These are identified by a single string (called their _target name_).
They also have a number of non-identifying but manipulable attributes:
a _username_, a _comment_, and a _target alias_.
For a given <_service_, _username_> pair,
this module uses the concatenated string `username.service`
as the mapped credential's _target name_, and
fills the _username_ and _comment_ fields with appropriate strings.
(This convention allows multiple users to store passwords for the same service.)
Because the Windows credential manager doesn't support multiple collections of credentials,
and because many Windows programs use _only_ the service name as the credential _target name_,
the `Entry::new_with_target` call uses the `target` parameter as the credential's _target name_
rather than concatenating the username and service.
So if you have a custom algorithm you want to use for computing the Windows target name,
you can specify the target name directly. (You still need to provide a service and username,
because they are used in the credential's metadata.)
The [`get_attributes`](crate::Entry::get_attributes)
call will return the values in the `username`, `comment`, and `target_alias` fields
(using those strings as the attribute names),
and the [`update_attributes`](crate::Entry::update_attributes)
call allows setting those fields.
## Caveat
Reads and writes of the same entry from multiple threads
are not guaranteed to be serialized by the Windows Credential Manager in
the order in which they were made. Careful testing has
shown that modifying the same entry in the same (almost simultaneous) order from
different threads produces different results on different runs.
*/
#![allow(unsafe_code)]
use crate::credential::{Credential, CredentialApi, CredentialBuilder, CredentialBuilderApi};
use crate::error::{Error as ErrorCode, Result};
use byteorder::{ByteOrder, LittleEndian};
use std::collections::HashMap;
use std::iter::once;
use std::str;
use windows::Win32::Foundation::{
ERROR_BAD_USERNAME, ERROR_INVALID_FLAGS, ERROR_INVALID_PARAMETER, ERROR_NO_SUCH_LOGON_SESSION,
ERROR_NOT_FOUND, FILETIME, WIN32_ERROR,
};
use windows::Win32::Security::Credentials::{
CRED_FLAGS, CRED_MAX_CREDENTIAL_BLOB_SIZE, CRED_MAX_GENERIC_TARGET_NAME_LENGTH,
CRED_MAX_STRING_LENGTH, CRED_MAX_USERNAME_LENGTH, CRED_PERSIST_ENTERPRISE, CRED_TYPE_GENERIC,
CREDENTIAL_ATTRIBUTEW, CREDENTIALW, CredDeleteW, CredFree, CredReadW, CredWriteW,
};
use windows::core::PWSTR;
use zeroize::Zeroize;
/// The representation of a Windows Generic credential.
///
/// See the module header for the meanings of these fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WinCredential {
pub username: String,
pub target_name: String,
pub target_alias: String,
pub comment: String,
}
// Windows API type mappings:
// DWORD is u32
// LPCWSTR is *const u16
// BOOL is i32 (false = 0, true = 1)
// PCREDENTIALW = *mut CREDENTIALW
#[async_trait::async_trait]
impl CredentialApi for WinCredential {
/// Create and write a credential with password for this entry.
///
/// The new credential replaces any existing one in the store.
/// Since there is only one credential with a given _target name_,
/// there is no chance of ambiguity.
async fn set_password(&self, password: &str) -> Result<()> {
self.validate_attributes(None, Some(password))?;
// Password strings are converted to UTF-16, because that's the native
// charset for Windows strings. This allows interoperability with native
// Windows credential APIs. But the storage for the credential is actually
// a little-endian blob, because Windows credentials can contain anything.
let mut blob_u16 = to_wstr_no_null(password);
let mut blob = vec![0; blob_u16.len() * 2];
LittleEndian::write_u16_into(&blob_u16, &mut blob);
let result = self.set_secret(&blob).await;
// make sure that the copies of the secret are erased
blob_u16.zeroize();
blob.zeroize();
result
}
/// Create and write a credential with secret for this entry.
///
/// The new credential replaces any existing one in the store.
/// Since there is only one credential with a given _target name_,
/// there is no chance of ambiguity.
async fn set_secret(&self, secret: &[u8]) -> Result<()> {
self.validate_attributes(Some(secret), None)?;
self.save_credential(secret).await
}
/// Look up the password for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn get_password(&self) -> Result<String> {
self.extract_from_platform(extract_password).await
}
/// Look up the secret for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn get_secret(&self) -> Result<Vec<u8>> {
self.extract_from_platform(extract_secret).await
}
/// Get the attributes from the credential for this entry, if it exists.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn get_attributes(&self) -> Result<HashMap<String, String>> {
let cred = self.extract_from_platform(Self::extract_credential).await?;
let mut attributes: HashMap<String, String> = HashMap::new();
attributes.insert("comment".to_string(), cred.comment.clone());
attributes.insert("target_alias".to_string(), cred.target_alias.clone());
attributes.insert("username".to_string(), cred.username.clone());
Ok(attributes)
}
/// Update the attributes on the credential for this entry, if it exists.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn update_attributes(&self, attributes: &HashMap<&str, &str>) -> Result<()> {
let secret = self.extract_from_platform(extract_secret).await?;
let mut cred = self.extract_from_platform(Self::extract_credential).await?;
if let Some(comment) = attributes.get(&"comment") {
cred.comment = (*comment).to_string();
}
if let Some(target_alias) = attributes.get(&"target_alias") {
cred.target_alias = (*target_alias).to_string();
}
if let Some(username) = attributes.get(&"username") {
cred.username = (*username).to_string();
}
cred.validate_attributes(Some(&secret), None)?;
cred.save_credential(&secret).await
}
/// Delete the underlying generic credential for this entry, if any.
///
/// Returns a [`NoEntry`](ErrorCode::NoEntry) error if there is no
/// credential in the store.
async fn delete_credential(&self) -> Result<()> {
self.validate_attributes(None, None)?;
let mut target_name = to_wstr(&self.target_name);
let cred_type = CRED_TYPE_GENERIC;
crate::blocking::spawn_blocking(move || {
// SAFETY: Calling Windows API
unsafe {
CredDeleteW(PWSTR(target_name.as_mut_ptr()), cred_type, None)
.map_err(|err| Error(err).into())
}
})
.await
}
/// Return the underlying concrete object with an `Any` type so that it can
/// be downgraded to a [`WinCredential`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// Expose the concrete debug formatter for use via the [`Credential`] trait
fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
impl WinCredential {
fn validate_attributes(&self, secret: Option<&[u8]>, password: Option<&str>) -> Result<()> {
if self.username.len() > CRED_MAX_USERNAME_LENGTH as usize {
return Err(ErrorCode::TooLong(
String::from("user"),
CRED_MAX_USERNAME_LENGTH,
));
}
if self.target_name.is_empty() {
return Err(ErrorCode::Invalid(
"target".to_string(),
"cannot be empty".to_string(),
));
}
if self.target_name.len() > CRED_MAX_GENERIC_TARGET_NAME_LENGTH as usize {
return Err(ErrorCode::TooLong(
String::from("target"),
CRED_MAX_GENERIC_TARGET_NAME_LENGTH,
));
}
if self.target_alias.len() > CRED_MAX_STRING_LENGTH as usize {
return Err(ErrorCode::TooLong(
String::from("target alias"),
CRED_MAX_STRING_LENGTH,
));
}
if self.comment.len() > CRED_MAX_STRING_LENGTH as usize {
return Err(ErrorCode::TooLong(
String::from("comment"),
CRED_MAX_STRING_LENGTH,
));
}
if let Some(secret) = secret {
if secret.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize {
return Err(ErrorCode::TooLong(
String::from("secret"),
CRED_MAX_CREDENTIAL_BLOB_SIZE,
));
}
}
if let Some(password) = password {
// We're going to store the password as UTF-16, so first transform it to UTF-16,
// count its runes, and then multiply by 2 to get the number of bytes needed.
if password.encode_utf16().count() * 2 > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize {
return Err(ErrorCode::TooLong(
String::from("password encoded as UTF-16"),
CRED_MAX_CREDENTIAL_BLOB_SIZE,
));
}
}
Ok(())
}
/// Write this credential into the underlying store as a Generic credential
///
/// You must always have validated attributes before you call this!
#[allow(clippy::cast_possible_truncation)]
async fn save_credential(&self, secret: &[u8]) -> Result<()> {
let mut username = to_wstr(&self.username);
let mut target_name = to_wstr(&self.target_name);
let mut target_alias = to_wstr(&self.target_alias);
let mut comment = to_wstr(&self.comment);
let mut blob = secret.to_vec();
let blob_len = blob.len() as u32;
crate::blocking::spawn_blocking(move || {
let flags = CRED_FLAGS::default();
let cred_type = CRED_TYPE_GENERIC;
let persist = CRED_PERSIST_ENTERPRISE;
// Ignored by CredWriteW
let last_written = FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
};
let attribute_count = 0;
let attributes: *mut CREDENTIAL_ATTRIBUTEW = std::ptr::null_mut();
let credential = CREDENTIALW {
Flags: flags,
Type: cred_type,
TargetName: PWSTR(target_name.as_mut_ptr()),
Comment: PWSTR(comment.as_mut_ptr()),
LastWritten: last_written,
CredentialBlobSize: blob_len,
CredentialBlob: blob.as_mut_ptr(),
Persist: persist,
AttributeCount: attribute_count,
Attributes: attributes,
TargetAlias: PWSTR(target_alias.as_mut_ptr()),
UserName: PWSTR(username.as_mut_ptr()),
};
// SAFETY: Calling Windows API
let result =
unsafe { CredWriteW(&raw const credential, 0) }.map_err(|err| Error(err).into());
// erase the copy of the secret
blob.zeroize();
result
})
.await
}
/// Construct a credential from this credential's underlying Generic credential.
///
/// This can be useful for seeing modifications made by a third party.
pub async fn get_credential(&self) -> Result<Self> {
self.extract_from_platform(Self::extract_credential).await
}
async fn extract_from_platform<F, T>(&self, f: F) -> Result<T>
where
F: FnOnce(&CREDENTIALW) -> Result<T> + Send + 'static,
T: Send + 'static,
{
self.validate_attributes(None, None)?;
let mut target_name = to_wstr(&self.target_name);
crate::blocking::spawn_blocking(move || {
let mut p_credential = std::ptr::null_mut();
// at this point, p_credential is just a pointer to nowhere.
// The allocation happens in the `CredReadW` call below.
let cred_type = CRED_TYPE_GENERIC;
// SAFETY: Calling windows API
unsafe {
CredReadW(
PWSTR(target_name.as_mut_ptr()),
cred_type,
None,
&raw mut p_credential,
)
}
.map_err(Error)?;
// SAFETY: `CredReadW` succeeded, so p_credential points at an allocated credential. Apply
// the passed extractor function to it.
let ref_cred: &mut CREDENTIALW = unsafe { &mut *p_credential };
let result = f(ref_cred);
// Finally, we erase the secret and free the allocated credential.
erase_secret(ref_cred);
let p_credential = p_credential;
// SAFETY: `CredReadW` succeeded, so p_credential points at an allocated credential.
// Free the allocation.
unsafe { CredFree(p_credential.cast()) }
result
})
.await
}
#[allow(clippy::unnecessary_wraps)]
fn extract_credential(w_credential: &CREDENTIALW) -> Result<Self> {
Ok(Self {
username: unsafe { from_wstr(w_credential.UserName.as_ptr()) },
target_name: unsafe { from_wstr(w_credential.TargetName.as_ptr()) },
target_alias: unsafe { from_wstr(w_credential.TargetAlias.as_ptr()) },
comment: unsafe { from_wstr(w_credential.Comment.as_ptr()) },
})
}
/// Create a credential for the given target, service, and user.
///
/// Creating a credential does not create a matching Generic credential
/// in the Windows Credential Manager.
/// If there isn't already one there, it will be created only
/// when [`set_password`](WinCredential::set_password) is
/// called.
pub fn new_with_target(target: Option<&str>, service: &str, user: &str) -> Result<Self> {
const VERSION: &str = env!("CARGO_PKG_VERSION");
let credential = if let Some(target) = target {
Self {
// On Windows, the target name is all that's used to
// search for the credential, so we allow clients to
// specify it if they want a different convention.
username: user.to_string(),
target_name: target.to_string(),
target_alias: String::new(),
comment: format!("{user}@{service}:{target} (keyring v{VERSION})"),
}
} else {
Self {
// Note: default concatenation of user and service name is
// used because windows uses target_name as sole identifier.
// See the module docs for more rationale. Also see this issue
// for Python: https://github.com/jaraco/keyring/issues/47
//
// Note that it's OK to have an empty user or service name,
// because the format for the target name will not be empty.
// But it's certainly not recommended.
username: user.to_string(),
target_name: format!("{user}.{service}"),
target_alias: String::new(),
comment: format!("{user}@{service}:{user}.{service} (keyring v{VERSION})"),
}
};
credential.validate_attributes(None, None)?;
Ok(credential)
}
}
/// The builder for Windows Generic credentials.
pub struct WinCredentialBuilder;
/// Returns an instance of the Windows credential builder.
///
/// On Windows, with the default feature set,
/// this is called once when an entry is first created.
pub fn default_credential_builder() -> Box<CredentialBuilder> {
Box::new(WinCredentialBuilder {})
}
impl CredentialBuilderApi for WinCredentialBuilder {
/// Build a [`WinCredential`] for the given target, service, and user.
fn build(&self, target: Option<&str>, service: &str, user: &str) -> Result<Box<Credential>> {
Ok(Box::new(WinCredential::new_with_target(
target, service, user,
)?))
}
/// Return the underlying builder object with an `Any` type so that it can
/// be downgraded to a [`WinCredentialBuilder`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
fn extract_password(credential: &CREDENTIALW) -> Result<String> {
let mut blob = extract_secret(credential)?;
// 3rd parties may write credential data with an odd number of bytes,
// so we make sure that we don't try to decode those as utf16
if blob.len() % 2 != 0 {
return Err(ErrorCode::BadEncoding(blob));
}
// This should be a UTF-16 string, so convert it to
// a UTF-16 vector and then try to decode it.
let mut blob_u16 = vec![0; blob.len() / 2];
LittleEndian::read_u16_into(&blob, &mut blob_u16);
let result = match String::from_utf16(&blob_u16) {
Err(_) => Err(ErrorCode::BadEncoding(blob)),
Ok(s) => {
// we aren't returning the blob, so clear it
blob.zeroize();
Ok(s)
}
};
// we aren't returning the utf16 blob, so clear it
blob_u16.zeroize();
result
}
#[allow(clippy::unnecessary_wraps)]
fn extract_secret(credential: &CREDENTIALW) -> Result<Vec<u8>> {
let blob_pointer: *const u8 = credential.CredentialBlob;
let blob_len: usize = credential.CredentialBlobSize as usize;
if blob_len == 0 {
return Ok(Vec::new());
}
let blob = unsafe { std::slice::from_raw_parts(blob_pointer, blob_len) };
Ok(blob.to_vec())
}
fn erase_secret(credential: &mut CREDENTIALW) {
let blob_pointer: *mut u8 = credential.CredentialBlob;
let blob_len: usize = credential.CredentialBlobSize as usize;
if blob_len == 0 {
return;
}
let blob = unsafe { std::slice::from_raw_parts_mut(blob_pointer, blob_len) };
blob.zeroize();
}
fn to_wstr(s: &str) -> Vec<u16> {
s.encode_utf16().chain(once(0)).collect()
}
fn to_wstr_no_null(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
#[allow(clippy::maybe_infinite_iter)]
unsafe fn from_wstr(ws: *const u16) -> String {
// null pointer case, return empty string
if ws.is_null() {
return String::new();
}
// this code from https://stackoverflow.com/a/48587463/558006
let len = (0..).take_while(|&i| unsafe { *ws.offset(i) != 0 }).count();
if len == 0 {
return String::new();
}
let slice = unsafe { std::slice::from_raw_parts(ws, len) };
String::from_utf16_lossy(slice)
}
/// Windows error codes are `DWORDS` which are 32-bit unsigned ints.
#[derive(Debug)]
pub struct Error(windows::core::Error);
impl From<WIN32_ERROR> for Error {
fn from(error: WIN32_ERROR) -> Self {
Self(windows::core::Error::from(error))
}
}
impl From<Error> for ErrorCode {
fn from(err: Error) -> Self {
if err.0 == ERROR_NOT_FOUND.into() {
Self::NoEntry
} else if err.0 == ERROR_NO_SUCH_LOGON_SESSION.into() {
Self::NoStorageAccess(Box::new(err))
} else {
Self::PlatformFailure(Box::new(err))
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.0 == ERROR_NO_SUCH_LOGON_SESSION.into() {
write!(f, "Windows ERROR_NO_SUCH_LOGON_SESSION")
} else if self.0 == ERROR_NOT_FOUND.into() {
write!(f, "Windows ERROR_NOT_FOUND")
} else if self.0 == ERROR_BAD_USERNAME.into() {
write!(f, "Windows ERROR_BAD_USERNAME")
} else if self.0 == ERROR_INVALID_FLAGS.into() {
write!(f, "Windows ERROR_INVALID_FLAGS")
} else if self.0 == ERROR_INVALID_PARAMETER.into() {
write!(f, "Windows ERROR_INVALID_PARAMETER")
} else {
write!(f, "Windows error code {}", self.0)
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
#[cfg(feature = "native-auth")]
#[cfg(test)]
mod tests {
use super::*;
use crate::Entry;
use crate::credential::CredentialPersistence;
use crate::tests::{generate_random_string, generate_random_string_of_len};
#[test]
fn test_persistence() {
assert!(matches!(
default_credential_builder().persistence(),
CredentialPersistence::UntilDelete
));
}
fn entry_new(service: &str, user: &str) -> Entry {
crate::tests::entry_from_constructor(WinCredential::new_with_target, service, user)
}
#[allow(clippy::cast_possible_truncation)]
#[test]
fn test_bad_password() {
fn make_platform_credential(password: &mut Vec<u8>) -> CREDENTIALW {
let last_written = FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
};
let attribute_count = 0;
let attributes: *mut CREDENTIAL_ATTRIBUTEW = std::ptr::null_mut();
CREDENTIALW {
Flags: CRED_FLAGS(0),
Type: CRED_TYPE_GENERIC,
TargetName: PWSTR::null(),
Comment: PWSTR::null(),
LastWritten: last_written,
CredentialBlobSize: password.len() as u32,
CredentialBlob: password.as_mut_ptr(),
Persist: CRED_PERSIST_ENTERPRISE,
AttributeCount: attribute_count,
Attributes: attributes,
TargetAlias: PWSTR::null(),
UserName: PWSTR::null(),
}
}
// the first malformed sequence can't be UTF-16 because it has an odd number of bytes.
// the second malformed sequence has a first surrogate marker (0xd800) without a matching
// companion (it's taken from the String::fromUTF16 docs).
let mut odd_bytes = b"1".to_vec();
let malformed_utf16 = [0xD834, 0xDD1E, 0x006d, 0x0075, 0xD800, 0x0069, 0x0063];
let mut malformed_bytes: Vec<u8> = vec![0; malformed_utf16.len() * 2];
LittleEndian::write_u16_into(&malformed_utf16, &mut malformed_bytes);
for bytes in [&mut odd_bytes, &mut malformed_bytes] {
let credential = make_platform_credential(bytes);
match extract_password(&credential) {
Err(ErrorCode::BadEncoding(str)) => assert_eq!(&str, bytes),
Err(other) => panic!("Bad password ({bytes:?}) decode gave wrong error: {other}"),
Ok(s) => panic!("Bad password ({bytes:?}) decode gave results: {s:?}"),
}
}
}
#[test]
fn test_validate_attributes() {
fn validate_attribute_too_long(result: Result<()>, attr: &str, len: u32) {
match result {
Err(ErrorCode::TooLong(arg, val)) => {
if attr == "password" {
assert_eq!(
&arg, "password encoded as UTF-16",
"Error names wrong attribute"
);
} else {
assert_eq!(&arg, attr, "Error names wrong attribute");
}
assert_eq!(val, len, "Error names wrong limit");
}
Err(other) => panic!("Error is not '{attr} too long': {other}"),
Ok(()) => panic!("No error when {attr} too long"),
}
}
let cred = WinCredential {
username: "username".to_string(),
target_name: "target_name".to_string(),
target_alias: "target_alias".to_string(),
comment: "comment".to_string(),
};
for (attr, len) in [
("user", CRED_MAX_USERNAME_LENGTH),
("target", CRED_MAX_GENERIC_TARGET_NAME_LENGTH),
("target alias", CRED_MAX_STRING_LENGTH),
("comment", CRED_MAX_STRING_LENGTH),
("password", CRED_MAX_CREDENTIAL_BLOB_SIZE),
("secret", CRED_MAX_CREDENTIAL_BLOB_SIZE),
] {
let long_string = generate_random_string_of_len(1 + len as usize);
let mut bad_cred = cred.clone();
match attr {
"user" => bad_cred.username = long_string.clone(),
"target" => bad_cred.target_name = long_string.clone(),
"target alias" => bad_cred.target_alias = long_string.clone(),
"comment" => bad_cred.comment = long_string.clone(),
_ => (),
}
let validate = |r| validate_attribute_too_long(r, attr, len);
match attr {
"password" => {
let password = generate_random_string_of_len((len / 2) as usize + 1);
validate(bad_cred.validate_attributes(None, Some(&password)));
}
"secret" => {
let secret: Vec<u8> = vec![255u8; len as usize + 1];
validate(bad_cred.validate_attributes(Some(&secret), None));
}
_ => validate(bad_cred.validate_attributes(None, None)),
}
}
}
#[test]
fn test_password_valid_only_after_conversion_to_utf16() {
let cred = WinCredential {
username: "username".to_string(),
target_name: "target_name".to_string(),
target_alias: "target_alias".to_string(),
comment: "comment".to_string(),
};
let len = CRED_MAX_CREDENTIAL_BLOB_SIZE / 2;
let password: String = (0..len).map(|_| "笑").collect();
assert!(password.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize);
cred.validate_attributes(None, Some(&password))
.expect("Password of appropriate length in UTF16 was invalid");
}
#[test]
fn test_invalid_parameter() {
let credential = WinCredential::new_with_target(Some(""), "service", "user");
assert!(
matches!(credential, Err(ErrorCode::Invalid(_, _))),
"Created entry with empty target"
);
}
#[tokio::test]
async fn test_missing_entry() {
crate::tests::test_missing_entry(entry_new).await;
}
#[tokio::test]
async fn test_empty_password() {
crate::tests::test_empty_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_ascii_password() {
crate::tests::test_round_trip_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_non_ascii_password() {
crate::tests::test_round_trip_non_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_random_secret() {
crate::tests::test_round_trip_random_secret(entry_new).await;
}
#[tokio::test]
async fn test_update() {
crate::tests::test_update(entry_new).await;
}
#[tokio::test]
async fn test_get_update_attributes() {
let name = generate_random_string();
let cred = WinCredential::new_with_target(None, &name, &name)
.expect("Can't create credential for attribute test");
let entry = Entry::new_with_credential(Box::new(cred.clone()));
assert!(
matches!(entry.get_attributes().await, Err(ErrorCode::NoEntry)),
"Read missing credential in attribute test",
);
let mut in_map: HashMap<&str, &str> = HashMap::new();
in_map.insert("label", "ignored label value");
in_map.insert("attribute name", "ignored attribute value");
in_map.insert("target_alias", "target alias value");
in_map.insert("comment", "comment value");
in_map.insert("username", "username value");
assert!(
matches!(
entry.update_attributes(&in_map).await,
Err(ErrorCode::NoEntry)
),
"Updated missing credential in attribute test",
);
// create the credential and test again
entry
.set_password("test password for attributes")
.await
.unwrap_or_else(|err| panic!("Can't set password for attribute test: {err:?}"));
let out_map = entry
.get_attributes()
.await
.expect("Can't get attributes after create");
assert_eq!(out_map["target_alias"], cred.target_alias);
assert_eq!(out_map["comment"], cred.comment);
assert_eq!(out_map["username"], cred.username);
assert!(
matches!(entry.update_attributes(&in_map).await, Ok(())),
"Couldn't update attributes in attribute test",
);
let after_map = entry
.get_attributes()
.await
.expect("Can't get attributes after update");
assert_eq!(after_map["target_alias"], in_map["target_alias"]);
assert_eq!(after_map["comment"], in_map["comment"]);
assert_eq!(after_map["username"], in_map["username"]);
assert!(!after_map.contains_key("label"));
assert!(!after_map.contains_key("attribute name"));
entry
.delete_credential()
.await
.unwrap_or_else(|err| panic!("Can't delete credential for attribute test: {err:?}"));
assert!(
matches!(entry.get_attributes().await, Err(ErrorCode::NoEntry)),
"Read deleted credential in attribute test",
);
}
#[tokio::test]
async fn test_get_credential() {
let name = generate_random_string();
let entry = entry_new(&name, &name);
let password = "test get password";
entry
.set_password(password)
.await
.expect("Can't set test get password");
let credential: &WinCredential = entry
.get_credential()
.downcast_ref()
.expect("Not a windows credential");
let actual = credential
.get_credential()
.await
.expect("Can't read credential");
assert_eq!(
actual.username, credential.username,
"Usernames don't match"
);
assert_eq!(
actual.target_name, credential.target_name,
"Target names don't match"
);
assert_eq!(
actual.target_alias, credential.target_alias,
"Target aliases don't match"
);
assert_eq!(actual.comment, credential.comment, "Comments don't match");
entry
.delete_credential()
.await
.expect("Couldn't delete get-credential");
assert!(matches!(
entry.get_password().await,
Err(ErrorCode::NoEntry)
));
}
}
| 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-keyring/src/secret_service.rs | crates/uv-keyring/src/secret_service.rs | /*!
# secret-service credential store
Items in the secret-service are identified by an arbitrary collection
of attributes. This implementation controls the following attributes:
- `target` (optional & taken from entry creation call, defaults to `default`)
- `service` (required & taken from entry creation call)
- `username` (required & taken from entry creation call's `user` parameter)
In addition, when creating a new credential, this implementation assigns
two additional attributes:
- `application` (set to `uv`)
- `label` (set to a string with the user, service, target, and keyring version at time of creation)
Client code is allowed to retrieve and to set all attributes _except_ the
three that are controlled by this implementation. (N.B. The `label` string
is not actually an attribute; it's a required element in every item and is used
by GUI tools as the name for the item. But this implementation treats the
label as if it were any other non-controlled attribute, with the caveat that
it will reject any attempt to set the label to an empty string.)
Existing items are always searched for at the service level, which
means all collections are searched. The search attributes used are
`target` (set from the entry target), `service` (set from the entry
service), and `username` (set from the entry user). Because earlier
versions of this crate did not set the `target` attribute on credentials
that were stored in the default collection, a fallback search is done
for items in the default collection with no `target` attribute *if
the original search for all three attributes returns no matches*.
New items are created in the default collection,
unless a target other than `default` is
specified for the entry, in which case the item
will be created in a collection (created if necessary)
that is labeled with the specified target.
Setting the password on an entry will always update the password on an
existing item in preference to creating a new item.
This provides better compatibility with 3rd party clients, as well as earlier
versions of this crate, that may already
have created items that match the entry, and thus reduces the chance
of ambiguity in later searches.
## Headless usage
If you must use the secret-service on a headless linux box,
be aware that there are known issues with getting
dbus and secret-service and the gnome keyring
to work properly in headless environments.
For a quick workaround, look at how this project's
[CI workflow](https://github.com/hwchen/keyring-rs/blob/master/.github/workflows/ci.yaml)
starts the Gnome keyring unlocked with a known password;
a similar solution is also documented in the
[Python Keyring docs](https://pypi.org/project/keyring/)
(search for "Using Keyring on headless Linux systems").
The following `bash` function may be helpful:
```shell
function unlock-keyring ()
{
read -rsp "Password: " pass
echo -n "$pass" | gnome-keyring-daemon --unlock
unset pass
}
```
For an excellent treatment of all the headless dbus issues, see
[this answer on ServerFault](https://serverfault.com/a/906224/79617).
## Usage - not! - on Windows Subsystem for Linux
As noted in
[this issue on GitHub](https://github.com/hwchen/keyring-rs/issues/133),
there is no "default" collection defined under WSL. So
this keystore doesn't work "out of the box" on WSL. See the
issue for more details and possible workarounds.
*/
use std::collections::HashMap;
use secret_service::{Collection, EncryptionType, Error, Item, SecretService};
use crate::credential::{Credential, CredentialApi, CredentialBuilder, CredentialBuilderApi};
use crate::error::{Error as ErrorCode, Result, decode_password};
/// The representation of an item in the secret-service.
///
/// This structure has two roles. On the one hand, it captures all the
/// information a user specifies for an [`Entry`](crate::Entry)
/// and so is the basis for our search
/// (or creation) of an item for that entry. On the other hand, when
/// a search is ambiguous, each item found is represented by a credential that
/// has the same attributes and label as the item.
#[derive(Debug, Clone)]
pub struct SsCredential {
pub attributes: HashMap<String, String>,
pub label: String,
target: Option<String>,
}
#[async_trait::async_trait]
impl CredentialApi for SsCredential {
/// Sets the password on a unique matching item, if it exists, or creates one if necessary.
///
/// If there are multiple matches,
/// returns an [`Ambiguous`](ErrorCode::Ambiguous) error with a credential for each
/// matching item.
///
/// When creating, the item is put into a collection named by the credential's `target`
/// attribute.
async fn set_password(&self, password: &str) -> Result<()> {
self.set_secret(password.as_bytes()).await
}
/// Sets the secret on a unique matching item, if it exists, or creates one if necessary.
///
/// If there are multiple matches,
/// returns an [`Ambiguous`](ErrorCode::Ambiguous) error with a credential for each
/// matching item.
///
/// When creating, the item is put into a collection named by the credential's `target`
/// attribute.
async fn set_secret(&self, secret: &[u8]) -> Result<()> {
// first try to find a unique, existing, matching item and set its password
let secret_vec = secret.to_vec();
match self
.map_matching_items(async move |i| set_item_secret(i, &secret_vec).await, true)
.await
{
Ok(_) => return Ok(()),
Err(ErrorCode::NoEntry) => {}
Err(err) => return Err(err),
}
// if there is no existing item, create one for this credential. In order to create
// an item, the credential must have an explicit target. All entries created with
// the [`new`] or [`new_with_target`] commands will have explicit targets. But entries
// created to wrap 3rd-party items that don't have `target` attributes may not.
let ss = SecretService::connect(EncryptionType::Dh)
.await
.map_err(platform_failure)?;
let name = self.target.as_ref().ok_or_else(empty_target)?;
let collection = match get_collection(&ss, name).await {
Ok(collection) => collection,
Err(_) => create_collection(&ss, name).await?,
};
collection
.create_item(
self.label.as_str(),
self.all_attributes(),
secret,
true, // replace
"text/plain",
)
.await
.map_err(platform_failure)?;
Ok(())
}
/// Gets the password on a unique matching item, if it exists.
///
/// If there are no
/// matching items, returns a [`NoEntry`](ErrorCode::NoEntry) error.
/// If there are multiple matches,
/// returns an [`Ambiguous`](ErrorCode::Ambiguous)
/// error with a credential for each matching item.
async fn get_password(&self) -> Result<String> {
Ok(self
.map_matching_items(get_item_password, true)
.await?
.remove(0))
}
/// Gets the secret on a unique matching item, if it exists.
///
/// If there are no
/// matching items, returns a [`NoEntry`](ErrorCode::NoEntry) error.
/// If there are multiple matches,
/// returns an [`Ambiguous`](ErrorCode::Ambiguous)
/// error with a credential for each matching item.
async fn get_secret(&self) -> Result<Vec<u8>> {
Ok(self
.map_matching_items(get_item_secret, true)
.await?
.remove(0))
}
/// Get attributes on a unique matching item, if it exists
async fn get_attributes(&self) -> Result<HashMap<String, String>> {
let attributes: Vec<HashMap<String, String>> =
self.map_matching_items(get_item_attributes, true).await?;
Ok(attributes.into_iter().next().unwrap())
}
/// Update attributes on a unique matching item, if it exists
async fn update_attributes(&self, attributes: &HashMap<&str, &str>) -> Result<()> {
// Convert to owned data to avoid lifetime issues
let attributes_owned: HashMap<String, String> = attributes
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect();
self.map_matching_items(
async move |item| {
let attrs_ref: HashMap<&str, &str> = attributes_owned
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
update_item_attributes(item, &attrs_ref).await
},
true,
)
.await?;
Ok(())
}
/// Deletes the unique matching item, if it exists.
///
/// If there are no
/// matching items, returns a [`NoEntry`](ErrorCode::NoEntry) error.
/// If there are multiple matches,
/// returns an [`Ambiguous`](ErrorCode::Ambiguous)
/// error with a credential for each matching item.
async fn delete_credential(&self) -> Result<()> {
self.map_matching_items(delete_item, true).await?;
Ok(())
}
/// Return the underlying credential object with an `Any` type so that it can
/// be downgraded to an [`SsCredential`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// Expose the concrete debug formatter for use via the [`Credential`] trait
fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
impl SsCredential {
/// Create a credential for the given target, service, and user.
///
/// The target defaults to `default` (the default secret-service collection).
///
/// Creating this credential does not create a matching item.
/// If there isn't already one there, it will be created only
/// when [`set_password`](SsCredential::set_password) is
/// called.
pub fn new_with_target(target: Option<&str>, service: &str, user: &str) -> Result<Self> {
if let Some("") = target {
return Err(empty_target());
}
let target = target.unwrap_or("default");
let attributes = HashMap::from([
("service".to_string(), service.to_string()),
("username".to_string(), user.to_string()),
("target".to_string(), target.to_string()),
("application".to_string(), "uv".to_string()),
]);
Ok(Self {
attributes,
label: format!(
"{user}@{service}:{target} (uv v{})",
env!("CARGO_PKG_VERSION"),
),
target: Some(target.to_string()),
})
}
/// Create a credential that has *no* target and the given service and user.
///
/// This emulates what keyring v1 did, and can be very handy when you need to
/// access an old v1 credential that's in your secret service default collection.
pub fn new_with_no_target(service: &str, user: &str) -> Result<Self> {
let attributes = HashMap::from([
("service".to_string(), service.to_string()),
("username".to_string(), user.to_string()),
("application".to_string(), "uv".to_string()),
]);
Ok(Self {
attributes,
label: format!(
"uv v{} for no target, service '{service}', user '{user}'",
env!("CARGO_PKG_VERSION"),
),
target: None,
})
}
/// Create a credential from an underlying item.
///
/// The created credential will have all the attributes and label
/// of the underlying item, so you can examine them.
pub async fn new_from_item(item: &Item<'_>) -> Result<Self> {
let attributes = item.get_attributes().await.map_err(decode_error)?;
let target = attributes.get("target").cloned();
Ok(Self {
attributes,
label: item.get_label().await.map_err(decode_error)?,
target,
})
}
/// Construct a credential for this credential's underlying matching item,
/// if there is exactly one.
pub async fn new_from_matching_item(&self) -> Result<Self> {
Ok(self
.map_matching_items(Self::new_from_item, true)
.await?
.remove(0))
}
/// If there are multiple matching items for this credential, get all of their passwords.
///
/// (This is useful if [`get_password`](SsCredential::get_password)
/// returns an [`Ambiguous`](ErrorCode::Ambiguous) error.)
pub async fn get_all_passwords(&self) -> Result<Vec<String>> {
self.map_matching_items(get_item_password, false).await
}
/// If there are multiple matching items for this credential, delete all of them.
///
/// (This is useful if [`delete_credential`](SsCredential::delete_credential)
/// returns an [`Ambiguous`](ErrorCode::Ambiguous) error.)
pub async fn delete_all_passwords(&self) -> Result<()> {
self.map_matching_items(delete_item, false).await?;
Ok(())
}
/// Map an async function over the items matching this credential.
///
/// Items are unlocked before the function is applied.
///
/// If `require_unique` is true, and there are no matching items, then
/// a [`NoEntry`](ErrorCode::NoEntry) error is returned.
/// If `require_unique` is true, and there are multiple matches,
/// then an [`Ambiguous`](ErrorCode::Ambiguous) error is returned
/// with a vector containing one
/// credential for each of the matching items.
async fn map_matching_items<F, T>(&self, f: F, require_unique: bool) -> Result<Vec<T>>
where
F: AsyncFn(&Item<'_>) -> Result<T>,
T: Sized,
{
let ss = SecretService::connect(EncryptionType::Dh)
.await
.map_err(platform_failure)?;
let attributes: HashMap<&str, &str> = self.search_attributes(false).into_iter().collect();
let search = ss.search_items(attributes).await.map_err(decode_error)?;
let count = search.locked.len() + search.unlocked.len();
if count == 0 {
if let Some("default") = self.target.as_deref() {
return self.map_matching_legacy_items(&ss, f, require_unique).await;
}
}
if require_unique {
if count == 0 {
return Err(ErrorCode::NoEntry);
} else if count > 1 {
let mut creds: Vec<Box<Credential>> = vec![];
for item in search.locked.iter().chain(search.unlocked.iter()) {
let cred = Self::new_from_item(item).await?;
creds.push(Box::new(cred));
}
return Err(ErrorCode::Ambiguous(creds));
}
}
let mut results: Vec<T> = vec![];
for item in &search.unlocked {
results.push(f(item).await?);
}
for item in &search.locked {
item.unlock().await.map_err(decode_error)?;
results.push(f(item).await?);
}
Ok(results)
}
/// Map an async function over items that older versions of keyring
/// would have matched against this credential.
///
/// Keyring v1 created secret service items that had no target attribute, and it was
/// only able to create items in the default collection. Keyring v2, and Keyring v3.1,
/// in order to be able to find items set by keyring v1, would first look for items
/// everywhere independent of target attribute, and then filter those found by the value
/// of the target attribute. But this matching behavior overgeneralized when the keyring
/// was locked at the time of the search (see
/// [issue #204](https://github.com/hwchen/keyring-rs/issues/204) for details).
///
/// As of keyring v3.2, the service-wide search behavior was changed to require a
/// matching target on items. But, as pointed out in
/// [issue #207](https://github.com/hwchen/keyring-rs/issues/207),
/// this meant that items set by keyring v1 (or by 3rd party tools that didn't set
/// the target attribute) would not be found, even if they were in the default
/// collection.
///
/// So with keyring v3.2.1, if the service-wide search fails to find any matching
/// credential, and the credential being searched for has the default target, we fall back and search the default collection for a v1-style credential.
/// That preserves the legacy behavior at the cost of a second round-trip through
/// the secret service for the collection search.
pub async fn map_matching_legacy_items<F, T>(
&self,
ss: &SecretService<'_>,
f: F,
require_unique: bool,
) -> Result<Vec<T>>
where
F: AsyncFn(&Item<'_>) -> Result<T>,
T: Sized,
{
let collection = ss.get_default_collection().await.map_err(decode_error)?;
let attributes = self.search_attributes(true);
let search = collection
.search_items(attributes)
.await
.map_err(decode_error)?;
if require_unique {
if search.is_empty() && require_unique {
return Err(ErrorCode::NoEntry);
} else if search.len() > 1 {
let mut creds: Vec<Box<Credential>> = vec![];
for item in &search {
let cred = Self::new_from_item(item).await?;
creds.push(Box::new(cred));
}
return Err(ErrorCode::Ambiguous(creds));
}
}
let mut results: Vec<T> = vec![];
for item in &search {
results.push(f(item).await?);
}
Ok(results)
}
/// Using strings in the credential map makes managing the lifetime
/// of the credential much easier. But since the secret service expects
/// a map from &str to &str, we have this utility to transform the
/// credential's map into one of the right form.
fn all_attributes(&self) -> HashMap<&str, &str> {
self.attributes
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect()
}
/// Similar to [`all_attributes`](SsCredential::all_attributes),
/// but this just selects the ones we search on
fn search_attributes(&self, omit_target: bool) -> HashMap<&str, &str> {
let mut result: HashMap<&str, &str> = HashMap::new();
if self.target.is_some() && !omit_target {
result.insert("target", self.attributes["target"].as_str());
}
result.insert("service", self.attributes["service"].as_str());
result.insert("username", self.attributes["username"].as_str());
result
}
}
/// The builder for secret-service credentials
#[derive(Debug, Default)]
pub struct SsCredentialBuilder;
/// Returns an instance of the secret-service credential builder.
///
/// If secret-service is the default credential store,
/// this is called once when an entry is first created.
pub fn default_credential_builder() -> Box<CredentialBuilder> {
Box::new(SsCredentialBuilder {})
}
impl CredentialBuilderApi for SsCredentialBuilder {
/// Build an [`SsCredential`] for the given target, service, and user.
fn build(&self, target: Option<&str>, service: &str, user: &str) -> Result<Box<Credential>> {
Ok(Box::new(SsCredential::new_with_target(
target, service, user,
)?))
}
/// Return the underlying builder object with an `Any` type so that it can
/// be downgraded to an [`SsCredentialBuilder`] for platform-specific processing.
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
//
// Secret Service utilities
//
/// Find the secret service collection whose label is the given name.
///
/// The name `default` is treated specially and is interpreted as naming
/// the default collection regardless of its label (which might be different).
pub async fn get_collection<'a>(ss: &'a SecretService<'_>, name: &str) -> Result<Collection<'a>> {
let collection = if name.eq("default") {
ss.get_default_collection().await.map_err(decode_error)?
} else {
let all = ss.get_all_collections().await.map_err(decode_error)?;
let mut found = None;
for c in all {
if c.get_label().await.map_err(decode_error)?.eq(name) {
found = Some(c);
break;
}
}
found.ok_or(ErrorCode::NoEntry)?
};
if collection.is_locked().await.map_err(decode_error)? {
collection.unlock().await.map_err(decode_error)?;
}
Ok(collection)
}
/// Create a secret service collection labeled with the given name.
///
/// If a collection with that name already exists, it is returned.
///
/// The name `default` is specially interpreted to mean the default collection.
pub async fn create_collection<'a>(
ss: &'a SecretService<'_>,
name: &str,
) -> Result<Collection<'a>> {
let collection = if name.eq("default") {
ss.get_default_collection().await.map_err(decode_error)?
} else {
ss.create_collection(name, "").await.map_err(decode_error)?
};
Ok(collection)
}
/// Given an existing item, set its secret.
pub async fn set_item_secret(item: &Item<'_>, secret: &[u8]) -> Result<()> {
item.set_secret(secret, "text/plain")
.await
.map_err(decode_error)
}
/// Given an existing item, retrieve and decode its password.
pub async fn get_item_password(item: &Item<'_>) -> Result<String> {
let bytes = item.get_secret().await.map_err(decode_error)?;
decode_password(bytes)
}
/// Given an existing item, retrieve its secret.
pub async fn get_item_secret(item: &Item<'_>) -> Result<Vec<u8>> {
let secret = item.get_secret().await.map_err(decode_error)?;
Ok(secret)
}
/// Given an existing item, retrieve its non-controlled attributes.
pub async fn get_item_attributes(item: &Item<'_>) -> Result<HashMap<String, String>> {
let mut attributes = item.get_attributes().await.map_err(decode_error)?;
attributes.remove("target");
attributes.remove("service");
attributes.remove("username");
attributes.insert(
"label".to_string(),
item.get_label().await.map_err(decode_error)?,
);
Ok(attributes)
}
/// Given an existing item, retrieve its non-controlled attributes.
pub async fn update_item_attributes(
item: &Item<'_>,
attributes: &HashMap<&str, &str>,
) -> Result<()> {
let existing = item.get_attributes().await.map_err(decode_error)?;
let mut updated: HashMap<&str, &str> = HashMap::new();
for (k, v) in &existing {
updated.insert(k, v);
}
for (k, v) in attributes {
if k.eq(&"target") || k.eq(&"service") || k.eq(&"username") {
continue;
}
if k.eq(&"label") {
if v.is_empty() {
return Err(ErrorCode::Invalid(
"label".to_string(),
"cannot be empty".to_string(),
));
}
item.set_label(v).await.map_err(decode_error)?;
if updated.contains_key("label") {
updated.insert("label", v);
}
} else {
updated.insert(k, v);
}
}
item.set_attributes(updated).await.map_err(decode_error)?;
Ok(())
}
// Given an existing item, delete it.
pub async fn delete_item(item: &Item<'_>) -> Result<()> {
item.delete().await.map_err(decode_error)
}
//
// Error utilities
//
/// Map underlying secret-service errors to crate errors with
/// appropriate annotation.
pub fn decode_error(err: Error) -> ErrorCode {
match err {
Error::Locked => no_access(err),
Error::NoResult => no_access(err),
Error::Prompt => no_access(err),
_ => platform_failure(err),
}
}
fn empty_target() -> ErrorCode {
ErrorCode::Invalid("target".to_string(), "cannot be empty".to_string())
}
fn platform_failure(err: Error) -> ErrorCode {
ErrorCode::PlatformFailure(wrap(err))
}
fn no_access(err: Error) -> ErrorCode {
ErrorCode::NoStorageAccess(wrap(err))
}
fn wrap(err: Error) -> Box<dyn std::error::Error + Send + Sync> {
Box::new(err)
}
#[cfg(feature = "native-auth")]
#[cfg(test)]
mod tests {
use crate::credential::CredentialPersistence;
use crate::secret_service::{EncryptionType, SecretService, SsCredential};
use crate::{Entry, Error, default_credential_builder, tests::generate_random_string};
use std::collections::HashMap;
#[test]
fn test_persistence() {
assert!(matches!(
default_credential_builder().persistence(),
CredentialPersistence::UntilDelete
));
}
fn entry_new(service: &str, user: &str) -> Entry {
crate::tests::entry_from_constructor(SsCredential::new_with_target, service, user)
}
#[test]
fn test_invalid_parameter() {
let credential = SsCredential::new_with_target(Some(""), "service", "user");
assert!(
matches!(credential, Err(Error::Invalid(_, _))),
"Created entry with empty target"
);
}
#[tokio::test]
async fn test_missing_entry() {
crate::tests::test_missing_entry(entry_new).await;
}
#[tokio::test]
async fn test_empty_password() {
crate::tests::test_empty_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_ascii_password() {
crate::tests::test_round_trip_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_non_ascii_password() {
crate::tests::test_round_trip_non_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_random_secret() {
crate::tests::test_round_trip_random_secret(entry_new).await;
}
#[tokio::test]
async fn test_update() {
crate::tests::test_update(entry_new).await;
}
#[tokio::test]
async fn test_get_credential() {
let name = generate_random_string();
let entry = entry_new(&name, &name);
entry
.set_password("test get credential")
.await
.expect("Can't set password for get_credential");
let credential: &SsCredential = entry
.get_credential()
.downcast_ref()
.expect("Not a secret service credential");
let actual = credential
.new_from_matching_item()
.await
.expect("Can't read credential");
assert_eq!(actual.label, credential.label, "Labels don't match");
for (key, value) in &credential.attributes {
assert_eq!(
actual.attributes.get(key).expect("Missing attribute"),
value,
"Attribute mismatch"
);
}
entry
.delete_credential()
.await
.expect("Couldn't delete get-credential");
assert!(matches!(entry.get_password().await, Err(Error::NoEntry)));
}
#[tokio::test]
async fn test_get_update_attributes() {
let name = generate_random_string();
let credential = SsCredential::new_with_target(None, &name, &name)
.expect("Can't create credential for attribute test");
let create_label = credential.label.clone();
let entry = Entry::new_with_credential(Box::new(credential));
assert!(
matches!(entry.get_attributes().await, Err(Error::NoEntry)),
"Read missing credential in attribute test",
);
let mut in_map: HashMap<&str, &str> = HashMap::new();
in_map.insert("label", "test label value");
in_map.insert("test attribute name", "test attribute value");
in_map.insert("target", "ignored target value");
in_map.insert("service", "ignored service value");
in_map.insert("username", "ignored username value");
assert!(
matches!(entry.update_attributes(&in_map).await, Err(Error::NoEntry)),
"Updated missing credential in attribute test",
);
// create the credential and test again
entry
.set_password("test password for attributes")
.await
.unwrap_or_else(|err| panic!("Can't set password for attribute test: {err:?}"));
let out_map = entry
.get_attributes()
.await
.expect("Can't get attributes after create");
assert_eq!(out_map["label"], create_label);
assert_eq!(out_map["application"], "uv");
assert!(!out_map.contains_key("target"));
assert!(!out_map.contains_key("service"));
assert!(!out_map.contains_key("username"));
assert!(
matches!(entry.update_attributes(&in_map).await, Ok(())),
"Couldn't update attributes in attribute test",
);
let after_map = entry
.get_attributes()
.await
.expect("Can't get attributes after update");
assert_eq!(after_map["label"], in_map["label"]);
assert_eq!(
after_map["test attribute name"],
in_map["test attribute name"]
);
assert_eq!(out_map["application"], "uv");
in_map.insert("label", "");
assert!(
matches!(
entry.update_attributes(&in_map).await,
Err(Error::Invalid(_, _))
),
"Was able to set empty label in attribute test",
);
entry
.delete_credential()
.await
.unwrap_or_else(|err| panic!("Can't delete credential for attribute test: {err:?}"));
assert!(
matches!(entry.get_attributes().await, Err(Error::NoEntry)),
"Read deleted credential in attribute test",
);
}
#[tokio::test]
#[ignore = "can't be run headless, because it needs to prompt"]
async fn test_create_new_target_collection() {
let name = generate_random_string();
let credential = SsCredential::new_with_target(Some(&name), &name, &name)
.expect("Can't create credential for new collection");
let entry = Entry::new_with_credential(Box::new(credential));
let password = "password in new collection";
entry
.set_password(password)
.await
.expect("Can't set password for new collection entry");
let actual = entry
.get_password()
.await
.expect("Can't get password for new collection entry");
assert_eq!(actual, password);
entry
.delete_credential()
.await
.expect("Couldn't delete password for new collection entry");
assert!(matches!(entry.get_password().await, Err(Error::NoEntry)));
delete_collection(&name).await;
}
#[tokio::test]
#[ignore = "can't be run headless, because it needs to prompt"]
async fn test_separate_targets_dont_interfere() {
let name1 = generate_random_string();
let name2 = generate_random_string();
let credential1 = SsCredential::new_with_target(Some(&name1), &name1, &name1)
.expect("Can't create credential1 with new collection");
let entry1 = Entry::new_with_credential(Box::new(credential1));
let credential2 = SsCredential::new_with_target(Some(&name2), &name1, &name1)
.expect("Can't create credential2 with new collection");
let entry2 = Entry::new_with_credential(Box::new(credential2));
let entry3 = Entry::new(&name1, &name1).expect("Can't create entry in default collection");
let password1 = "password for collection 1";
let password2 = "password for collection 2";
let password3 = "password for default collection";
entry1
.set_password(password1)
.await
.expect("Can't set password for collection 1");
entry2
.set_password(password2)
.await
.expect("Can't set password for collection 2");
entry3
.set_password(password3)
.await
.expect("Can't set password for default collection");
let actual1 = entry1
.get_password()
.await
.expect("Can't get password for collection 1");
assert_eq!(actual1, password1);
let actual2 = entry2
.get_password()
.await
.expect("Can't get password for collection 2");
assert_eq!(actual2, password2);
| 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-keyring/src/mock.rs | crates/uv-keyring/src/mock.rs | /*!
# Mock credential store
To facilitate testing of clients, this crate provides a Mock credential store
that is platform-independent, provides no persistence, and allows the client
to specify the return values (including errors) for each call. The credentials
in this store have no attributes at all.
To use this credential store instead of the default, make this call during
application startup _before_ creating any entries:
```rust
keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
```
You can then create entries as you usually do, and call their usual methods
to set, get, and delete passwords. There is no persistence other than
in the entry itself, so getting a password before setting it will always result
in a [`NoEntry`](Error::NoEntry) error.
If you want a method call on an entry to fail in a specific way, you can
downcast the entry to a [`MockCredential`] and then call [`set_error`](MockCredential::set_error)
with the appropriate error. The next entry method called on the credential
will fail with the error you set. The error will then be cleared, so the next
call on the mock will operate as usual. Here's a complete example:
```rust
# use keyring::{Entry, Error, mock, mock::MockCredential};
# keyring::set_default_credential_builder(mock::default_credential_builder());
let entry = Entry::new("service", "user").unwrap();
let mock: &MockCredential = entry.get_credential().downcast_ref().unwrap();
mock.set_error(Error::Invalid("mock error".to_string(), "takes precedence".to_string()));
entry.set_password("test").expect_err("error will override");
entry.set_password("test").expect("error has been cleared");
```
*/
use std::cell::RefCell;
use std::sync::Mutex;
use crate::credential::{
Credential, CredentialApi, CredentialBuilder, CredentialBuilderApi, CredentialPersistence,
};
use crate::error::{Error, Result, decode_password};
/// The concrete mock credential
///
/// Mocks use an internal mutability pattern since entries are read-only.
/// The mutex is used to make sure these are Sync.
#[derive(Debug)]
pub struct MockCredential {
pub inner: Mutex<RefCell<MockData>>,
}
impl Default for MockCredential {
fn default() -> Self {
Self {
inner: Mutex::new(RefCell::new(MockData::default())),
}
}
}
/// The (in-memory) persisted data for a mock credential.
///
/// We keep a password, but unlike most keystores
/// we also keep an intended error to return on the next call.
///
/// (Everything about this structure is public for transparency.
/// Most keystore implementation hide their internals.)
#[derive(Debug, Default)]
pub struct MockData {
pub secret: Option<Vec<u8>>,
pub error: Option<Error>,
}
#[async_trait::async_trait]
impl CredentialApi for MockCredential {
/// Set a password on a mock credential.
///
/// If there is an error in the mock, it will be returned
/// and the password will _not_ be set. The error will
/// be cleared, so calling again will set the password.
async fn set_password(&self, password: &str) -> Result<()> {
let mut inner = self.inner.lock().expect("Can't access mock data for set");
let data = inner.get_mut();
let err = data.error.take();
match err {
None => {
data.secret = Some(password.as_bytes().to_vec());
Ok(())
}
Some(err) => Err(err),
}
}
/// Set a password on a mock credential.
///
/// If there is an error in the mock, it will be returned
/// and the password will _not_ be set. The error will
/// be cleared, so calling again will set the password.
async fn set_secret(&self, secret: &[u8]) -> Result<()> {
let mut inner = self.inner.lock().expect("Can't access mock data for set");
let data = inner.get_mut();
let err = data.error.take();
match err {
None => {
data.secret = Some(secret.to_vec());
Ok(())
}
Some(err) => Err(err),
}
}
/// Get the password from a mock credential, if any.
///
/// If there is an error set in the mock, it will
/// be returned instead of a password.
async fn get_password(&self) -> Result<String> {
let mut inner = self.inner.lock().expect("Can't access mock data for get");
let data = inner.get_mut();
let err = data.error.take();
match err {
None => match &data.secret {
None => Err(Error::NoEntry),
Some(val) => decode_password(val.clone()),
},
Some(err) => Err(err),
}
}
/// Get the password from a mock credential, if any.
///
/// If there is an error set in the mock, it will
/// be returned instead of a password.
async fn get_secret(&self) -> Result<Vec<u8>> {
let mut inner = self.inner.lock().expect("Can't access mock data for get");
let data = inner.get_mut();
let err = data.error.take();
match err {
None => match &data.secret {
None => Err(Error::NoEntry),
Some(val) => Ok(val.clone()),
},
Some(err) => Err(err),
}
}
/// Delete the password in a mock credential
///
/// If there is an error, it will be returned and
/// the deletion will not happen.
///
/// If there is no password, a [NoEntry](Error::NoEntry) error
/// will be returned.
async fn delete_credential(&self) -> Result<()> {
let mut inner = self
.inner
.lock()
.expect("Can't access mock data for delete");
let data = inner.get_mut();
let err = data.error.take();
match err {
None => match data.secret {
Some(_) => {
data.secret = None;
Ok(())
}
None => Err(Error::NoEntry),
},
Some(err) => Err(err),
}
}
/// Return this mock credential concrete object
/// wrapped in the [Any](std::any::Any) trait,
/// so it can be downcast.
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// Expose the concrete debug formatter for use via the [Credential] trait
fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
impl MockCredential {
/// Make a new mock credential.
///
/// Since mocks have no persistence between sessions,
/// new mocks always have no password.
fn new_with_target(_target: Option<&str>, _service: &str, _user: &str) -> Self {
Self::default()
}
/// Set an error to be returned from this mock credential.
///
/// Error returns always take precedence over the normal
/// behavior of the mock. But once an error has been
/// returned it is removed, so the mock works thereafter.
pub fn set_error(&self, err: Error) {
let mut inner = self
.inner
.lock()
.expect("Can't access mock data for set_error");
let data = inner.get_mut();
data.error = Some(err);
}
}
/// The builder for mock credentials.
pub struct MockCredentialBuilder;
impl CredentialBuilderApi for MockCredentialBuilder {
/// Build a mock credential for the given target, service, and user.
///
/// Since mocks don't persist between sessions, all mocks
/// start off without passwords.
fn build(&self, target: Option<&str>, service: &str, user: &str) -> Result<Box<Credential>> {
let credential = MockCredential::new_with_target(target, service, user);
Ok(Box::new(credential))
}
/// Get an [Any][std::any::Any] reference to the mock credential builder.
fn as_any(&self) -> &dyn std::any::Any {
self
}
/// This keystore keeps the password in the entry!
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::EntryOnly
}
}
/// Return a mock credential builder for use by clients.
pub fn default_credential_builder() -> Box<CredentialBuilder> {
Box::new(MockCredentialBuilder {})
}
#[cfg(test)]
mod tests {
use super::{MockCredential, default_credential_builder};
use crate::credential::CredentialPersistence;
use crate::{Entry, Error, tests::generate_random_string};
#[test]
fn test_persistence() {
assert!(matches!(
default_credential_builder().persistence(),
CredentialPersistence::EntryOnly
));
}
fn entry_new(service: &str, user: &str) -> Entry {
let credential = MockCredential::new_with_target(None, service, user);
Entry::new_with_credential(Box::new(credential))
}
#[tokio::test]
async fn test_missing_entry() {
crate::tests::test_missing_entry(entry_new).await;
}
#[tokio::test]
async fn test_empty_password() {
crate::tests::test_empty_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_ascii_password() {
crate::tests::test_round_trip_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_non_ascii_password() {
crate::tests::test_round_trip_non_ascii_password(entry_new).await;
}
#[tokio::test]
async fn test_round_trip_random_secret() {
crate::tests::test_round_trip_random_secret(entry_new).await;
}
#[tokio::test]
async fn test_update() {
crate::tests::test_update(entry_new).await;
}
#[tokio::test]
async fn test_get_update_attributes() {
crate::tests::test_noop_get_update_attributes(entry_new).await;
}
#[tokio::test]
async fn test_set_error() {
let name = generate_random_string();
let entry = entry_new(&name, &name);
let password = "test ascii password";
let mock: &MockCredential = entry
.inner
.as_any()
.downcast_ref()
.expect("Downcast failed");
mock.set_error(Error::Invalid(
"mock error".to_string(),
"is an error".to_string(),
));
assert!(
matches!(
entry.set_password(password).await,
Err(Error::Invalid(_, _))
),
"set: No error"
);
entry
.set_password(password)
.await
.expect("set: Error not cleared");
mock.set_error(Error::NoEntry);
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"get: No error"
);
let stored_password = entry.get_password().await.expect("get: Error not cleared");
assert_eq!(
stored_password, password,
"Retrieved and set ascii passwords don't match"
);
mock.set_error(Error::TooLong("mock".to_string(), 3));
assert!(
matches!(entry.delete_credential().await, Err(Error::TooLong(_, 3))),
"delete: No error"
);
entry
.delete_credential()
.await
.expect("delete: Error not cleared");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
}
}
| 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-keyring/src/credential.rs | crates/uv-keyring/src/credential.rs | /*!
# Platform-independent secure storage model
This module defines a plug and play model for platform-specific credential stores.
The model comprises two traits: [`CredentialBuilderApi`] for the underlying store
and [`CredentialApi`] for the entries in the store. These traits must be implemented
in a thread-safe way, a requirement captured in the [`CredentialBuilder`] and
[`Credential`] types that wrap them.
*/
use std::any::Any;
use std::collections::HashMap;
use crate::Result;
/// The API that [credentials](Credential) implement.
#[async_trait::async_trait]
pub trait CredentialApi {
/// Set the credential's password (a string).
///
/// This will persist the password in the underlying store.
async fn set_password(&self, password: &str) -> Result<()> {
self.set_secret(password.as_bytes()).await
}
/// Set the credential's secret (a byte array).
///
/// This will persist the secret in the underlying store.
async fn set_secret(&self, password: &[u8]) -> Result<()>;
/// Retrieve the password (a string) from the underlying credential.
///
/// This has no effect on the underlying store. If there is no credential
/// for this entry, a [`NoEntry`](crate::Error::NoEntry) error is returned.
async fn get_password(&self) -> Result<String> {
let secret = self.get_secret().await?;
crate::error::decode_password(secret)
}
/// Retrieve a secret (a byte array) from the credential.
///
/// This has no effect on the underlying store. If there is no credential
/// for this entry, a [NoEntry](crate::Error::NoEntry) error is returned.
async fn get_secret(&self) -> Result<Vec<u8>>;
/// Get the secure store attributes on this entry's credential.
///
/// Each credential store may support reading and updating different
/// named attributes; see the documentation on each of the stores
/// for details. Note that the keyring itself uses some of these
/// attributes to map entries to their underlying credential; these
/// _controlled_ attributes are not available for reading or updating.
///
/// We provide a default (no-op) implementation of this method
/// for backward compatibility with stores that don't implement it.
async fn get_attributes(&self) -> Result<HashMap<String, String>> {
// this should err in the same cases as get_secret, so first call that for effect
self.get_secret().await?;
// if we got this far, return success with no attributes
Ok(HashMap::new())
}
/// Update the secure store attributes on this entry's credential.
///
/// Each credential store may support reading and updating different
/// named attributes; see the documentation on each of the stores
/// for details. The implementation will ignore any attribute names
/// that you supply that are not available for update. Because the
/// names used by the different stores tend to be distinct, you can
/// write cross-platform code that will work correctly on each platform.
///
/// We provide a default no-op implementation of this method
/// for backward compatibility with stores that don't implement it.
async fn update_attributes(&self, _: &HashMap<&str, &str>) -> Result<()> {
// this should err in the same cases as get_secret, so first call that for effect
self.get_secret().await?;
// if we got this far, return success after setting no attributes
Ok(())
}
/// Delete the underlying credential, if there is one.
///
/// This is not idempotent if the credential existed!
/// A second call to `delete_credential` will return
/// a [`NoEntry`](crate::Error::NoEntry) error.
async fn delete_credential(&self) -> Result<()>;
/// Return the underlying concrete object cast to [Any].
///
/// This allows clients
/// to downcast the credential to its concrete type so they
/// can do platform-specific things with it (e.g.,
/// query its attributes in the underlying store).
fn as_any(&self) -> &dyn Any;
/// The `Debug` trait call for the object.
///
/// This is used to implement the `Debug` trait on this type; it
/// allows generic code to provide debug printing as provided by
/// the underlying concrete object.
///
/// We provide a (useless) default implementation for backward
/// compatibility with existing implementors who may have not
/// implemented the `Debug` trait for their credential objects
fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_any(), f)
}
}
/// A thread-safe implementation of the [Credential API](CredentialApi).
pub type Credential = dyn CredentialApi + Send + Sync;
impl std::fmt::Debug for Credential {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.debug_fmt(f)
}
}
/// A descriptor for the lifetime of stored credentials, returned from
/// a credential store's [`persistence`](CredentialBuilderApi::persistence) call.
#[non_exhaustive]
pub enum CredentialPersistence {
/// Credentials vanish when the entry vanishes (stored in the entry)
EntryOnly,
/// Credentials vanish when the process terminates (stored in process memory)
ProcessOnly,
/// Credentials persist until the machine reboots (stored in kernel memory)
UntilReboot,
/// Credentials persist until they are explicitly deleted (stored on disk)
UntilDelete,
}
/// The API that [credential builders](CredentialBuilder) implement.
pub trait CredentialBuilderApi {
/// Create a credential identified by the given target, service, and user.
///
/// This typically has no effect on the content of the underlying store.
/// A credential need not be persisted until its password is set.
fn build(&self, target: Option<&str>, service: &str, user: &str) -> Result<Box<Credential>>;
/// Return the underlying concrete object cast to [Any].
///
/// Because credential builders need not have any internal structure,
/// this call is not so much for clients
/// as it is to allow automatic derivation of a Debug trait for builders.
fn as_any(&self) -> &dyn Any;
/// The lifetime of credentials produced by this builder.
///
/// A default implementation is provided for backward compatibility,
/// since this API was added in a minor release. The default assumes
/// that keystores use disk-based credential storage.
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::UntilDelete
}
}
impl std::fmt::Debug for CredentialBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_any().fmt(f)
}
}
/// A thread-safe implementation of the [`CredentialBuilder` API](CredentialBuilderApi).
pub type CredentialBuilder = dyn CredentialBuilderApi + Send + Sync;
struct NopCredentialBuilder;
impl CredentialBuilderApi for NopCredentialBuilder {
fn build(&self, _: Option<&str>, _: &str, _: &str) -> Result<Box<Credential>> {
Err(super::Error::NoDefaultCredentialBuilder)
}
fn as_any(&self) -> &dyn Any {
self
}
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::EntryOnly
}
}
// Return a credential builder that always fails. This is the builder
// used if none of the crate-supplied keystores were included in the build.
pub fn nop_credential_builder() -> Box<CredentialBuilder> {
Box::new(NopCredentialBuilder)
}
| 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-keyring/tests/threading.rs | crates/uv-keyring/tests/threading.rs | #![cfg(feature = "native-auth")]
use common::{generate_random_string, init_logger};
use uv_keyring::{Entry, Error};
mod common;
#[tokio::test]
async fn test_create_then_move() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).unwrap();
let handle = tokio::spawn(async move {
let password = "test ascii password";
entry
.set_password(password)
.await
.expect("Can't set initial ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set initial ascii passwords don't match"
);
let password = "このきれいな花は桜です";
entry
.set_password(password)
.await
.expect("Can't set non-ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get non-ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set non-ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete non-ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted non-ascii password"
);
});
handle.await.expect("Task failed");
}
#[tokio::test]
async fn test_simultaneous_create_then_move() {
init_logger();
let mut handles = vec![];
for i in 0..10 {
let name = format!("{}-{}", generate_random_string(), i);
let entry = Entry::new(&name, &name).expect("Can't create entry");
let handle = tokio::spawn(async move {
entry
.set_password(&name)
.await
.expect("Can't set ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, name,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
});
handles.push(handle);
}
for handle in handles {
handle.await.expect("Task failed");
}
}
#[tokio::test]
#[cfg(not(target_os = "windows"))]
async fn test_create_set_then_move() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let password = "test ascii password";
entry
.set_password(password)
.await
.expect("Can't set ascii password");
let handle = tokio::spawn(async move {
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
});
handle.await.expect("Task failed");
}
#[tokio::test]
#[cfg(not(target_os = "windows"))]
async fn test_simultaneous_create_set_then_move() {
init_logger();
let mut handles = vec![];
for i in 0..10 {
let name = format!("{}-{}", generate_random_string(), i);
let entry = Entry::new(&name, &name).expect("Can't create entry");
entry
.set_password(&name)
.await
.expect("Can't set ascii password");
let handle = tokio::spawn(async move {
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, name,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
});
handles.push(handle);
}
for handle in handles {
handle.await.expect("Task failed");
}
}
#[tokio::test]
async fn test_simultaneous_independent_create_set() {
init_logger();
let mut handles = vec![];
for i in 0..10 {
let name = format!("thread_entry{i}");
let handle = tokio::spawn(async move {
let entry = Entry::new(&name, &name).expect("Can't create entry");
entry
.set_password(&name)
.await
.expect("Can't set ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, name,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
});
handles.push(handle);
}
for handle in handles {
handle.await.expect("Task failed");
}
}
#[tokio::test]
#[cfg(any(target_os = "macos", target_os = "windows"))]
async fn test_multiple_create_delete_single_thread() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let repeats = 10;
for _i in 0..repeats {
entry
.set_password(&name)
.await
.expect("Can't set ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, name,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
}
}
/// Empirically, this test frequently flakes on Windows indicating that these operations are
/// not concurrency-safe.
#[tokio::test]
#[cfg(target_os = "macos")]
async fn test_simultaneous_multiple_create_delete_single_thread() {
init_logger();
let mut handles = vec![];
for t in 0..10 {
let name = generate_random_string();
let handle = tokio::spawn(async move {
let name = format!("{name}-{t}");
let entry = Entry::new(&name, &name).expect("Can't create entry");
let repeats = 10;
for _i in 0..repeats {
entry
.set_password(&name)
.await
.expect("Can't set ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, name,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
}
});
handles.push(handle);
}
for handle in handles {
handle.await.expect("Task failed");
}
}
| 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-keyring/tests/basic.rs | crates/uv-keyring/tests/basic.rs | #![cfg(feature = "native-auth")]
use common::{generate_random_bytes_of_len, generate_random_string, init_logger};
use uv_keyring::{Entry, Error};
mod common;
#[tokio::test]
async fn test_missing_entry() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Missing entry has password"
);
}
#[tokio::test]
#[cfg(target_os = "linux")]
async fn test_empty_password() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let in_pass = "";
entry
.set_password(in_pass)
.await
.expect("Can't set empty password");
let out_pass = entry
.get_password()
.await
.expect("Can't get empty password");
assert_eq!(
in_pass, out_pass,
"Retrieved and set empty passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted password"
);
}
#[tokio::test]
async fn test_round_trip_ascii_password() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let password = "test ascii password";
entry
.set_password(password)
.await
.expect("Can't set ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted ascii password"
);
}
#[tokio::test]
async fn test_round_trip_non_ascii_password() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let password = "このきれいな花は桜です";
entry
.set_password(password)
.await
.expect("Can't set non-ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get non-ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set non-ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete non-ascii password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted non-ascii password"
);
}
#[tokio::test]
async fn test_round_trip_random_secret() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let secret = generate_random_bytes_of_len(24);
entry
.set_secret(secret.as_slice())
.await
.expect("Can't set random secret");
let stored_secret = entry.get_secret().await.expect("Can't get random secret");
assert_eq!(
&stored_secret,
secret.as_slice(),
"Retrieved and set random secrets don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete random secret");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted random secret"
);
}
#[tokio::test]
async fn test_update() {
init_logger();
let name = generate_random_string();
let entry = Entry::new(&name, &name).expect("Can't create entry");
let password = "test ascii password";
entry
.set_password(password)
.await
.expect("Can't set initial ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get ascii password");
assert_eq!(
stored_password, password,
"Retrieved and set initial ascii passwords don't match"
);
let password = "このきれいな花は桜です";
entry
.set_password(password)
.await
.expect("Can't update ascii with non-ascii password");
let stored_password = entry
.get_password()
.await
.expect("Can't get non-ascii password");
assert_eq!(
stored_password, password,
"Retrieved and updated non-ascii passwords don't match"
);
entry
.delete_credential()
.await
.expect("Can't delete updated password");
assert!(
matches!(entry.get_password().await, Err(Error::NoEntry)),
"Able to read a deleted updated password"
);
}
| 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-keyring/tests/common/mod.rs | crates/uv-keyring/tests/common/mod.rs | #![allow(dead_code)] // not all of these utilities are used by all tests
/// When tests fail, they leave keys behind, and those keys
/// have to be cleaned up before the tests can be run again
/// in order to avoid bad results. So it's a lot easier just
/// to have tests use a random string for key names to avoid
/// the conflicts, and then do any needed cleanup once everything
/// is working correctly. So tests make keys with these functions.
/// When tests fail, they leave keys behind, and those keys
/// have to be cleaned up before the tests can be run again
/// in order to avoid bad results. So it's a lot easier just
/// to have tests use a random string for key names to avoid
/// the conflicts, and then do any needed cleanup once everything
/// is working correctly. So we export this function for tests to use.
pub(crate) fn generate_random_string_of_len(len: usize) -> String {
use fastrand;
use std::iter::repeat_with;
repeat_with(fastrand::alphanumeric).take(len).collect()
}
pub(crate) fn generate_random_string() -> String {
generate_random_string_of_len(30)
}
pub(crate) fn generate_random_bytes_of_len(len: usize) -> Vec<u8> {
use fastrand;
use std::iter::repeat_with;
repeat_with(|| fastrand::u8(..)).take(len).collect()
}
pub(crate) fn init_logger() {
let _ = env_logger::builder().is_test(true).try_init();
}
| 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-tool/src/lib.rs | crates/uv-tool/src/lib.rs | use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use fs_err as fs;
use fs_err::File;
use thiserror::Error;
use tracing::{debug, warn};
use uv_cache::Cache;
use uv_dirs::user_executable_directory;
use uv_fs::{LockedFile, LockedFileError, LockedFileMode, Simplified};
use uv_install_wheel::read_record_file;
use uv_installer::SitePackages;
use uv_normalize::{InvalidNameError, PackageName};
use uv_pep440::Version;
use uv_preview::Preview;
use uv_python::{Interpreter, PythonEnvironment};
use uv_state::{StateBucket, StateStore};
use uv_static::EnvVars;
use uv_virtualenv::remove_virtualenv;
pub use receipt::ToolReceipt;
pub use tool::{Tool, ToolEntrypoint};
mod receipt;
mod tool;
/// A wrapper around [`PythonEnvironment`] for tools that provides additional functionality.
#[derive(Debug, Clone)]
pub struct ToolEnvironment {
environment: PythonEnvironment,
name: PackageName,
}
impl ToolEnvironment {
pub fn new(environment: PythonEnvironment, name: PackageName) -> Self {
Self { environment, name }
}
/// Return the [`Version`] of the tool package in this environment.
pub fn version(&self) -> Result<Version, Error> {
let site_packages = SitePackages::from_environment(&self.environment).map_err(|err| {
Error::EnvironmentRead(self.environment.root().to_path_buf(), err.to_string())
})?;
let packages = site_packages.get_packages(&self.name);
let package = packages
.first()
.ok_or_else(|| Error::MissingToolPackage(self.name.clone()))?;
Ok(package.version().clone())
}
/// Get the underlying [`PythonEnvironment`].
pub fn into_environment(self) -> PythonEnvironment {
self.environment
}
/// Get a reference to the underlying [`PythonEnvironment`].
pub fn environment(&self) -> &PythonEnvironment {
&self.environment
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
LockedFile(#[from] LockedFileError),
#[error("Failed to update `uv-receipt.toml` at {0}")]
ReceiptWrite(PathBuf, #[source] Box<toml_edit::ser::Error>),
#[error("Failed to read `uv-receipt.toml` at {0}")]
ReceiptRead(PathBuf, #[source] Box<toml::de::Error>),
#[error(transparent)]
VirtualEnvError(#[from] uv_virtualenv::Error),
#[error("Failed to read package entry points {0}")]
EntrypointRead(#[from] uv_install_wheel::Error),
#[error("Failed to find a directory to install executables into")]
NoExecutableDirectory,
#[error(transparent)]
ToolName(#[from] InvalidNameError),
#[error(transparent)]
EnvironmentError(#[from] uv_python::Error),
#[error("Failed to find a receipt for tool `{0}` at {1}")]
MissingToolReceipt(String, PathBuf),
#[error("Failed to read tool environment packages at `{0}`: {1}")]
EnvironmentRead(PathBuf, String),
#[error("Failed find package `{0}` in tool environment")]
MissingToolPackage(PackageName),
#[error("Tool `{0}` environment not found at `{1}`")]
ToolEnvironmentNotFound(PackageName, PathBuf),
}
impl Error {
pub fn as_io_error(&self) -> Option<&io::Error> {
match self {
Self::Io(err) => Some(err),
Self::LockedFile(err) => err.as_io_error(),
Self::VirtualEnvError(uv_virtualenv::Error::Io(err)) => Some(err),
Self::ReceiptWrite(_, _)
| Self::ReceiptRead(_, _)
| Self::VirtualEnvError(_)
| Self::EntrypointRead(_)
| Self::NoExecutableDirectory
| Self::ToolName(_)
| Self::EnvironmentError(_)
| Self::MissingToolReceipt(_, _)
| Self::EnvironmentRead(_, _)
| Self::MissingToolPackage(_)
| Self::ToolEnvironmentNotFound(_, _) => None,
}
}
}
/// A collection of uv-managed tools installed on the current system.
#[derive(Debug, Clone)]
pub struct InstalledTools {
/// The path to the top-level directory of the tools.
root: PathBuf,
}
impl InstalledTools {
/// A directory for tools at `root`.
fn from_path(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
/// Create a new [`InstalledTools`] from settings.
///
/// Prefer, in order:
///
/// 1. The specific tool directory specified by the user, i.e., `UV_TOOL_DIR`
/// 2. A directory in the system-appropriate user-level data directory, e.g., `~/.local/uv/tools`
/// 3. A directory in the local data directory, e.g., `./.uv/tools`
pub fn from_settings() -> Result<Self, Error> {
if let Some(tool_dir) = std::env::var_os(EnvVars::UV_TOOL_DIR).filter(|s| !s.is_empty()) {
Ok(Self::from_path(std::path::absolute(tool_dir)?))
} else {
Ok(Self::from_path(
StateStore::from_settings(None)?.bucket(StateBucket::Tools),
))
}
}
/// Return the expected directory for a tool with the given [`PackageName`].
pub fn tool_dir(&self, name: &PackageName) -> PathBuf {
self.root.join(name.to_string())
}
/// Return the metadata for all installed tools.
///
/// If a tool is present, but is missing a receipt or the receipt is invalid, the tool will be
/// included with an error.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
#[allow(clippy::type_complexity)]
pub fn tools(&self) -> Result<Vec<(PackageName, Result<Tool, Error>)>, Error> {
let mut tools = Vec::new();
for directory in uv_fs::directories(self.root())? {
let Some(name) = directory
.file_name()
.and_then(|file_name| file_name.to_str())
else {
continue;
};
let name = PackageName::from_str(name)?;
let path = directory.join("uv-receipt.toml");
let contents = match fs_err::read_to_string(&path) {
Ok(contents) => contents,
Err(err) if err.kind() == io::ErrorKind::NotFound => {
let err = Error::MissingToolReceipt(name.to_string(), path);
tools.push((name, Err(err)));
continue;
}
Err(err) => return Err(err.into()),
};
match ToolReceipt::from_string(contents) {
Ok(tool_receipt) => tools.push((name, Ok(tool_receipt.tool))),
Err(err) => {
let err = Error::ReceiptRead(path, Box::new(err));
tools.push((name, Err(err)));
}
}
}
Ok(tools)
}
/// Get the receipt for the given tool.
///
/// If the tool is not installed, returns `Ok(None)`. If the receipt is invalid, returns an
/// error.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
pub fn get_tool_receipt(&self, name: &PackageName) -> Result<Option<Tool>, Error> {
let path = self.tool_dir(name).join("uv-receipt.toml");
match ToolReceipt::from_path(&path) {
Ok(tool_receipt) => Ok(Some(tool_receipt.tool)),
Err(Error::Io(err)) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
/// Grab a file lock for the tools 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?)
}
/// Add a receipt for a tool.
///
/// Any existing receipt will be replaced.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
pub fn add_tool_receipt(&self, name: &PackageName, tool: Tool) -> Result<(), Error> {
let tool_receipt = ToolReceipt::from(tool);
let path = self.tool_dir(name).join("uv-receipt.toml");
debug!(
"Adding metadata entry for tool `{name}` at {}",
path.user_display()
);
let doc = tool_receipt
.to_toml()
.map_err(|err| Error::ReceiptWrite(path.clone(), Box::new(err)))?;
// Save the modified `uv-receipt.toml`.
fs_err::write(&path, doc)?;
Ok(())
}
/// Remove the environment for a tool.
///
/// Does not remove the tool's entrypoints.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
///
/// # Errors
///
/// If no such environment exists for the tool.
pub fn remove_environment(&self, name: &PackageName) -> Result<(), Error> {
let environment_path = self.tool_dir(name);
debug!(
"Deleting environment for tool `{name}` at {}",
environment_path.user_display()
);
remove_virtualenv(environment_path.as_path())?;
Ok(())
}
/// Return the [`PythonEnvironment`] for a given tool, if it exists.
///
/// Returns `Ok(None)` if the environment does not exist or is linked to a non-existent
/// interpreter.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
pub fn get_environment(
&self,
name: &PackageName,
cache: &Cache,
) -> Result<Option<ToolEnvironment>, Error> {
let environment_path = self.tool_dir(name);
match PythonEnvironment::from_root(&environment_path, cache) {
Ok(venv) => {
debug!(
"Found existing environment for tool `{name}`: {}",
environment_path.user_display()
);
Ok(Some(ToolEnvironment::new(venv, name.clone())))
}
Err(uv_python::Error::MissingEnvironment(_)) => Ok(None),
Err(uv_python::Error::Query(uv_python::InterpreterError::NotFound(
interpreter_path,
))) => {
warn!(
"Ignoring existing virtual environment with missing Python interpreter: {}",
interpreter_path.user_display()
);
Ok(None)
}
Err(uv_python::Error::Query(uv_python::InterpreterError::BrokenSymlink(
broken_symlink,
))) => {
let target_path = fs_err::read_link(&broken_symlink.path)?;
warn!(
"Ignoring existing virtual environment linked to non-existent Python interpreter: {} -> {}",
broken_symlink.path.user_display(),
target_path.user_display()
);
Ok(None)
}
Err(err) => Err(err.into()),
}
}
/// Create the [`PythonEnvironment`] for a given tool, removing any existing environments.
///
/// Note it is generally incorrect to use this without [`Self::acquire_lock`].
pub fn create_environment(
&self,
name: &PackageName,
interpreter: Interpreter,
preview: Preview,
) -> Result<PythonEnvironment, Error> {
let environment_path = self.tool_dir(name);
// Remove any existing environment.
match fs_err::remove_dir_all(&environment_path) {
Ok(()) => {
debug!(
"Removed existing environment for tool `{name}`: {}",
environment_path.user_display()
);
}
Err(err) if err.kind() == io::ErrorKind::NotFound => (),
Err(err) => return Err(err.into()),
}
debug!(
"Creating environment for tool `{name}`: {}",
environment_path.user_display()
);
// Create a virtual environment.
let venv = uv_virtualenv::create_venv(
&environment_path,
interpreter,
uv_virtualenv::Prompt::None,
false,
uv_virtualenv::OnExisting::Remove(uv_virtualenv::RemovalReason::ManagedEnvironment),
false,
false,
false,
preview,
)?;
Ok(venv)
}
/// Create a temporary tools directory.
pub fn temp() -> Result<Self, Error> {
Ok(Self::from_path(
StateStore::temp()?.bucket(StateBucket::Tools),
))
}
/// Initialize the tools directory.
///
/// Ensures the directory is created.
pub fn init(self) -> Result<Self, Error> {
let root = &self.root;
// Create the tools directory, if it doesn't exist.
fs::create_dir_all(root)?;
// 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)
}
/// Return the path of the tools directory.
pub fn root(&self) -> &Path {
&self.root
}
}
/// A uv-managed tool installed on the current system..
#[derive(Debug, Clone)]
pub struct InstalledTool {
/// The path to the top-level directory of the tools.
path: PathBuf,
}
impl InstalledTool {
pub fn new(path: PathBuf) -> Result<Self, Error> {
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl std::fmt::Display for InstalledTool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.path
.file_name()
.unwrap_or(self.path.as_os_str())
.to_string_lossy()
)
}
}
/// Find the tool executable directory.
pub fn tool_executable_dir() -> Result<PathBuf, Error> {
user_executable_directory(Some(EnvVars::UV_TOOL_BIN_DIR)).ok_or(Error::NoExecutableDirectory)
}
/// Find the `.dist-info` directory for a package in an environment.
fn find_dist_info<'a>(
site_packages: &'a SitePackages,
package_name: &PackageName,
package_version: &Version,
) -> Result<&'a Path, Error> {
site_packages
.get_packages(package_name)
.iter()
.find(|package| package.version() == package_version)
.map(|dist| dist.install_path())
.ok_or_else(|| Error::MissingToolPackage(package_name.clone()))
}
/// Find the paths to the entry points provided by a package in an environment.
///
/// Entry points can either be true Python entrypoints (defined in `entrypoints.txt`) or scripts in
/// the `.data` directory.
///
/// Returns a list of `(name, path)` tuples.
pub fn entrypoint_paths(
site_packages: &SitePackages,
package_name: &PackageName,
package_version: &Version,
) -> Result<Vec<(String, PathBuf)>, Error> {
// Find the `.dist-info` directory in the installed environment.
let dist_info_path = find_dist_info(site_packages, package_name, package_version)?;
debug!(
"Looking at `.dist-info` at: {}",
dist_info_path.user_display()
);
// Read the RECORD file.
let record = read_record_file(&mut File::open(dist_info_path.join("RECORD"))?)?;
// The RECORD file uses relative paths, so we're looking for the relative path to be a prefix.
let layout = site_packages.interpreter().layout();
let script_relative = pathdiff::diff_paths(&layout.scheme.scripts, &layout.scheme.purelib)
.ok_or_else(|| {
io::Error::other(format!(
"Could not find relative path for: {}",
layout.scheme.scripts.simplified_display()
))
})?;
// Identify any installed binaries (both entrypoints and scripts from the `.data` directory).
let mut entrypoints = vec![];
for entry in record {
let relative_path = PathBuf::from(&entry.path);
let Ok(path_in_scripts) = relative_path.strip_prefix(&script_relative) else {
continue;
};
let absolute_path = layout.scheme.scripts.join(path_in_scripts);
let script_name = relative_path
.file_name()
.and_then(|filename| filename.to_str())
.map(ToString::to_string)
.unwrap_or(entry.path);
entrypoints.push((script_name, absolute_path));
}
Ok(entrypoints)
}
| 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-tool/src/receipt.rs | crates/uv-tool/src/receipt.rs | use std::path::Path;
use serde::Deserialize;
use crate::Tool;
/// A `uv-receipt.toml` file tracking the installation of a tool.
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct ToolReceipt {
pub(crate) tool: Tool,
/// The raw unserialized document.
#[serde(skip)]
pub(crate) raw: String,
}
impl ToolReceipt {
/// Parse a [`ToolReceipt`] from a raw TOML string.
pub(crate) fn from_string(raw: String) -> Result<Self, toml::de::Error> {
let tool = toml::from_str(&raw)?;
Ok(Self { raw, ..tool })
}
/// Read a [`ToolReceipt`] from the given path.
pub(crate) fn from_path(path: &Path) -> Result<Self, crate::Error> {
match fs_err::read_to_string(path) {
Ok(contents) => Ok(Self::from_string(contents)
.map_err(|err| crate::Error::ReceiptRead(path.to_owned(), Box::new(err)))?),
Err(err) => Err(err.into()),
}
}
/// Returns the TOML representation of this receipt.
pub(crate) fn to_toml(&self) -> Result<String, toml_edit::ser::Error> {
// We construct a TOML document manually instead of going through Serde to enable
// the use of inline tables.
let mut doc = toml_edit::DocumentMut::new();
doc.insert("tool", toml_edit::Item::Table(self.tool.to_toml()?));
Ok(doc.to_string())
}
}
impl From<Tool> for ToolReceipt {
fn from(tool: Tool) -> Self {
Self {
tool,
raw: String::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-tool/src/tool.rs | crates/uv-tool/src/tool.rs | use std::fmt::{self, Display, Formatter};
use std::path::PathBuf;
use serde::Deserialize;
use toml_edit::{Array, Item, Table, Value, value};
use uv_distribution_types::Requirement;
use uv_fs::{PortablePath, Simplified};
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::PythonRequest;
use uv_settings::ToolOptions;
/// A tool entry.
#[derive(Debug, Clone, Deserialize)]
#[serde(try_from = "ToolWire", into = "ToolWire")]
pub struct Tool {
/// The requirements requested by the user during installation.
requirements: Vec<Requirement>,
/// The constraints requested by the user during installation.
constraints: Vec<Requirement>,
/// The overrides requested by the user during installation.
overrides: Vec<Requirement>,
/// The build constraints requested by the user during installation.
build_constraints: Vec<Requirement>,
/// The Python requested by the user during installation.
python: Option<PythonRequest>,
/// A mapping of entry point names to their metadata.
entrypoints: Vec<ToolEntrypoint>,
/// The [`ToolOptions`] used to install this tool.
options: ToolOptions,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct ToolWire {
#[serde(default)]
requirements: Vec<RequirementWire>,
#[serde(default)]
constraints: Vec<Requirement>,
#[serde(default)]
overrides: Vec<Requirement>,
#[serde(default)]
build_constraint_dependencies: Vec<Requirement>,
python: Option<PythonRequest>,
entrypoints: Vec<ToolEntrypoint>,
#[serde(default)]
options: ToolOptions,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
enum RequirementWire {
/// A [`Requirement`] following our uv-specific schema.
Requirement(Requirement),
/// A PEP 508-compatible requirement. We no longer write these, but there might be receipts out
/// there that still use them.
Deprecated(uv_pep508::Requirement<VerbatimParsedUrl>),
}
impl From<Tool> for ToolWire {
fn from(tool: Tool) -> Self {
Self {
requirements: tool
.requirements
.into_iter()
.map(RequirementWire::Requirement)
.collect(),
constraints: tool.constraints,
overrides: tool.overrides,
build_constraint_dependencies: tool.build_constraints,
python: tool.python,
entrypoints: tool.entrypoints,
options: tool.options,
}
}
}
impl TryFrom<ToolWire> for Tool {
type Error = serde::de::value::Error;
fn try_from(tool: ToolWire) -> Result<Self, Self::Error> {
Ok(Self {
requirements: tool
.requirements
.into_iter()
.map(|req| match req {
RequirementWire::Requirement(requirements) => requirements,
RequirementWire::Deprecated(requirement) => Requirement::from(requirement),
})
.collect(),
constraints: tool.constraints,
overrides: tool.overrides,
build_constraints: tool.build_constraint_dependencies,
python: tool.python,
entrypoints: tool.entrypoints,
options: tool.options,
})
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct ToolEntrypoint {
pub name: String,
pub install_path: PathBuf,
pub from: Option<String>,
}
impl Display for ToolEntrypoint {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
#[cfg(windows)]
{
write!(
f,
"{} ({})",
self.name,
self.install_path
.simplified_display()
.to_string()
.replace('/', "\\")
)
}
#[cfg(unix)]
{
write!(
f,
"{} ({})",
self.name,
self.install_path.simplified_display()
)
}
}
}
/// Format an array so that each element is on its own line and has a trailing comma.
///
/// Example:
///
/// ```toml
/// requirements = [
/// "foo",
/// "bar",
/// ]
/// ```
fn each_element_on_its_line_array(elements: impl Iterator<Item = impl Into<Value>>) -> Array {
let mut array = elements
.map(Into::into)
.map(|mut value| {
// Each dependency is on its own line and indented.
value.decor_mut().set_prefix("\n ");
value
})
.collect::<Array>();
// With a trailing comma, inserting another entry doesn't change the preceding line,
// reducing the diff noise.
array.set_trailing_comma(true);
// The line break between the last element's comma and the closing square bracket.
array.set_trailing("\n");
array
}
impl Tool {
/// Create a new `Tool`.
pub fn new(
requirements: Vec<Requirement>,
constraints: Vec<Requirement>,
overrides: Vec<Requirement>,
build_constraints: Vec<Requirement>,
python: Option<PythonRequest>,
entrypoints: impl IntoIterator<Item = ToolEntrypoint>,
options: ToolOptions,
) -> Self {
let mut entrypoints: Vec<_> = entrypoints.into_iter().collect();
entrypoints.sort();
Self {
requirements,
constraints,
overrides,
build_constraints,
python,
entrypoints,
options,
}
}
/// Create a new [`Tool`] with the given [`ToolOptions`].
#[must_use]
pub fn with_options(self, options: ToolOptions) -> Self {
Self { options, ..self }
}
/// Returns the TOML table for this tool.
pub(crate) fn to_toml(&self) -> Result<Table, toml_edit::ser::Error> {
let mut table = Table::new();
if !self.requirements.is_empty() {
table.insert("requirements", {
let requirements = self
.requirements
.iter()
.map(|requirement| {
serde::Serialize::serialize(
&requirement,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let requirements = match requirements.as_slice() {
[] => Array::new(),
[requirement] => Array::from_iter([requirement]),
requirements => each_element_on_its_line_array(requirements.iter()),
};
value(requirements)
});
}
if !self.constraints.is_empty() {
table.insert("constraints", {
let constraints = self
.constraints
.iter()
.map(|constraint| {
serde::Serialize::serialize(
&constraint,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let constraints = match constraints.as_slice() {
[] => Array::new(),
[constraint] => Array::from_iter([constraint]),
constraints => each_element_on_its_line_array(constraints.iter()),
};
value(constraints)
});
}
if !self.overrides.is_empty() {
table.insert("overrides", {
let overrides = self
.overrides
.iter()
.map(|r#override| {
serde::Serialize::serialize(
&r#override,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let overrides = match overrides.as_slice() {
[] => Array::new(),
[r#override] => Array::from_iter([r#override]),
overrides => each_element_on_its_line_array(overrides.iter()),
};
value(overrides)
});
}
if !self.build_constraints.is_empty() {
table.insert("build-constraint-dependencies", {
let build_constraints = self
.build_constraints
.iter()
.map(|r#build_constraint| {
serde::Serialize::serialize(
&r#build_constraint,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let build_constraints = match build_constraints.as_slice() {
[] => Array::new(),
[r#build_constraint] => Array::from_iter([r#build_constraint]),
build_constraints => each_element_on_its_line_array(build_constraints.iter()),
};
value(build_constraints)
});
}
if let Some(ref python) = self.python {
table.insert(
"python",
value(serde::Serialize::serialize(
&python,
toml_edit::ser::ValueSerializer::new(),
)?),
);
}
table.insert("entrypoints", {
let entrypoints = each_element_on_its_line_array(
self.entrypoints
.iter()
.map(ToolEntrypoint::to_toml)
.map(Table::into_inline_table),
);
value(entrypoints)
});
if self.options != ToolOptions::default() {
let serialized =
serde::Serialize::serialize(&self.options, toml_edit::ser::ValueSerializer::new())?;
let Value::InlineTable(serialized) = serialized else {
return Err(toml_edit::ser::Error::Custom(
"Expected an inline table".to_string(),
));
};
table.insert("options", Item::Table(serialized.into_table()));
}
Ok(table)
}
pub fn entrypoints(&self) -> &[ToolEntrypoint] {
&self.entrypoints
}
pub fn requirements(&self) -> &[Requirement] {
&self.requirements
}
pub fn constraints(&self) -> &[Requirement] {
&self.constraints
}
pub fn overrides(&self) -> &[Requirement] {
&self.overrides
}
pub fn build_constraints(&self) -> &[Requirement] {
&self.build_constraints
}
pub fn python(&self) -> &Option<PythonRequest> {
&self.python
}
pub fn options(&self) -> &ToolOptions {
&self.options
}
}
impl ToolEntrypoint {
/// Create a new [`ToolEntrypoint`].
pub fn new(name: &str, install_path: PathBuf, from: String) -> Self {
let name = name
.trim_end_matches(std::env::consts::EXE_SUFFIX)
.to_string();
Self {
name,
install_path,
from: Some(from),
}
}
/// Returns the TOML table for this entrypoint.
pub(crate) fn to_toml(&self) -> Table {
let mut table = Table::new();
table.insert("name", value(&self.name));
table.insert(
"install-path",
// Use cross-platform slashes so the toml string type does not change
value(PortablePath::from(&self.install_path).to_string()),
);
if let Some(from) = &self.from {
table.insert("from", value(from));
}
table
}
}
| 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/src/lib.rs | crates/uv-distribution/src/lib.rs | pub use distribution_database::{DistributionDatabase, HttpArchivePointer, LocalArchivePointer};
pub use download::LocalWheel;
pub use error::Error;
pub use index::{BuiltWheelIndex, RegistryWheelIndex};
pub use metadata::{
ArchiveMetadata, BuildRequires, FlatRequiresDist, LoweredExtraBuildDependencies,
LoweredRequirement, LoweringError, Metadata, MetadataError, RequiresDist,
SourcedDependencyGroups,
};
pub use reporter::Reporter;
pub use source::prune;
mod archive;
mod distribution_database;
mod download;
mod error;
mod index;
mod metadata;
mod reporter;
mod source;
| 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/src/download.rs | crates/uv-distribution/src/download.rs | use std::path::Path;
use uv_cache_info::CacheInfo;
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{BuildInfo, CachedDist, Dist, Hashed};
use uv_metadata::read_flat_wheel_metadata;
use uv_pypi_types::{HashDigest, HashDigests, ResolutionMetadata};
use crate::Error;
/// A locally available wheel.
#[derive(Debug, Clone)]
pub struct LocalWheel {
/// The remote distribution from which this wheel was downloaded.
pub(crate) dist: Dist,
/// The parsed filename.
pub(crate) filename: WheelFilename,
/// The canonicalized path in the cache directory to which the wheel was downloaded.
/// Typically, a directory within the archive bucket.
pub(crate) archive: Box<Path>,
/// The cache info of the wheel.
pub(crate) cache: CacheInfo,
/// The build info, if available.
pub(crate) build: Option<BuildInfo>,
/// The computed hashes of the wheel.
pub(crate) hashes: HashDigests,
}
impl LocalWheel {
/// Return the path to the downloaded wheel's entry in the cache.
pub fn target(&self) -> &Path {
&self.archive
}
/// Return the [`Dist`] from which this wheel was downloaded.
pub fn remote(&self) -> &Dist {
&self.dist
}
/// Return the [`WheelFilename`] of this wheel.
pub fn filename(&self) -> &WheelFilename {
&self.filename
}
/// Read the [`ResolutionMetadata`] from a wheel.
pub fn metadata(&self) -> Result<ResolutionMetadata, Error> {
read_flat_wheel_metadata(&self.filename, &self.archive)
.map_err(|err| Error::WheelMetadata(self.archive.to_path_buf(), Box::new(err)))
}
}
impl Hashed for LocalWheel {
fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
}
/// Convert a [`LocalWheel`] into a [`CachedDist`].
impl From<LocalWheel> for CachedDist {
fn from(wheel: LocalWheel) -> Self {
Self::from_remote(
wheel.dist,
wheel.filename,
wheel.hashes,
wheel.cache,
wheel.build,
wheel.archive,
)
}
}
impl std::fmt::Display for LocalWheel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.remote())
}
}
| 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/src/archive.rs | crates/uv-distribution/src/archive.rs | use uv_cache::{ARCHIVE_VERSION, ArchiveId, Cache};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::Hashed;
use uv_pypi_types::{HashDigest, HashDigests};
/// An archive (unzipped wheel) that exists in the local cache.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Archive {
/// The unique ID of the entry in the wheel's archive bucket.
pub id: ArchiveId,
/// The computed hashes of the archive.
pub hashes: HashDigests,
/// The filename of the wheel.
pub filename: WheelFilename,
/// The version of the archive bucket.
pub version: u8,
}
impl Archive {
/// Create a new [`Archive`] with the given ID and hashes.
pub(crate) fn new(id: ArchiveId, hashes: HashDigests, filename: WheelFilename) -> Self {
Self {
id,
hashes,
filename,
version: ARCHIVE_VERSION,
}
}
/// Returns `true` if the archive exists in the cache.
pub(crate) fn exists(&self, cache: &Cache) -> bool {
self.version == ARCHIVE_VERSION && cache.archive(&self.id).exists()
}
}
impl Hashed for Archive {
fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
}
| 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/src/error.rs | crates/uv-distribution/src/error.rs | use std::path::PathBuf;
use owo_colors::OwoColorize;
use tokio::task::JoinError;
use zip::result::ZipError;
use crate::metadata::MetadataError;
use uv_cache::Error as CacheError;
use uv_client::WrappedReqwestError;
use uv_distribution_filename::{WheelFilename, WheelFilenameError};
use uv_distribution_types::{InstalledDist, InstalledDistError, IsBuildBackendError};
use uv_fs::Simplified;
use uv_git::GitError;
use uv_normalize::PackageName;
use uv_pep440::{Version, VersionSpecifiers};
use uv_platform_tags::Platform;
use uv_pypi_types::{HashAlgorithm, HashDigest};
use uv_redacted::DisplaySafeUrl;
use uv_types::AnyErrorBuild;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Building source distributions is disabled")]
NoBuild,
// Network error
#[error("Expected an absolute path, but received: {}", _0.user_display())]
RelativePath(PathBuf),
#[error(transparent)]
InvalidUrl(#[from] uv_distribution_types::ToUrlError),
#[error("Expected a file URL, but received: {0}")]
NonFileUrl(DisplaySafeUrl),
#[error(transparent)]
Git(#[from] uv_git::GitResolverError),
#[error(transparent)]
Reqwest(#[from] WrappedReqwestError),
#[error(transparent)]
Client(#[from] uv_client::Error),
// Cache writing error
#[error("Failed to read from the distribution cache")]
CacheRead(#[source] std::io::Error),
#[error("Failed to write to the distribution cache")]
CacheWrite(#[source] std::io::Error),
#[error("Failed to acquire lock on the distribution cache")]
CacheLock(#[source] CacheError),
#[error("Failed to deserialize cache entry")]
CacheDecode(#[from] rmp_serde::decode::Error),
#[error("Failed to serialize cache entry")]
CacheEncode(#[from] rmp_serde::encode::Error),
#[error("Failed to walk the distribution cache")]
CacheWalk(#[source] walkdir::Error),
#[error(transparent)]
CacheInfo(#[from] uv_cache_info::CacheInfoError),
// Build error
#[error(transparent)]
Build(AnyErrorBuild),
#[error("Built wheel has an invalid filename")]
WheelFilename(#[from] WheelFilenameError),
#[error("Package metadata name `{metadata}` does not match given name `{given}`")]
WheelMetadataNameMismatch {
given: PackageName,
metadata: PackageName,
},
#[error("Package metadata version `{metadata}` does not match given version `{given}`")]
WheelMetadataVersionMismatch { given: Version, metadata: Version },
#[error(
"Package metadata name `{metadata}` does not match `{filename}` from the wheel filename"
)]
WheelFilenameNameMismatch {
filename: PackageName,
metadata: PackageName,
},
#[error(
"Package metadata version `{metadata}` does not match `{filename}` from the wheel filename"
)]
WheelFilenameVersionMismatch {
filename: Version,
metadata: Version,
},
/// This shouldn't happen, it's a bug in the build backend.
#[error(
"The built wheel `{}` is not compatible with the current Python {}.{} on {} {}",
filename,
python_version.0,
python_version.1,
python_platform.os(),
python_platform.arch(),
)]
BuiltWheelIncompatibleHostPlatform {
filename: WheelFilename,
python_platform: Platform,
python_version: (u8, u8),
},
/// This may happen when trying to cross-install native dependencies without their build backend
/// being aware that the target is a cross-install.
#[error(
"The built wheel `{}` is not compatible with the target Python {}.{} on {} {}. Consider using `--no-build` to disable building wheels.",
filename,
python_version.0,
python_version.1,
python_platform.os(),
python_platform.arch(),
)]
BuiltWheelIncompatibleTargetPlatform {
filename: WheelFilename,
python_platform: Platform,
python_version: (u8, u8),
},
#[error("Failed to parse metadata from built wheel")]
Metadata(#[from] uv_pypi_types::MetadataError),
#[error("Failed to read metadata: `{}`", _0.user_display())]
WheelMetadata(PathBuf, #[source] Box<uv_metadata::Error>),
#[error("Failed to read metadata from installed package `{0}`")]
ReadInstalled(Box<InstalledDist>, #[source] InstalledDistError),
#[error("Failed to read zip archive from built wheel")]
Zip(#[from] ZipError),
#[error("Failed to extract archive: {0}")]
Extract(String, #[source] uv_extract::Error),
#[error("The source distribution is missing a `PKG-INFO` file")]
MissingPkgInfo,
#[error("The source distribution `{}` has no subdirectory `{}`", _0, _1.display())]
MissingSubdirectory(DisplaySafeUrl, PathBuf),
#[error("The source distribution `{0}` is missing Git LFS artifacts.")]
MissingGitLfsArtifacts(DisplaySafeUrl, #[source] GitError),
#[error("Failed to extract static metadata from `PKG-INFO`")]
PkgInfo(#[source] uv_pypi_types::MetadataError),
#[error("Failed to extract metadata from `requires.txt`")]
RequiresTxt(#[source] uv_pypi_types::MetadataError),
#[error("The source distribution is missing a `pyproject.toml` file")]
MissingPyprojectToml,
#[error("Failed to extract static metadata from `pyproject.toml`")]
PyprojectToml(#[source] uv_pypi_types::MetadataError),
#[error("Unsupported scheme in URL: {0}")]
UnsupportedScheme(String),
#[error(transparent)]
MetadataLowering(#[from] MetadataError),
#[error("Distribution not found at: {0}")]
NotFound(DisplaySafeUrl),
#[error("Attempted to re-extract the source distribution for `{}`, but the {} hash didn't match. Run `{}` to clear the cache.", _0, _1, "uv cache clean".green())]
CacheHeal(String, HashAlgorithm),
#[error("The source distribution requires Python {0}, but {1} is installed")]
RequiresPython(VersionSpecifiers, Version),
#[error("Failed to identify base Python interpreter")]
BaseInterpreter(#[source] std::io::Error),
/// A generic request middleware error happened while making a request.
/// Refer to the error message for more details.
#[error(transparent)]
ReqwestMiddlewareError(#[from] anyhow::Error),
/// Should not occur; only seen when another task panicked.
#[error("The task executor is broken, did some other task panic?")]
Join(#[from] JoinError),
/// An I/O error that occurs while exhausting a reader to compute a hash.
#[error("Failed to hash distribution")]
HashExhaustion(#[source] std::io::Error),
#[error("Hash mismatch for `{distribution}`\n\nExpected:\n{expected}\n\nComputed:\n{actual}")]
MismatchedHashes {
distribution: String,
expected: String,
actual: String,
},
#[error(
"Hash-checking is enabled, but no hashes were provided or computed for: `{distribution}`"
)]
MissingHashes { distribution: String },
#[error(
"Hash-checking is enabled, but no hashes were computed for: `{distribution}`\n\nExpected:\n{expected}"
)]
MissingActualHashes {
distribution: String,
expected: String,
},
#[error(
"Hash-checking is enabled, but no hashes were provided for: `{distribution}`\n\nComputed:\n{actual}"
)]
MissingExpectedHashes {
distribution: String,
actual: String,
},
#[error("Hash-checking is not supported for local directories: `{0}`")]
HashesNotSupportedSourceTree(String),
#[error("Hash-checking is not supported for Git repositories: `{0}`")]
HashesNotSupportedGit(String),
}
impl From<reqwest::Error> for Error {
fn from(error: reqwest::Error) -> Self {
Self::Reqwest(WrappedReqwestError::from(error))
}
}
impl From<reqwest_middleware::Error> for Error {
fn from(error: reqwest_middleware::Error) -> Self {
match error {
reqwest_middleware::Error::Middleware(error) => Self::ReqwestMiddlewareError(error),
reqwest_middleware::Error::Reqwest(error) => {
Self::Reqwest(WrappedReqwestError::from(error))
}
}
}
}
impl IsBuildBackendError for Error {
fn is_build_backend_error(&self) -> bool {
match self {
Self::Build(err) => err.is_build_backend_error(),
_ => false,
}
}
}
impl Error {
/// Construct a hash mismatch error.
pub fn hash_mismatch(
distribution: String,
expected: &[HashDigest],
actual: &[HashDigest],
) -> Self {
match (expected.is_empty(), actual.is_empty()) {
(true, true) => Self::MissingHashes { distribution },
(true, false) => {
let actual = actual
.iter()
.map(|hash| format!(" {hash}"))
.collect::<Vec<_>>()
.join("\n");
Self::MissingExpectedHashes {
distribution,
actual,
}
}
(false, true) => {
let expected = expected
.iter()
.map(|hash| format!(" {hash}"))
.collect::<Vec<_>>()
.join("\n");
Self::MissingActualHashes {
distribution,
expected,
}
}
(false, false) => {
let expected = expected
.iter()
.map(|hash| format!(" {hash}"))
.collect::<Vec<_>>()
.join("\n");
let actual = actual
.iter()
.map(|hash| format!(" {hash}"))
.collect::<Vec<_>>()
.join("\n");
Self::MismatchedHashes {
distribution,
expected,
actual,
}
}
}
}
}
| 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/src/reporter.rs | crates/uv-distribution/src/reporter.rs | use std::sync::Arc;
use uv_distribution_types::BuildableSource;
use uv_normalize::PackageName;
use uv_redacted::DisplaySafeUrl;
pub trait Reporter: Send + Sync {
/// Callback to invoke when a source distribution build is kicked off.
fn on_build_start(&self, source: &BuildableSource) -> usize;
/// Callback to invoke when a source distribution build is complete.
fn on_build_complete(&self, source: &BuildableSource, id: usize);
/// Callback to invoke when a repository checkout begins.
fn on_checkout_start(&self, url: &DisplaySafeUrl, rev: &str) -> usize;
/// Callback to invoke when a repository checkout completes.
fn on_checkout_complete(&self, url: &DisplaySafeUrl, rev: &str, id: usize);
/// Callback to invoke when a download is kicked off.
fn on_download_start(&self, name: &PackageName, size: Option<u64>) -> usize;
/// Callback to invoke when a download makes progress (i.e. some number of bytes are
/// downloaded).
fn on_download_progress(&self, id: usize, inc: u64);
/// Callback to invoke when a download is complete.
fn on_download_complete(&self, name: &PackageName, id: usize);
}
impl dyn Reporter {
/// Converts this reporter to a [`uv_git::Reporter`].
pub(crate) fn into_git_reporter(self: Arc<dyn Reporter>) -> Arc<dyn uv_git::Reporter> {
Arc::new(Facade {
reporter: self.clone(),
})
}
}
/// A facade for converting from [`Reporter`] to [`uv_git::Reporter`].
struct Facade {
reporter: Arc<dyn Reporter>,
}
impl uv_git::Reporter for Facade {
fn on_checkout_start(&self, url: &DisplaySafeUrl, rev: &str) -> usize {
self.reporter.on_checkout_start(url, rev)
}
fn on_checkout_complete(&self, url: &DisplaySafeUrl, rev: &str, id: usize) {
self.reporter.on_checkout_complete(url, rev, 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/src/distribution_database.rs | crates/uv-distribution/src/distribution_database.rs | use std::future::Future;
use std::io;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use futures::{FutureExt, TryStreamExt};
use tempfile::TempDir;
use tokio::io::{AsyncRead, AsyncSeekExt, ReadBuf};
use tokio::sync::Semaphore;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use tracing::{Instrument, info_span, instrument, warn};
use url::Url;
use uv_cache::{ArchiveId, CacheBucket, CacheEntry, WheelCache};
use uv_cache_info::{CacheInfo, Timestamp};
use uv_client::{
CacheControl, CachedClientError, Connectivity, DataWithCachePolicy, RegistryClient,
};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{
BuildInfo, BuildableSource, BuiltDist, Dist, File, HashPolicy, Hashed, IndexUrl, InstalledDist,
Name, SourceDist, ToUrlError,
};
use uv_extract::hash::Hasher;
use uv_fs::write_atomic;
use uv_platform_tags::Tags;
use uv_pypi_types::{HashDigest, HashDigests, PyProjectToml};
use uv_redacted::DisplaySafeUrl;
use uv_types::{BuildContext, BuildStack};
use crate::archive::Archive;
use crate::metadata::{ArchiveMetadata, Metadata};
use crate::source::SourceDistributionBuilder;
use crate::{Error, LocalWheel, Reporter, RequiresDist};
/// A cached high-level interface to convert distributions (a requirement resolved to a location)
/// to a wheel or wheel metadata.
///
/// For wheel metadata, this happens by either fetching the metadata from the remote wheel or by
/// building the source distribution. For wheel files, either the wheel is downloaded or a source
/// distribution is downloaded, built and the new wheel gets returned.
///
/// All kinds of wheel sources (index, URL, path) and source distribution source (index, URL, path,
/// Git) are supported.
///
/// This struct also has the task of acquiring locks around source dist builds in general and git
/// operation especially, as well as respecting concurrency limits.
pub struct DistributionDatabase<'a, Context: BuildContext> {
build_context: &'a Context,
builder: SourceDistributionBuilder<'a, Context>,
client: ManagedClient<'a>,
reporter: Option<Arc<dyn Reporter>>,
}
impl<'a, Context: BuildContext> DistributionDatabase<'a, Context> {
pub fn new(
client: &'a RegistryClient,
build_context: &'a Context,
concurrent_downloads: usize,
) -> Self {
Self {
build_context,
builder: SourceDistributionBuilder::new(build_context),
client: ManagedClient::new(client, concurrent_downloads),
reporter: None,
}
}
/// Set the build stack to use for the [`DistributionDatabase`].
#[must_use]
pub fn with_build_stack(self, build_stack: &'a BuildStack) -> Self {
Self {
builder: self.builder.with_build_stack(build_stack),
..self
}
}
/// Set the [`Reporter`] to use for the [`DistributionDatabase`].
#[must_use]
pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
builder: self.builder.with_reporter(reporter.clone()),
reporter: Some(reporter),
..self
}
}
/// Handle a specific `reqwest` error, and convert it to [`io::Error`].
fn handle_response_errors(&self, err: reqwest::Error) -> io::Error {
if err.is_timeout() {
io::Error::new(
io::ErrorKind::TimedOut,
format!(
"Failed to download distribution due to network timeout. Try increasing UV_HTTP_TIMEOUT (current value: {}s).",
self.client.unmanaged.timeout().as_secs()
),
)
} else {
io::Error::other(err)
}
}
/// Either fetch the wheel or fetch and build the source distribution
///
/// Returns a wheel that's compliant with the given platform tags.
///
/// While hashes will be generated in some cases, hash-checking is only enforced for source
/// distributions, and should be enforced by the caller for wheels.
#[instrument(skip_all, fields(%dist))]
pub async fn get_or_build_wheel(
&self,
dist: &Dist,
tags: &Tags,
hashes: HashPolicy<'_>,
) -> Result<LocalWheel, Error> {
match dist {
Dist::Built(built) => self.get_wheel(built, hashes).await,
Dist::Source(source) => self.build_wheel(source, tags, hashes).await,
}
}
/// Either fetch the only wheel metadata (directly from the index or with range requests) or
/// fetch and build the source distribution.
///
/// While hashes will be generated in some cases, hash-checking is only enforced for source
/// distributions, and should be enforced by the caller for wheels.
#[instrument(skip_all, fields(%dist))]
pub async fn get_installed_metadata(
&self,
dist: &InstalledDist,
) -> Result<ArchiveMetadata, Error> {
// If the metadata was provided by the user directly, prefer it.
if let Some(metadata) = self
.build_context
.dependency_metadata()
.get(dist.name(), Some(dist.version()))
{
return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
}
let metadata = dist
.read_metadata()
.map_err(|err| Error::ReadInstalled(Box::new(dist.clone()), err))?;
Ok(ArchiveMetadata::from_metadata23(metadata.clone()))
}
/// Either fetch the only wheel metadata (directly from the index or with range requests) or
/// fetch and build the source distribution.
///
/// While hashes will be generated in some cases, hash-checking is only enforced for source
/// distributions, and should be enforced by the caller for wheels.
#[instrument(skip_all, fields(%dist))]
pub async fn get_or_build_wheel_metadata(
&self,
dist: &Dist,
hashes: HashPolicy<'_>,
) -> Result<ArchiveMetadata, Error> {
match dist {
Dist::Built(built) => self.get_wheel_metadata(built, hashes).await,
Dist::Source(source) => {
self.build_wheel_metadata(&BuildableSource::Dist(source), hashes)
.await
}
}
}
/// Fetch a wheel from the cache or download it from the index.
///
/// While hashes will be generated in all cases, hash-checking is _not_ enforced and should
/// instead be enforced by the caller.
async fn get_wheel(
&self,
dist: &BuiltDist,
hashes: HashPolicy<'_>,
) -> Result<LocalWheel, Error> {
match dist {
BuiltDist::Registry(wheels) => {
let wheel = wheels.best_wheel();
let WheelTarget {
url,
extension,
size,
} = WheelTarget::try_from(&*wheel.file)?;
// Create a cache entry for the wheel.
let wheel_entry = self.build_context.cache().entry(
CacheBucket::Wheels,
WheelCache::Index(&wheel.index).wheel_dir(wheel.name().as_ref()),
wheel.filename.cache_key(),
);
// If the URL is a file URL, load the wheel directly.
if url.scheme() == "file" {
let path = url
.to_file_path()
.map_err(|()| Error::NonFileUrl(url.clone()))?;
return self
.load_wheel(
&path,
&wheel.filename,
WheelExtension::Whl,
wheel_entry,
dist,
hashes,
)
.await;
}
// Download and unzip.
match self
.stream_wheel(
url.clone(),
dist.index(),
&wheel.filename,
extension,
size,
&wheel_entry,
dist,
hashes,
)
.await
{
Ok(archive) => Ok(LocalWheel {
dist: Dist::Built(dist.clone()),
archive: self
.build_context
.cache()
.archive(&archive.id)
.into_boxed_path(),
hashes: archive.hashes,
filename: wheel.filename.clone(),
cache: CacheInfo::default(),
build: None,
}),
Err(Error::Extract(name, err)) => {
if err.is_http_streaming_unsupported() {
warn!(
"Streaming unsupported for {dist}; downloading wheel to disk ({err})"
);
} else if err.is_http_streaming_failed() {
warn!("Streaming failed for {dist}; downloading wheel to disk ({err})");
} else {
return Err(Error::Extract(name, err));
}
// If the request failed because streaming is unsupported, download the
// wheel directly.
let archive = self
.download_wheel(
url,
dist.index(),
&wheel.filename,
extension,
size,
&wheel_entry,
dist,
hashes,
)
.await?;
Ok(LocalWheel {
dist: Dist::Built(dist.clone()),
archive: self
.build_context
.cache()
.archive(&archive.id)
.into_boxed_path(),
hashes: archive.hashes,
filename: wheel.filename.clone(),
cache: CacheInfo::default(),
build: None,
})
}
Err(err) => Err(err),
}
}
BuiltDist::DirectUrl(wheel) => {
// Create a cache entry for the wheel.
let wheel_entry = self.build_context.cache().entry(
CacheBucket::Wheels,
WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
wheel.filename.cache_key(),
);
// Download and unzip.
match self
.stream_wheel(
wheel.url.raw().clone(),
None,
&wheel.filename,
WheelExtension::Whl,
None,
&wheel_entry,
dist,
hashes,
)
.await
{
Ok(archive) => Ok(LocalWheel {
dist: Dist::Built(dist.clone()),
archive: self
.build_context
.cache()
.archive(&archive.id)
.into_boxed_path(),
hashes: archive.hashes,
filename: wheel.filename.clone(),
cache: CacheInfo::default(),
build: None,
}),
Err(Error::Client(err)) if err.is_http_streaming_unsupported() => {
warn!(
"Streaming unsupported for {dist}; downloading wheel to disk ({err})"
);
// If the request failed because streaming is unsupported, download the
// wheel directly.
let archive = self
.download_wheel(
wheel.url.raw().clone(),
None,
&wheel.filename,
WheelExtension::Whl,
None,
&wheel_entry,
dist,
hashes,
)
.await?;
Ok(LocalWheel {
dist: Dist::Built(dist.clone()),
archive: self
.build_context
.cache()
.archive(&archive.id)
.into_boxed_path(),
hashes: archive.hashes,
filename: wheel.filename.clone(),
cache: CacheInfo::default(),
build: None,
})
}
Err(err) => Err(err),
}
}
BuiltDist::Path(wheel) => {
let cache_entry = self.build_context.cache().entry(
CacheBucket::Wheels,
WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
wheel.filename.cache_key(),
);
self.load_wheel(
&wheel.install_path,
&wheel.filename,
WheelExtension::Whl,
cache_entry,
dist,
hashes,
)
.await
}
}
}
/// Convert a source distribution into a wheel, fetching it from the cache or building it if
/// necessary.
///
/// The returned wheel is guaranteed to come from a distribution with a matching hash, and
/// no build processes will be executed for distributions with mismatched hashes.
async fn build_wheel(
&self,
dist: &SourceDist,
tags: &Tags,
hashes: HashPolicy<'_>,
) -> Result<LocalWheel, Error> {
let built_wheel = self
.builder
.download_and_build(&BuildableSource::Dist(dist), tags, hashes, &self.client)
.boxed_local()
.await?;
// Check that the wheel is compatible with its install target.
//
// When building a build dependency for a cross-install, the build dependency needs
// to install and run on the host instead of the target. In this case the `tags` are already
// for the host instead of the target, so this check passes.
if !built_wheel.filename.is_compatible(tags) {
return if tags.is_cross() {
Err(Error::BuiltWheelIncompatibleTargetPlatform {
filename: built_wheel.filename,
python_platform: tags.python_platform().clone(),
python_version: tags.python_version(),
})
} else {
Err(Error::BuiltWheelIncompatibleHostPlatform {
filename: built_wheel.filename,
python_platform: tags.python_platform().clone(),
python_version: tags.python_version(),
})
};
}
// Acquire the advisory lock.
#[cfg(windows)]
let _lock = {
let lock_entry = CacheEntry::new(
built_wheel.target.parent().unwrap(),
format!(
"{}.lock",
built_wheel.target.file_name().unwrap().to_str().unwrap()
),
);
lock_entry.lock().await.map_err(Error::CacheLock)?
};
// If the wheel was unzipped previously, respect it. Source distributions are
// cached under a unique revision ID, so unzipped directories are never stale.
match self.build_context.cache().resolve_link(&built_wheel.target) {
Ok(archive) => {
return Ok(LocalWheel {
dist: Dist::Source(dist.clone()),
archive: archive.into_boxed_path(),
filename: built_wheel.filename,
hashes: built_wheel.hashes,
cache: built_wheel.cache_info,
build: Some(built_wheel.build_info),
});
}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(Error::CacheRead(err)),
}
// Otherwise, unzip the wheel.
let id = self
.unzip_wheel(&built_wheel.path, &built_wheel.target)
.await?;
Ok(LocalWheel {
dist: Dist::Source(dist.clone()),
archive: self.build_context.cache().archive(&id).into_boxed_path(),
hashes: built_wheel.hashes,
filename: built_wheel.filename,
cache: built_wheel.cache_info,
build: Some(built_wheel.build_info),
})
}
/// Fetch the wheel metadata from the index, or from the cache if possible.
///
/// While hashes will be generated in some cases, hash-checking is _not_ enforced and should
/// instead be enforced by the caller.
async fn get_wheel_metadata(
&self,
dist: &BuiltDist,
hashes: HashPolicy<'_>,
) -> Result<ArchiveMetadata, Error> {
// If hash generation is enabled, and the distribution isn't hosted on a registry, get the
// entire wheel to ensure that the hashes are included in the response. If the distribution
// is hosted on an index, the hashes will be included in the simple metadata response.
// For hash _validation_, callers are expected to enforce the policy when retrieving the
// wheel.
//
// Historically, for `uv pip compile --universal`, we also generate hashes for
// registry-based distributions when the relevant registry doesn't provide them. This was
// motivated by `--find-links`. We continue that behavior (under `HashGeneration::All`) for
// backwards compatibility, but it's a little dubious, since we're only hashing _one_
// distribution here (as opposed to hashing all distributions for the version), and it may
// not even be a compatible distribution!
//
// TODO(charlie): Request the hashes via a separate method, to reduce the coupling in this API.
if hashes.is_generate(dist) {
let wheel = self.get_wheel(dist, hashes).await?;
// If the metadata was provided by the user directly, prefer it.
let metadata = if let Some(metadata) = self
.build_context
.dependency_metadata()
.get(dist.name(), Some(dist.version()))
{
metadata.clone()
} else {
wheel.metadata()?
};
let hashes = wheel.hashes;
return Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata),
hashes,
});
}
// If the metadata was provided by the user directly, prefer it.
if let Some(metadata) = self
.build_context
.dependency_metadata()
.get(dist.name(), Some(dist.version()))
{
return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
}
let result = self
.client
.managed(|client| {
client
.wheel_metadata(dist, self.build_context.capabilities())
.boxed_local()
})
.await;
match result {
Ok(metadata) => {
// Validate that the metadata is consistent with the distribution.
Ok(ArchiveMetadata::from_metadata23(metadata))
}
Err(err) if err.is_http_streaming_unsupported() => {
warn!(
"Streaming unsupported when fetching metadata for {dist}; downloading wheel directly ({err})"
);
// If the request failed due to an error that could be resolved by
// downloading the wheel directly, try that.
let wheel = self.get_wheel(dist, hashes).await?;
let metadata = wheel.metadata()?;
let hashes = wheel.hashes;
Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata),
hashes,
})
}
Err(err) => Err(err.into()),
}
}
/// Build the wheel metadata for a source distribution, or fetch it from the cache if possible.
///
/// The returned metadata is guaranteed to come from a distribution with a matching hash, and
/// no build processes will be executed for distributions with mismatched hashes.
pub async fn build_wheel_metadata(
&self,
source: &BuildableSource<'_>,
hashes: HashPolicy<'_>,
) -> Result<ArchiveMetadata, Error> {
// If the metadata was provided by the user directly, prefer it.
if let Some(dist) = source.as_dist() {
if let Some(metadata) = self
.build_context
.dependency_metadata()
.get(dist.name(), dist.version())
{
// If we skipped the build, we should still resolve any Git dependencies to precise
// commits.
self.builder.resolve_revision(source, &self.client).await?;
return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
}
}
let metadata = self
.builder
.download_and_build_metadata(source, hashes, &self.client)
.boxed_local()
.await?;
Ok(metadata)
}
/// Return the [`RequiresDist`] from a `pyproject.toml`, if it can be statically extracted.
pub async fn requires_dist(
&self,
path: &Path,
pyproject_toml: &PyProjectToml,
) -> Result<Option<RequiresDist>, Error> {
self.builder
.source_tree_requires_dist(
path,
pyproject_toml,
self.client.unmanaged.credentials_cache(),
)
.await
}
/// Stream a wheel from a URL, unzipping it into the cache as it's downloaded.
async fn stream_wheel(
&self,
url: DisplaySafeUrl,
index: Option<&IndexUrl>,
filename: &WheelFilename,
extension: WheelExtension,
size: Option<u64>,
wheel_entry: &CacheEntry,
dist: &BuiltDist,
hashes: HashPolicy<'_>,
) -> Result<Archive, Error> {
// Acquire an advisory lock, to guard against concurrent writes.
#[cfg(windows)]
let _lock = {
let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
lock_entry.lock().await.map_err(Error::CacheLock)?
};
// Create an entry for the HTTP cache.
let http_entry = wheel_entry.with_file(format!("{}.http", filename.cache_key()));
let download = |response: reqwest::Response| {
async {
let size = size.or_else(|| content_length(&response));
let progress = self
.reporter
.as_ref()
.map(|reporter| (reporter, reporter.on_download_start(dist.name(), size)));
let reader = response
.bytes_stream()
.map_err(|err| self.handle_response_errors(err))
.into_async_read();
// Create a hasher for each hash algorithm.
let algorithms = hashes.algorithms();
let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
let mut hasher = uv_extract::hash::HashReader::new(reader.compat(), &mut hashers);
// Download and unzip the wheel to a temporary directory.
let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
.map_err(Error::CacheWrite)?;
match progress {
Some((reporter, progress)) => {
let mut reader = ProgressReader::new(&mut hasher, progress, &**reporter);
match extension {
WheelExtension::Whl => {
uv_extract::stream::unzip(&mut reader, temp_dir.path())
.await
.map_err(|err| Error::Extract(filename.to_string(), err))?;
}
WheelExtension::WhlZst => {
uv_extract::stream::untar_zst(&mut reader, temp_dir.path())
.await
.map_err(|err| Error::Extract(filename.to_string(), err))?;
}
}
}
None => match extension {
WheelExtension::Whl => {
uv_extract::stream::unzip(&mut hasher, temp_dir.path())
.await
.map_err(|err| Error::Extract(filename.to_string(), err))?;
}
WheelExtension::WhlZst => {
uv_extract::stream::untar_zst(&mut hasher, temp_dir.path())
.await
.map_err(|err| Error::Extract(filename.to_string(), err))?;
}
},
}
// If necessary, exhaust the reader to compute the hash.
if !hashes.is_none() {
hasher.finish().await.map_err(Error::HashExhaustion)?;
}
// Persist the temporary directory to the directory store.
let id = self
.build_context
.cache()
.persist(temp_dir.keep(), wheel_entry.path())
.await
.map_err(Error::CacheRead)?;
if let Some((reporter, progress)) = progress {
reporter.on_download_complete(dist.name(), progress);
}
Ok(Archive::new(
id,
hashers.into_iter().map(HashDigest::from).collect(),
filename.clone(),
))
}
.instrument(info_span!("wheel", wheel = %dist))
};
// Fetch the archive from the cache, or download it if necessary.
let req = self.request(url.clone())?;
// Determine the cache control policy for the URL.
let cache_control = match self.client.unmanaged.connectivity() {
Connectivity::Online => {
if let Some(header) = index.and_then(|index| {
self.build_context
.locations()
.artifact_cache_control_for(index)
}) {
CacheControl::Override(header)
} else {
CacheControl::from(
self.build_context
.cache()
.freshness(&http_entry, Some(&filename.name), None)
.map_err(Error::CacheRead)?,
)
}
}
Connectivity::Offline => CacheControl::AllowStale,
};
let archive = self
.client
.managed(|client| {
client.cached_client().get_serde_with_retry(
req,
&http_entry,
cache_control,
download,
)
})
.await
.map_err(|err| match err {
CachedClientError::Callback { err, .. } => err,
CachedClientError::Client(err) => Error::Client(err),
})?;
// If the archive is missing the required hashes, or has since been removed, force a refresh.
let archive = Some(archive)
.filter(|archive| archive.has_digests(hashes))
.filter(|archive| archive.exists(self.build_context.cache()));
let archive = if let Some(archive) = archive {
archive
} else {
self.client
.managed(async |client| {
client
.cached_client()
.skip_cache_with_retry(
self.request(url)?,
&http_entry,
cache_control,
download,
)
.await
.map_err(|err| match err {
CachedClientError::Callback { err, .. } => err,
CachedClientError::Client(err) => Error::Client(err),
})
})
.await?
};
Ok(archive)
}
/// Download a wheel from a URL, then unzip it into the cache.
async fn download_wheel(
&self,
url: DisplaySafeUrl,
index: Option<&IndexUrl>,
filename: &WheelFilename,
extension: WheelExtension,
size: Option<u64>,
wheel_entry: &CacheEntry,
dist: &BuiltDist,
hashes: HashPolicy<'_>,
) -> Result<Archive, Error> {
// Acquire an advisory lock, to guard against concurrent writes.
#[cfg(windows)]
let _lock = {
let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
lock_entry.lock().await.map_err(Error::CacheLock)?
};
// Create an entry for the HTTP cache.
let http_entry = wheel_entry.with_file(format!("{}.http", filename.cache_key()));
let download = |response: reqwest::Response| {
async {
let size = size.or_else(|| content_length(&response));
let progress = self
.reporter
.as_ref()
.map(|reporter| (reporter, reporter.on_download_start(dist.name(), size)));
let reader = response
.bytes_stream()
.map_err(|err| self.handle_response_errors(err))
.into_async_read();
// Download the wheel to a temporary file.
let temp_file = tempfile::tempfile_in(self.build_context.cache().root())
.map_err(Error::CacheWrite)?;
let mut writer = tokio::io::BufWriter::new(fs_err::tokio::File::from_std(
// It's an unnamed file on Linux so that's the best approximation.
fs_err::File::from_parts(temp_file, self.build_context.cache().root()),
));
match progress {
Some((reporter, progress)) => {
// Wrap the reader in a progress reporter. This will report 100% progress
// after the download is complete, even if we still have to unzip and hash
// part of the file.
let mut reader =
ProgressReader::new(reader.compat(), progress, &**reporter);
tokio::io::copy(&mut reader, &mut writer)
.await
.map_err(Error::CacheWrite)?;
}
None => {
tokio::io::copy(&mut reader.compat(), &mut writer)
.await
.map_err(Error::CacheWrite)?;
}
}
| 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/src/index/built_wheel_index.rs | crates/uv-distribution/src/index/built_wheel_index.rs | use std::borrow::Cow;
use uv_cache::{Cache, CacheBucket, CacheShard, WheelCache};
use uv_cache_info::CacheInfo;
use uv_distribution_types::{
BuildInfo, BuildVariables, ConfigSettings, DirectUrlSourceDist, DirectorySourceDist,
ExtraBuildRequirement, ExtraBuildRequires, ExtraBuildVariables, GitSourceDist, Hashed,
PackageConfigSettings, PathSourceDist,
};
use uv_normalize::PackageName;
use uv_platform_tags::Tags;
use uv_pypi_types::HashDigests;
use uv_types::HashStrategy;
use crate::Error;
use crate::index::cached_wheel::{CachedWheel, ResolvedWheel};
use crate::source::{HTTP_REVISION, HttpRevisionPointer, LOCAL_REVISION, LocalRevisionPointer};
/// A local index of built distributions for a specific source distribution.
#[derive(Debug)]
pub struct BuiltWheelIndex<'a> {
cache: &'a Cache,
tags: &'a Tags,
hasher: &'a HashStrategy,
config_settings: &'a ConfigSettings,
config_settings_package: &'a PackageConfigSettings,
extra_build_requires: &'a ExtraBuildRequires,
extra_build_variables: &'a ExtraBuildVariables,
}
impl<'a> BuiltWheelIndex<'a> {
/// Initialize an index of built distributions.
pub fn new(
cache: &'a Cache,
tags: &'a Tags,
hasher: &'a HashStrategy,
config_settings: &'a ConfigSettings,
config_settings_package: &'a PackageConfigSettings,
extra_build_requires: &'a ExtraBuildRequires,
extra_build_variables: &'a ExtraBuildVariables,
) -> Self {
Self {
cache,
tags,
hasher,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
}
}
/// Return the most compatible [`CachedWheel`] for a given source distribution at a direct URL.
///
/// This method does not perform any freshness checks and assumes that the source distribution
/// is already up-to-date.
pub fn url(&self, source_dist: &DirectUrlSourceDist) -> Result<Option<CachedWheel>, Error> {
// For direct URLs, cache directly under the hash of the URL itself.
let cache_shard = self.cache.shard(
CacheBucket::SourceDistributions,
WheelCache::Url(source_dist.url.raw()).root(),
);
// Read the revision from the cache.
let Some(pointer) = HttpRevisionPointer::read_from(cache_shard.entry(HTTP_REVISION))?
else {
return Ok(None);
};
// Enforce hash-checking by omitting any wheels that don't satisfy the required hashes.
let revision = pointer.into_revision();
if !revision.satisfies(self.hasher.get(source_dist)) {
return Ok(None);
}
let cache_shard = cache_shard.shard(revision.id());
// If there are build settings, we need to scope to a cache shard.
let config_settings = self.config_settings_for(&source_dist.name);
let extra_build_deps = self.extra_build_requires_for(&source_dist.name);
let extra_build_vars = self.extra_build_variables_for(&source_dist.name);
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_vars);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
Ok(self.find(&cache_shard).map(|wheel| {
CachedWheel::from_entry(
wheel,
revision.into_hashes(),
CacheInfo::default(),
build_info,
)
}))
}
/// Return the most compatible [`CachedWheel`] for a given source distribution at a local path.
pub fn path(&self, source_dist: &PathSourceDist) -> Result<Option<CachedWheel>, Error> {
let cache_shard = self.cache.shard(
CacheBucket::SourceDistributions,
WheelCache::Path(&source_dist.url).root(),
);
// Read the revision from the cache.
let Some(pointer) = LocalRevisionPointer::read_from(cache_shard.entry(LOCAL_REVISION))?
else {
return Ok(None);
};
// If the distribution is stale, omit it from the index.
let cache_info =
CacheInfo::from_file(&source_dist.install_path).map_err(Error::CacheRead)?;
if cache_info != *pointer.cache_info() {
return Ok(None);
}
// Enforce hash-checking by omitting any wheels that don't satisfy the required hashes.
let revision = pointer.into_revision();
if !revision.satisfies(self.hasher.get(source_dist)) {
return Ok(None);
}
let cache_shard = cache_shard.shard(revision.id());
// If there are build settings, we need to scope to a cache shard.
let config_settings = self.config_settings_for(&source_dist.name);
let extra_build_deps = self.extra_build_requires_for(&source_dist.name);
let extra_build_vars = self.extra_build_variables_for(&source_dist.name);
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_vars);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
Ok(self.find(&cache_shard).map(|wheel| {
CachedWheel::from_entry(wheel, revision.into_hashes(), cache_info, build_info)
}))
}
/// Return the most compatible [`CachedWheel`] for a given source distribution built from a
/// local directory (source tree).
pub fn directory(
&self,
source_dist: &DirectorySourceDist,
) -> Result<Option<CachedWheel>, Error> {
let cache_shard = self.cache.shard(
CacheBucket::SourceDistributions,
if source_dist.editable.unwrap_or(false) {
WheelCache::Editable(&source_dist.url).root()
} else {
WheelCache::Path(&source_dist.url).root()
},
);
// Read the revision from the cache.
let Some(pointer) = LocalRevisionPointer::read_from(cache_shard.entry(LOCAL_REVISION))?
else {
return Ok(None);
};
// If the distribution is stale, omit it from the index.
let cache_info = CacheInfo::from_directory(&source_dist.install_path)?;
if cache_info != *pointer.cache_info() {
return Ok(None);
}
// Enforce hash-checking by omitting any wheels that don't satisfy the required hashes.
let revision = pointer.into_revision();
if !revision.satisfies(self.hasher.get(source_dist)) {
return Ok(None);
}
let cache_shard = cache_shard.shard(revision.id());
// If there are build settings, we need to scope to a cache shard.
let config_settings = self.config_settings_for(&source_dist.name);
let extra_build_deps = self.extra_build_requires_for(&source_dist.name);
let extra_build_vars = self.extra_build_variables_for(&source_dist.name);
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_vars);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
Ok(self.find(&cache_shard).map(|wheel| {
CachedWheel::from_entry(wheel, revision.into_hashes(), cache_info, build_info)
}))
}
/// Return the most compatible [`CachedWheel`] for a given source distribution at a git URL.
pub fn git(&self, source_dist: &GitSourceDist) -> Option<CachedWheel> {
// Enforce hash-checking, which isn't supported for Git distributions.
if self.hasher.get(source_dist).is_validate() {
return None;
}
let git_sha = source_dist.git.precise()?;
let cache_shard = self.cache.shard(
CacheBucket::SourceDistributions,
WheelCache::Git(&source_dist.url, git_sha.as_short_str()).root(),
);
// If there are build settings, we need to scope to a cache shard.
let config_settings = self.config_settings_for(&source_dist.name);
let extra_build_deps = self.extra_build_requires_for(&source_dist.name);
let extra_build_vars = self.extra_build_variables_for(&source_dist.name);
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_vars);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
self.find(&cache_shard).map(|wheel| {
CachedWheel::from_entry(
wheel,
HashDigests::empty(),
CacheInfo::default(),
build_info,
)
})
}
/// Find the "best" distribution in the index for a given source distribution.
///
/// This lookup prefers newer versions over older versions, and aims to maximize compatibility
/// with the target platform.
///
/// The `shard` should point to a directory containing the built distributions for a specific
/// source distribution. For example, given the built wheel cache structure:
/// ```text
/// built-wheels-v0/
/// └── pypi
/// └── django-allauth-0.51.0.tar.gz
/// ├── django_allauth-0.51.0-py3-none-any.whl
/// └── metadata.json
/// ```
///
/// The `shard` should be `built-wheels-v0/pypi/django-allauth-0.51.0.tar.gz`.
fn find(&self, shard: &CacheShard) -> Option<ResolvedWheel> {
let mut candidate: Option<ResolvedWheel> = None;
// Unzipped wheels are stored as symlinks into the archive directory.
for wheel_dir in uv_fs::entries(shard).ok().into_iter().flatten() {
// Ignore any `.lock` files.
if wheel_dir
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("lock"))
{
continue;
}
match ResolvedWheel::from_built_source(&wheel_dir, self.cache) {
None => {}
Some(dist_info) => {
// Pick the wheel with the highest priority
let compatibility = dist_info.filename.compatibility(self.tags);
// Only consider wheels that are compatible with our tags.
if !compatibility.is_compatible() {
continue;
}
if let Some(existing) = candidate.as_ref() {
// Override if the wheel is newer, or "more" compatible.
if dist_info.filename.version > existing.filename.version
|| compatibility > existing.filename.compatibility(self.tags)
{
candidate = Some(dist_info);
}
} else {
candidate = Some(dist_info);
}
}
}
}
candidate
}
/// Determine the [`ConfigSettings`] for the given package name.
fn config_settings_for(&self, name: &PackageName) -> Cow<'_, ConfigSettings> {
if let Some(package_settings) = self.config_settings_package.get(name) {
Cow::Owned(package_settings.clone().merge(self.config_settings.clone()))
} else {
Cow::Borrowed(self.config_settings)
}
}
/// Determine the extra build requirements for the given package name.
fn extra_build_requires_for(&self, name: &PackageName) -> &[ExtraBuildRequirement] {
self.extra_build_requires
.get(name)
.map(Vec::as_slice)
.unwrap_or(&[])
}
/// Determine the extra build variables for the given package name.
fn extra_build_variables_for(&self, name: &PackageName) -> Option<&BuildVariables> {
self.extra_build_variables.get(name)
}
}
| 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/src/index/registry_wheel_index.rs | crates/uv-distribution/src/index/registry_wheel_index.rs | use std::borrow::Cow;
use std::collections::hash_map::Entry;
use rustc_hash::{FxHashMap, FxHashSet};
use uv_cache::{Cache, CacheBucket, WheelCache};
use uv_cache_info::CacheInfo;
use uv_distribution_types::{
BuildInfo, BuildVariables, CachedRegistryDist, ConfigSettings, ExtraBuildRequirement,
ExtraBuildRequires, ExtraBuildVariables, Hashed, Index, IndexLocations, IndexUrl,
PackageConfigSettings,
};
use uv_fs::{directories, files};
use uv_normalize::PackageName;
use uv_platform_tags::Tags;
use uv_types::HashStrategy;
use crate::index::cached_wheel::{CachedWheel, ResolvedWheel};
use crate::source::{HTTP_REVISION, HttpRevisionPointer, LOCAL_REVISION, LocalRevisionPointer};
/// An entry in the [`RegistryWheelIndex`].
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct IndexEntry<'index> {
/// The cached distribution.
pub dist: CachedRegistryDist,
/// Whether the wheel was built from source (true), or downloaded from the registry directly (false).
pub built: bool,
/// The index from which the wheel was downloaded.
pub index: &'index Index,
}
/// A local index of distributions that originate from a registry, like `PyPI`.
#[derive(Debug)]
pub struct RegistryWheelIndex<'a> {
cache: &'a Cache,
tags: &'a Tags,
index_locations: &'a IndexLocations,
hasher: &'a HashStrategy,
index: FxHashMap<&'a PackageName, Vec<IndexEntry<'a>>>,
config_settings: &'a ConfigSettings,
config_settings_package: &'a PackageConfigSettings,
extra_build_requires: &'a ExtraBuildRequires,
extra_build_variables: &'a ExtraBuildVariables,
}
impl<'a> RegistryWheelIndex<'a> {
/// Initialize an index of registry distributions.
pub fn new(
cache: &'a Cache,
tags: &'a Tags,
index_locations: &'a IndexLocations,
hasher: &'a HashStrategy,
config_settings: &'a ConfigSettings,
config_settings_package: &'a PackageConfigSettings,
extra_build_requires: &'a ExtraBuildRequires,
extra_build_variables: &'a ExtraBuildVariables,
) -> Self {
Self {
cache,
tags,
index_locations,
hasher,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
index: FxHashMap::default(),
}
}
/// Return an iterator over available wheels for a given package.
///
/// If the package is not yet indexed, this will index the package by reading from the cache.
pub fn get(&mut self, name: &'a PackageName) -> impl Iterator<Item = &IndexEntry<'_>> {
self.get_impl(name).iter().rev()
}
/// Get an entry in the index.
fn get_impl(&mut self, name: &'a PackageName) -> &[IndexEntry<'_>] {
(match self.index.entry(name) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(Self::index(
name,
self.cache,
self.tags,
self.index_locations,
self.hasher,
self.config_settings,
self.config_settings_package,
self.extra_build_requires,
self.extra_build_variables,
)),
}) as _
}
/// Add a package to the index by reading from the cache.
fn index<'index>(
package: &PackageName,
cache: &Cache,
tags: &Tags,
index_locations: &'index IndexLocations,
hasher: &HashStrategy,
config_settings: &ConfigSettings,
config_settings_package: &PackageConfigSettings,
extra_build_requires: &ExtraBuildRequires,
extra_build_variables: &ExtraBuildVariables,
) -> Vec<IndexEntry<'index>> {
let mut entries = vec![];
let mut seen = FxHashSet::default();
for index in index_locations.allowed_indexes() {
if !seen.insert(index.url()) {
continue;
}
// Index all the wheels that were downloaded directly from the registry.
let wheel_dir = cache.shard(
CacheBucket::Wheels,
WheelCache::Index(index.url()).wheel_dir(package.as_ref()),
);
// For registry wheels, the cache structure is: `<index>/<package-name>/<wheel>.http`
// or `<index>/<package-name>/<version>/<wheel>.rev`.
for file in files(&wheel_dir).ok().into_iter().flatten() {
match index.url() {
// Add files from remote registries.
IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
if file
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("http"))
{
if let Some(wheel) =
CachedWheel::from_http_pointer(wheel_dir.join(file), cache)
{
if wheel.filename.compatibility(tags).is_compatible() {
// Enforce hash-checking based on the built distribution.
if wheel.satisfies(
hasher.get_package(
&wheel.filename.name,
&wheel.filename.version,
),
) {
entries.push(IndexEntry {
dist: wheel.into_registry_dist(),
index,
built: false,
});
}
}
}
}
}
// Add files from local registries (e.g., `--find-links`).
IndexUrl::Path(_) => {
if file
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("rev"))
{
if let Some(wheel) =
CachedWheel::from_local_pointer(wheel_dir.join(file), cache)
{
if wheel.filename.compatibility(tags).is_compatible() {
// Enforce hash-checking based on the built distribution.
if wheel.satisfies(
hasher.get_package(
&wheel.filename.name,
&wheel.filename.version,
),
) {
entries.push(IndexEntry {
dist: wheel.into_registry_dist(),
index,
built: false,
});
}
}
}
}
}
}
}
// Index all the built wheels, created by downloading and building source distributions
// from the registry.
let cache_shard = cache.shard(
CacheBucket::SourceDistributions,
WheelCache::Index(index.url()).wheel_dir(package.as_ref()),
);
// For registry source distributions, the cache structure is: `<index>/<package-name>/<version>/`.
for shard in directories(&cache_shard).ok().into_iter().flatten() {
let cache_shard = cache_shard.shard(shard);
// Read the revision from the cache.
let revision = match index.url() {
// Add files from remote registries.
IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
let revision_entry = cache_shard.entry(HTTP_REVISION);
if let Ok(Some(pointer)) = HttpRevisionPointer::read_from(revision_entry) {
Some(pointer.into_revision())
} else {
None
}
}
// Add files from local registries (e.g., `--find-links`).
IndexUrl::Path(_) => {
let revision_entry = cache_shard.entry(LOCAL_REVISION);
if let Ok(Some(pointer)) = LocalRevisionPointer::read_from(revision_entry) {
Some(pointer.into_revision())
} else {
None
}
}
};
if let Some(revision) = revision {
let cache_shard = cache_shard.shard(revision.id());
// If there are build settings, we need to scope to a cache shard.
let extra_build_deps =
Self::extra_build_requires_for(package, extra_build_requires);
let extra_build_vars =
Self::extra_build_variables_for(package, extra_build_variables);
let config_settings = Self::config_settings_for(
package,
config_settings,
config_settings_package,
);
let build_info = BuildInfo::from_settings(
&config_settings,
extra_build_deps,
extra_build_vars,
);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
for wheel_dir in uv_fs::entries(cache_shard).ok().into_iter().flatten() {
// Ignore any `.lock` files.
if wheel_dir
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("lock"))
{
continue;
}
if let Some(wheel) = ResolvedWheel::from_built_source(wheel_dir, cache) {
if wheel.filename.compatibility(tags).is_compatible() {
// Enforce hash-checking based on the source distribution.
if revision.satisfies(
hasher
.get_package(&wheel.filename.name, &wheel.filename.version),
) {
let wheel = CachedWheel::from_entry(
wheel,
revision.hashes().into(),
CacheInfo::default(),
build_info.clone(),
);
entries.push(IndexEntry {
dist: wheel.into_registry_dist(),
index,
built: true,
});
}
}
}
}
}
}
}
// Sort the cached distributions by (1) version, (2) compatibility, and (3) build status.
// We want the highest versions, with the greatest compatibility, that were built from source.
// at the end of the list.
entries.sort_unstable_by(|a, b| {
a.dist
.filename
.version
.cmp(&b.dist.filename.version)
.then_with(|| {
a.dist
.filename
.compatibility(tags)
.cmp(&b.dist.filename.compatibility(tags))
.then_with(|| a.built.cmp(&b.built))
})
});
entries
}
/// Determine the [`ConfigSettings`] for the given package name.
fn config_settings_for<'settings>(
name: &PackageName,
config_settings: &'settings ConfigSettings,
config_settings_package: &PackageConfigSettings,
) -> Cow<'settings, ConfigSettings> {
if let Some(package_settings) = config_settings_package.get(name) {
Cow::Owned(package_settings.clone().merge(config_settings.clone()))
} else {
Cow::Borrowed(config_settings)
}
}
/// Determine the extra build requirements for the given package name.
fn extra_build_requires_for<'settings>(
name: &PackageName,
extra_build_requires: &'settings ExtraBuildRequires,
) -> &'settings [ExtraBuildRequirement] {
extra_build_requires
.get(name)
.map(Vec::as_slice)
.unwrap_or(&[])
}
/// Determine the extra build variables for the given package name.
fn extra_build_variables_for<'settings>(
name: &PackageName,
extra_build_variables: &'settings ExtraBuildVariables,
) -> Option<&'settings BuildVariables> {
extra_build_variables.get(name)
}
}
| 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/src/index/mod.rs | crates/uv-distribution/src/index/mod.rs | pub use built_wheel_index::BuiltWheelIndex;
pub use registry_wheel_index::RegistryWheelIndex;
mod built_wheel_index;
mod cached_wheel;
mod registry_wheel_index;
| 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/src/index/cached_wheel.rs | crates/uv-distribution/src/index/cached_wheel.rs | use std::path::Path;
use uv_cache::{Cache, CacheBucket, CacheEntry};
use uv_cache_info::CacheInfo;
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{
BuildInfo, CachedDirectUrlDist, CachedRegistryDist, DirectUrlSourceDist, DirectorySourceDist,
GitSourceDist, Hashed, PathSourceDist,
};
use uv_pypi_types::{HashDigest, HashDigests, VerbatimParsedUrl};
use crate::archive::Archive;
use crate::{HttpArchivePointer, LocalArchivePointer};
#[derive(Debug, Clone)]
pub struct ResolvedWheel {
/// The filename of the wheel.
pub filename: WheelFilename,
/// The [`CacheEntry`] for the wheel.
pub entry: CacheEntry,
}
impl ResolvedWheel {
/// Try to parse a distribution from a cached directory name (like `typing-extensions-4.8.0-py3-none-any`).
pub fn from_built_source(path: impl AsRef<Path>, cache: &Cache) -> Option<Self> {
let path = path.as_ref();
// Determine the wheel filename.
let filename = path.file_name()?.to_str()?;
let filename = WheelFilename::from_stem(filename).ok()?;
// Convert to a cached wheel.
let archive = cache.resolve_link(path).ok()?;
let entry = CacheEntry::from_path(archive);
Some(Self { filename, entry })
}
}
#[derive(Debug, Clone)]
pub struct CachedWheel {
/// The filename of the wheel.
pub filename: WheelFilename,
/// The [`CacheEntry`] for the wheel.
pub entry: CacheEntry,
/// The [`HashDigest`]s for the wheel.
pub hashes: HashDigests,
/// The [`CacheInfo`] for the wheel.
pub cache_info: CacheInfo,
/// The [`BuildInfo`] for the wheel, if it was built.
pub build_info: Option<BuildInfo>,
}
impl CachedWheel {
/// Create a [`CachedWheel`] from a [`ResolvedWheel`].
pub fn from_entry(
wheel: ResolvedWheel,
hashes: HashDigests,
cache_info: CacheInfo,
build_info: BuildInfo,
) -> Self {
Self {
filename: wheel.filename,
entry: wheel.entry,
hashes,
cache_info,
build_info: Some(build_info),
}
}
/// Read a cached wheel from a `.http` pointer
pub fn from_http_pointer(path: impl AsRef<Path>, cache: &Cache) -> Option<Self> {
let path = path.as_ref();
// Read the pointer.
let pointer = HttpArchivePointer::read_from(path).ok()??;
let cache_info = pointer.to_cache_info();
let build_info = pointer.to_build_info();
let archive = pointer.into_archive();
// Ignore stale pointers.
if !archive.exists(cache) {
return None;
}
let Archive { id, hashes, .. } = archive;
let entry = cache.entry(CacheBucket::Archive, "", id);
// Convert to a cached wheel.
Some(Self {
filename: archive.filename,
entry,
hashes,
cache_info,
build_info,
})
}
/// Read a cached wheel from a `.rev` pointer
pub fn from_local_pointer(path: impl AsRef<Path>, cache: &Cache) -> Option<Self> {
let path = path.as_ref();
// Read the pointer.
let pointer = LocalArchivePointer::read_from(path).ok()??;
let cache_info = pointer.to_cache_info();
let build_info = pointer.to_build_info();
let archive = pointer.into_archive();
// Ignore stale pointers.
if !archive.exists(cache) {
return None;
}
let Archive { id, hashes, .. } = archive;
let entry = cache.entry(CacheBucket::Archive, "", id);
// Convert to a cached wheel.
Some(Self {
filename: archive.filename,
entry,
hashes,
cache_info,
build_info,
})
}
/// Convert a [`CachedWheel`] into a [`CachedRegistryDist`].
pub fn into_registry_dist(self) -> CachedRegistryDist {
CachedRegistryDist {
filename: self.filename,
path: self.entry.into_path_buf().into_boxed_path(),
hashes: self.hashes,
cache_info: self.cache_info,
build_info: self.build_info,
}
}
/// Convert a [`CachedWheel`] into a [`CachedDirectUrlDist`] by merging in the given
/// [`DirectUrlSourceDist`].
pub fn into_url_dist(self, dist: &DirectUrlSourceDist) -> CachedDirectUrlDist {
CachedDirectUrlDist {
filename: self.filename,
url: VerbatimParsedUrl {
parsed_url: dist.parsed_url(),
verbatim: dist.url.clone(),
},
path: self.entry.into_path_buf().into_boxed_path(),
hashes: self.hashes,
cache_info: self.cache_info,
build_info: self.build_info,
}
}
/// Convert a [`CachedWheel`] into a [`CachedDirectUrlDist`] by merging in the given
/// [`PathSourceDist`].
pub fn into_path_dist(self, dist: &PathSourceDist) -> CachedDirectUrlDist {
CachedDirectUrlDist {
filename: self.filename,
url: VerbatimParsedUrl {
parsed_url: dist.parsed_url(),
verbatim: dist.url.clone(),
},
path: self.entry.into_path_buf().into_boxed_path(),
hashes: self.hashes,
cache_info: self.cache_info,
build_info: self.build_info,
}
}
/// Convert a [`CachedWheel`] into a [`CachedDirectUrlDist`] by merging in the given
/// [`DirectorySourceDist`].
pub fn into_directory_dist(self, dist: &DirectorySourceDist) -> CachedDirectUrlDist {
CachedDirectUrlDist {
filename: self.filename,
url: VerbatimParsedUrl {
parsed_url: dist.parsed_url(),
verbatim: dist.url.clone(),
},
path: self.entry.into_path_buf().into_boxed_path(),
hashes: self.hashes,
cache_info: self.cache_info,
build_info: self.build_info,
}
}
/// Convert a [`CachedWheel`] into a [`CachedDirectUrlDist`] by merging in the given
/// [`GitSourceDist`].
pub fn into_git_dist(self, dist: &GitSourceDist) -> CachedDirectUrlDist {
CachedDirectUrlDist {
filename: self.filename,
url: VerbatimParsedUrl {
parsed_url: dist.parsed_url(),
verbatim: dist.url.clone(),
},
path: self.entry.into_path_buf().into_boxed_path(),
hashes: self.hashes,
cache_info: self.cache_info,
build_info: self.build_info,
}
}
}
impl Hashed for CachedWheel {
fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
}
| 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/src/metadata/build_requires.rs | crates/uv-distribution/src/metadata/build_requires.rs | use std::collections::BTreeMap;
use std::path::Path;
use uv_auth::CredentialsCache;
use uv_configuration::SourceStrategy;
use uv_distribution_types::{
ExtraBuildRequirement, ExtraBuildRequires, IndexLocations, Requirement,
};
use uv_normalize::PackageName;
use uv_workspace::pyproject::{ExtraBuildDependencies, ExtraBuildDependency, ToolUvSources};
use uv_workspace::{
DiscoveryOptions, MemberDiscovery, ProjectWorkspace, Workspace, WorkspaceCache,
};
use crate::metadata::{LoweredRequirement, MetadataError};
/// Lowered requirements from a `[build-system.requires]` field in a `pyproject.toml` file.
#[derive(Debug, Clone)]
pub struct BuildRequires {
pub name: Option<PackageName>,
pub requires_dist: Vec<Requirement>,
}
impl BuildRequires {
/// Lower without considering `tool.uv` in `pyproject.toml`, used for index and other archive
/// dependencies.
pub fn from_metadata23(metadata: uv_pypi_types::BuildRequires) -> Self {
Self {
name: metadata.name,
requires_dist: metadata
.requires_dist
.into_iter()
.map(Requirement::from)
.collect(),
}
}
/// Lower by considering `tool.uv` in `pyproject.toml` if present, used for Git and directory
/// dependencies.
pub async fn from_project_maybe_workspace(
metadata: uv_pypi_types::BuildRequires,
install_path: &Path,
locations: &IndexLocations,
sources: SourceStrategy,
cache: &WorkspaceCache,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
let discovery = match sources {
SourceStrategy::Enabled => DiscoveryOptions::default(),
SourceStrategy::Disabled => DiscoveryOptions {
members: MemberDiscovery::None,
..Default::default()
},
};
let Some(project_workspace) =
ProjectWorkspace::from_maybe_project_root(install_path, &discovery, cache).await?
else {
return Ok(Self::from_metadata23(metadata));
};
Self::from_project_workspace(
metadata,
&project_workspace,
locations,
sources,
credentials_cache,
)
}
/// Lower the `build-system.requires` field from a `pyproject.toml` file.
pub fn from_project_workspace(
metadata: uv_pypi_types::BuildRequires,
project_workspace: &ProjectWorkspace,
locations: &IndexLocations,
source_strategy: SourceStrategy,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
// Collect any `tool.uv.index` entries.
let empty = vec![];
let project_indexes = match source_strategy {
SourceStrategy::Enabled => project_workspace
.current_project()
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.index.as_deref())
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
// Collect any `tool.uv.sources` and `tool.uv.dev_dependencies` from `pyproject.toml`.
let empty = BTreeMap::default();
let project_sources = match source_strategy {
SourceStrategy::Enabled => project_workspace
.current_project()
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
// Lower the requirements.
let requires_dist = metadata.requires_dist.into_iter();
let requires_dist = match source_strategy {
SourceStrategy::Enabled => requires_dist
.flat_map(|requirement| {
let requirement_name = requirement.name.clone();
let extra = requirement.marker.top_level_extra_name();
let group = None;
LoweredRequirement::from_requirement(
requirement,
metadata.name.as_ref(),
project_workspace.project_root(),
project_sources,
project_indexes,
extra.as_deref(),
group,
locations,
project_workspace.workspace(),
None,
credentials_cache,
)
.map(move |requirement| match requirement {
Ok(requirement) => Ok(requirement.into_inner()),
Err(err) => Err(MetadataError::LoweringError(
requirement_name.clone(),
Box::new(err),
)),
})
})
.collect::<Result<Vec<_>, _>>()?,
SourceStrategy::Disabled => requires_dist.into_iter().map(Requirement::from).collect(),
};
Ok(Self {
name: metadata.name,
requires_dist,
})
}
/// Lower the `build-system.requires` field from a `pyproject.toml` file.
pub fn from_workspace(
metadata: uv_pypi_types::BuildRequires,
workspace: &Workspace,
locations: &IndexLocations,
source_strategy: SourceStrategy,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
// Collect any `tool.uv.index` entries.
let empty = vec![];
let project_indexes = match source_strategy {
SourceStrategy::Enabled => workspace
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.index.as_deref())
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
// Collect any `tool.uv.sources` and `tool.uv.dev_dependencies` from `pyproject.toml`.
let empty = BTreeMap::default();
let project_sources = match source_strategy {
SourceStrategy::Enabled => workspace
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
// Lower the requirements.
let requires_dist = metadata.requires_dist.into_iter();
let requires_dist = match source_strategy {
SourceStrategy::Enabled => requires_dist
.flat_map(|requirement| {
let requirement_name = requirement.name.clone();
let extra = requirement.marker.top_level_extra_name();
let group = None;
LoweredRequirement::from_requirement(
requirement,
None,
workspace.install_path(),
project_sources,
project_indexes,
extra.as_deref(),
group,
locations,
workspace,
None,
credentials_cache,
)
.map(move |requirement| match requirement {
Ok(requirement) => Ok(requirement.into_inner()),
Err(err) => Err(MetadataError::LoweringError(
requirement_name.clone(),
Box::new(err),
)),
})
})
.collect::<Result<Vec<_>, _>>()?,
SourceStrategy::Disabled => requires_dist.into_iter().map(Requirement::from).collect(),
};
Ok(Self {
name: metadata.name,
requires_dist,
})
}
}
/// Lowered extra build dependencies.
///
/// This is a wrapper around [`ExtraBuildRequires`] that provides methods to lower
/// [`ExtraBuildDependencies`] from a workspace context or from already lowered dependencies.
#[derive(Debug, Clone, Default)]
pub struct LoweredExtraBuildDependencies(ExtraBuildRequires);
impl LoweredExtraBuildDependencies {
/// Return the [`ExtraBuildRequires`] that this was lowered into.
pub fn into_inner(self) -> ExtraBuildRequires {
self.0
}
/// Create from a workspace, lowering the extra build dependencies.
pub fn from_workspace(
extra_build_dependencies: ExtraBuildDependencies,
workspace: &Workspace,
index_locations: &IndexLocations,
source_strategy: SourceStrategy,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
match source_strategy {
SourceStrategy::Enabled => {
// Collect project sources and indexes
let project_indexes = workspace
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.index.as_deref())
.unwrap_or(&[]);
let empty_sources = BTreeMap::default();
let project_sources = workspace
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.unwrap_or(&empty_sources);
// Lower each package's extra build dependencies
let mut build_requires = ExtraBuildRequires::default();
for (package_name, requirements) in extra_build_dependencies {
let lowered: Vec<ExtraBuildRequirement> = requirements
.into_iter()
.flat_map(
|ExtraBuildDependency {
requirement,
match_runtime,
}| {
let requirement_name = requirement.name.clone();
let extra = requirement.marker.top_level_extra_name();
let group = None;
LoweredRequirement::from_requirement(
requirement,
None,
workspace.install_path(),
project_sources,
project_indexes,
extra.as_deref(),
group,
index_locations,
workspace,
None,
credentials_cache,
)
.map(move |requirement| {
match requirement {
Ok(requirement) => Ok(ExtraBuildRequirement {
requirement: requirement.into_inner(),
match_runtime,
}),
Err(err) => Err(MetadataError::LoweringError(
requirement_name.clone(),
Box::new(err),
)),
}
})
},
)
.collect::<Result<Vec<_>, _>>()?;
build_requires.insert(package_name, lowered);
}
Ok(Self(build_requires))
}
SourceStrategy::Disabled => Ok(Self::from_non_lowered(extra_build_dependencies)),
}
}
/// Create from lowered dependencies (for non-workspace contexts, like scripts).
pub fn from_lowered(extra_build_dependencies: ExtraBuildRequires) -> Self {
Self(extra_build_dependencies)
}
/// Create from unlowered dependencies (e.g., for contexts in the pip CLI).
pub fn from_non_lowered(extra_build_dependencies: ExtraBuildDependencies) -> Self {
Self(
extra_build_dependencies
.into_iter()
.map(|(name, requirements)| {
(
name,
requirements
.into_iter()
.map(
|ExtraBuildDependency {
requirement,
match_runtime,
}| {
ExtraBuildRequirement {
requirement: requirement.into(),
match_runtime,
}
},
)
.collect::<Vec<_>>(),
)
})
.collect(),
)
}
}
| 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/src/metadata/mod.rs | crates/uv-distribution/src/metadata/mod.rs | use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use thiserror::Error;
use uv_auth::CredentialsCache;
use uv_configuration::SourceStrategy;
use uv_distribution_types::{GitSourceUrl, IndexLocations, Requirement};
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_pep440::{Version, VersionSpecifiers};
use uv_pypi_types::{HashDigests, ResolutionMetadata};
use uv_workspace::dependency_groups::DependencyGroupError;
use uv_workspace::{WorkspaceCache, WorkspaceError};
pub use crate::metadata::build_requires::{BuildRequires, LoweredExtraBuildDependencies};
pub use crate::metadata::dependency_groups::SourcedDependencyGroups;
pub use crate::metadata::lowering::LoweredRequirement;
pub use crate::metadata::lowering::LoweringError;
pub use crate::metadata::requires_dist::{FlatRequiresDist, RequiresDist};
mod build_requires;
mod dependency_groups;
mod lowering;
mod requires_dist;
#[derive(Debug, Error)]
pub enum MetadataError {
#[error(transparent)]
Workspace(#[from] WorkspaceError),
#[error(transparent)]
DependencyGroup(#[from] DependencyGroupError),
#[error("No pyproject.toml found at: {0}")]
MissingPyprojectToml(PathBuf),
#[error("Failed to parse entry: `{0}`")]
LoweringError(PackageName, #[source] Box<LoweringError>),
#[error("Failed to parse entry in group `{0}`: `{1}`")]
GroupLoweringError(GroupName, PackageName, #[source] Box<LoweringError>),
#[error(
"Source entry for `{0}` only applies to extra `{1}`, but the `{1}` extra does not exist. When an extra is present on a source (e.g., `extra = \"{1}\"`), the relevant package must be included in the `project.optional-dependencies` section for that extra (e.g., `project.optional-dependencies = {{ \"{1}\" = [\"{0}\"] }}`)."
)]
MissingSourceExtra(PackageName, ExtraName),
#[error(
"Source entry for `{0}` only applies to extra `{1}`, but `{0}` was not found under the `project.optional-dependencies` section for that extra. When an extra is present on a source (e.g., `extra = \"{1}\"`), the relevant package must be included in the `project.optional-dependencies` section for that extra (e.g., `project.optional-dependencies = {{ \"{1}\" = [\"{0}\"] }}`)."
)]
IncompleteSourceExtra(PackageName, ExtraName),
#[error(
"Source entry for `{0}` only applies to dependency group `{1}`, but the `{1}` group does not exist. When a group is present on a source (e.g., `group = \"{1}\"`), the relevant package must be included in the `dependency-groups` section for that extra (e.g., `dependency-groups = {{ \"{1}\" = [\"{0}\"] }}`)."
)]
MissingSourceGroup(PackageName, GroupName),
#[error(
"Source entry for `{0}` only applies to dependency group `{1}`, but `{0}` was not found under the `dependency-groups` section for that group. When a group is present on a source (e.g., `group = \"{1}\"`), the relevant package must be included in the `dependency-groups` section for that extra (e.g., `dependency-groups = {{ \"{1}\" = [\"{0}\"] }}`)."
)]
IncompleteSourceGroup(PackageName, GroupName),
}
#[derive(Debug, Clone)]
pub struct Metadata {
// Mandatory fields
pub name: PackageName,
pub version: Version,
// Optional fields
pub requires_dist: Box<[Requirement]>,
pub requires_python: Option<VersionSpecifiers>,
pub provides_extra: Box<[ExtraName]>,
pub dependency_groups: BTreeMap<GroupName, Box<[Requirement]>>,
pub dynamic: bool,
}
impl Metadata {
/// Lower without considering `tool.uv` in `pyproject.toml`, used for index and other archive
/// dependencies.
pub fn from_metadata23(metadata: ResolutionMetadata) -> Self {
Self {
name: metadata.name,
version: metadata.version,
requires_dist: Box::into_iter(metadata.requires_dist)
.map(Requirement::from)
.collect(),
requires_python: metadata.requires_python,
provides_extra: metadata.provides_extra,
dependency_groups: BTreeMap::default(),
dynamic: metadata.dynamic,
}
}
/// Lower by considering `tool.uv` in `pyproject.toml` if present, used for Git and directory
/// dependencies.
pub async fn from_workspace(
metadata: ResolutionMetadata,
install_path: &Path,
git_source: Option<&GitWorkspaceMember<'_>>,
locations: &IndexLocations,
sources: SourceStrategy,
cache: &WorkspaceCache,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
// Lower the requirements.
let requires_dist = uv_pypi_types::RequiresDist {
name: metadata.name,
requires_dist: metadata.requires_dist,
provides_extra: metadata.provides_extra,
dynamic: metadata.dynamic,
};
let RequiresDist {
name,
requires_dist,
provides_extra,
dependency_groups,
dynamic,
} = RequiresDist::from_project_maybe_workspace(
requires_dist,
install_path,
git_source,
locations,
sources,
cache,
credentials_cache,
)
.await?;
// Combine with the remaining metadata.
Ok(Self {
name,
version: metadata.version,
requires_dist,
requires_python: metadata.requires_python,
provides_extra,
dependency_groups,
dynamic,
})
}
}
/// The metadata associated with an archive.
#[derive(Debug, Clone)]
pub struct ArchiveMetadata {
/// The [`Metadata`] for the underlying distribution.
pub metadata: Metadata,
/// The hashes of the source or built archive.
pub hashes: HashDigests,
}
impl ArchiveMetadata {
/// Lower without considering `tool.uv` in `pyproject.toml`, used for index and other archive
/// dependencies.
pub fn from_metadata23(metadata: ResolutionMetadata) -> Self {
Self {
metadata: Metadata::from_metadata23(metadata),
hashes: HashDigests::empty(),
}
}
}
impl From<Metadata> for ArchiveMetadata {
fn from(metadata: Metadata) -> Self {
Self {
metadata,
hashes: HashDigests::empty(),
}
}
}
/// A workspace member from a checked-out Git repo.
#[derive(Debug, Clone)]
pub struct GitWorkspaceMember<'a> {
/// The root of the checkout, which may be the root of the workspace or may be above the
/// workspace root.
pub fetch_root: &'a Path,
pub git_source: &'a GitSourceUrl<'a>,
}
| 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/src/metadata/lowering.rs | crates/uv-distribution/src/metadata/lowering.rs | use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use either::Either;
use thiserror::Error;
use uv_auth::CredentialsCache;
use uv_distribution_filename::DistExtension;
use uv_distribution_types::{
Index, IndexLocations, IndexMetadata, IndexName, Origin, Requirement, RequirementSource,
};
use uv_git_types::{GitLfs, GitReference, GitUrl, GitUrlParseError};
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_pep440::VersionSpecifiers;
use uv_pep508::{MarkerTree, VerbatimUrl, VersionOrUrl, looks_like_git_repository};
use uv_pypi_types::{ConflictItem, ParsedGitUrl, ParsedUrlError, VerbatimParsedUrl};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
use uv_workspace::Workspace;
use uv_workspace::pyproject::{PyProjectToml, Source, Sources};
use crate::metadata::GitWorkspaceMember;
#[derive(Debug, Clone)]
pub struct LoweredRequirement(Requirement);
#[derive(Debug, Clone, Copy)]
enum RequirementOrigin {
/// The `tool.uv.sources` were read from the project.
Project,
/// The `tool.uv.sources` were read from the workspace root.
Workspace,
}
impl LoweredRequirement {
/// Combine `project.dependencies` or `project.optional-dependencies` with `tool.uv.sources`.
pub(crate) fn from_requirement<'data>(
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
project_name: Option<&'data PackageName>,
project_dir: &'data Path,
project_sources: &'data BTreeMap<PackageName, Sources>,
project_indexes: &'data [Index],
extra: Option<&ExtraName>,
group: Option<&GroupName>,
locations: &'data IndexLocations,
workspace: &'data Workspace,
git_member: Option<&'data GitWorkspaceMember<'data>>,
credentials_cache: &'data CredentialsCache,
) -> impl Iterator<Item = Result<Self, LoweringError>> + use<'data> + 'data {
// Identify the source from the `tool.uv.sources` table.
let (sources, origin) = if let Some(source) = project_sources.get(&requirement.name) {
(Some(source), RequirementOrigin::Project)
} else if let Some(source) = workspace.sources().get(&requirement.name) {
(Some(source), RequirementOrigin::Workspace)
} else {
(None, RequirementOrigin::Project)
};
// If the source only applies to a given extra or dependency group, filter it out.
let sources = sources.map(|sources| {
sources
.iter()
.filter(|source| {
if let Some(target) = source.extra() {
if extra != Some(target) {
return false;
}
}
if let Some(target) = source.group() {
if group != Some(target) {
return false;
}
}
true
})
.cloned()
.collect::<Sources>()
});
// If you use a package that's part of the workspace...
if workspace.packages().contains_key(&requirement.name) {
// And it's not a recursive self-inclusion (extras that activate other extras), e.g.
// `framework[machine_learning]` depends on `framework[cuda]`.
if project_name.is_none_or(|project_name| *project_name != requirement.name) {
// It must be declared as a workspace source.
let Some(sources) = sources.as_ref() else {
// No sources were declared for the workspace package.
return Either::Left(std::iter::once(Err(
LoweringError::MissingWorkspaceSource(requirement.name.clone()),
)));
};
for source in sources.iter() {
match source {
Source::Git { .. } => {
return Either::Left(std::iter::once(Err(
LoweringError::NonWorkspaceSource(
requirement.name.clone(),
SourceKind::Git,
),
)));
}
Source::Url { .. } => {
return Either::Left(std::iter::once(Err(
LoweringError::NonWorkspaceSource(
requirement.name.clone(),
SourceKind::Url,
),
)));
}
Source::Path { .. } => {
return Either::Left(std::iter::once(Err(
LoweringError::NonWorkspaceSource(
requirement.name.clone(),
SourceKind::Path,
),
)));
}
Source::Registry { .. } => {
return Either::Left(std::iter::once(Err(
LoweringError::NonWorkspaceSource(
requirement.name.clone(),
SourceKind::Registry,
),
)));
}
Source::Workspace { .. } => {
// OK
}
}
}
}
}
let Some(sources) = sources else {
return Either::Left(std::iter::once(Ok(Self(Requirement::from(requirement)))));
};
// Determine whether the markers cover the full space for the requirement. If not, fill the
// remaining space with the negation of the sources.
let remaining = {
// Determine the space covered by the sources.
let mut total = MarkerTree::FALSE;
for source in sources.iter() {
total.or(source.marker());
}
// Determine the space covered by the requirement.
let mut remaining = total.negate();
remaining.and(requirement.marker);
Self(Requirement {
marker: remaining,
..Requirement::from(requirement.clone())
})
};
Either::Right(
sources
.into_iter()
.map(move |source| {
let (source, mut marker) = match source {
Source::Git {
git,
subdirectory,
rev,
tag,
branch,
lfs,
marker,
..
} => {
let source = git_source(
&git,
subdirectory.map(Box::<Path>::from),
rev,
tag,
branch,
lfs,
)?;
(source, marker)
}
Source::Url {
url,
subdirectory,
marker,
..
} => {
let source =
url_source(&requirement, url, subdirectory.map(Box::<Path>::from))?;
(source, marker)
}
Source::Path {
path,
editable,
package,
marker,
..
} => {
let source = path_source(
path,
git_member,
origin,
project_dir,
workspace.install_path(),
editable,
package,
)?;
(source, marker)
}
Source::Registry {
index,
marker,
extra,
group,
} => {
// Identify the named index from either the project indexes or the workspace indexes,
// in that order.
let Some(index) = locations
.indexes()
.filter(|index| matches!(index.origin, Some(Origin::Cli)))
.chain(project_indexes.iter())
.chain(workspace.indexes().iter())
.find(|Index { name, .. }| {
name.as_ref().is_some_and(|name| *name == index)
})
else {
return Err(LoweringError::MissingIndex(
requirement.name.clone(),
index,
));
};
if let Some(credentials) = index.credentials() {
credentials_cache.store_credentials(index.raw_url(), credentials);
}
let index = IndexMetadata {
url: index.url.clone(),
format: index.format,
};
let conflict = project_name.and_then(|project_name| {
if let Some(extra) = extra {
Some(ConflictItem::from((project_name.clone(), extra)))
} else {
group.map(|group| {
ConflictItem::from((project_name.clone(), group))
})
}
});
let source = registry_source(&requirement, index, conflict);
(source, marker)
}
Source::Workspace {
workspace: is_workspace,
marker,
..
} => {
if !is_workspace {
return Err(LoweringError::WorkspaceFalse);
}
let member = workspace
.packages()
.get(&requirement.name)
.ok_or_else(|| {
LoweringError::UndeclaredWorkspacePackage(
requirement.name.clone(),
)
})?
.clone();
// Say we have:
// ```
// root
// ├── main_workspace <- We want to the path from here ...
// │ ├── pyproject.toml
// │ └── uv.lock
// └──current_workspace
// └── packages
// └── current_package <- ... to here.
// └── pyproject.toml
// ```
// The path we need in the lockfile: `../current_workspace/packages/current_project`
// member root: `/root/current_workspace/packages/current_project`
// workspace install root: `/root/current_workspace`
// relative to workspace: `packages/current_project`
// workspace lock root: `../current_workspace`
// relative to main workspace: `../current_workspace/packages/current_project`
let url = VerbatimUrl::from_absolute_path(member.root())?;
let install_path = url.to_file_path().map_err(|()| {
LoweringError::RelativeTo(io::Error::other(
"Invalid path in file URL",
))
})?;
let source = if let Some(git_member) = &git_member {
// If the workspace comes from a Git dependency, all workspace
// members need to be Git dependencies, too.
let subdirectory =
uv_fs::relative_to(member.root(), git_member.fetch_root)
.expect("Workspace member must be relative");
let subdirectory = uv_fs::normalize_path_buf(subdirectory);
RequirementSource::Git {
git: git_member.git_source.git.clone(),
subdirectory: if subdirectory == PathBuf::new() {
None
} else {
Some(subdirectory.into_boxed_path())
},
url,
}
} else {
let value = workspace.required_members().get(&requirement.name);
let is_required_member = value.is_some();
let editability = value.copied().flatten();
if member.pyproject_toml().is_package(!is_required_member) {
RequirementSource::Directory {
install_path: install_path.into_boxed_path(),
url,
editable: Some(editability.unwrap_or(true)),
r#virtual: Some(false),
}
} else {
RequirementSource::Directory {
install_path: install_path.into_boxed_path(),
url,
editable: Some(false),
r#virtual: Some(true),
}
}
};
(source, marker)
}
};
marker.and(requirement.marker);
Ok(Self(Requirement {
name: requirement.name.clone(),
extras: requirement.extras.clone(),
groups: Box::new([]),
marker,
source,
origin: requirement.origin.clone(),
}))
})
.chain(std::iter::once(Ok(remaining)))
.filter(|requirement| match requirement {
Ok(requirement) => !requirement.0.marker.is_false(),
Err(_) => true,
}),
)
}
/// Lower a [`uv_pep508::Requirement`] in a non-workspace setting (for example, in a PEP 723
/// script, which runs in an isolated context).
pub fn from_non_workspace_requirement<'data>(
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
dir: &'data Path,
sources: &'data BTreeMap<PackageName, Sources>,
indexes: &'data [Index],
locations: &'data IndexLocations,
credentials_cache: &'data CredentialsCache,
) -> impl Iterator<Item = Result<Self, LoweringError>> + 'data {
let source = sources.get(&requirement.name).cloned();
let Some(source) = source else {
return Either::Left(std::iter::once(Ok(Self(Requirement::from(requirement)))));
};
// If the source only applies to a given extra, filter it out.
let source = source
.iter()
.filter(|source| {
source.extra().is_none_or(|target| {
requirement
.marker
.top_level_extra_name()
.is_some_and(|extra| &*extra == target)
})
})
.cloned()
.collect::<Sources>();
// Determine whether the markers cover the full space for the requirement. If not, fill the
// remaining space with the negation of the sources.
let remaining = {
// Determine the space covered by the sources.
let mut total = MarkerTree::FALSE;
for source in source.iter() {
total.or(source.marker());
}
// Determine the space covered by the requirement.
let mut remaining = total.negate();
remaining.and(requirement.marker);
Self(Requirement {
marker: remaining,
..Requirement::from(requirement.clone())
})
};
Either::Right(
source
.into_iter()
.map(move |source| {
let (source, mut marker) = match source {
Source::Git {
git,
subdirectory,
rev,
tag,
branch,
lfs,
marker,
..
} => {
let source = git_source(
&git,
subdirectory.map(Box::<Path>::from),
rev,
tag,
branch,
lfs,
)?;
(source, marker)
}
Source::Url {
url,
subdirectory,
marker,
..
} => {
let source =
url_source(&requirement, url, subdirectory.map(Box::<Path>::from))?;
(source, marker)
}
Source::Path {
path,
editable,
package,
marker,
..
} => {
let source = path_source(
path,
None,
RequirementOrigin::Project,
dir,
dir,
editable,
package,
)?;
(source, marker)
}
Source::Registry { index, marker, .. } => {
let Some(index) = locations
.indexes()
.filter(|index| matches!(index.origin, Some(Origin::Cli)))
.chain(indexes.iter())
.find(|Index { name, .. }| {
name.as_ref().is_some_and(|name| *name == index)
})
else {
return Err(LoweringError::MissingIndex(
requirement.name.clone(),
index,
));
};
if let Some(credentials) = index.credentials() {
credentials_cache.store_credentials(index.raw_url(), credentials);
}
let index = IndexMetadata {
url: index.url.clone(),
format: index.format,
};
let conflict = None;
let source = registry_source(&requirement, index, conflict);
(source, marker)
}
Source::Workspace { .. } => {
return Err(LoweringError::WorkspaceMember);
}
};
marker.and(requirement.marker);
Ok(Self(Requirement {
name: requirement.name.clone(),
extras: requirement.extras.clone(),
groups: Box::new([]),
marker,
source,
origin: requirement.origin.clone(),
}))
})
.chain(std::iter::once(Ok(remaining)))
.filter(|requirement| match requirement {
Ok(requirement) => !requirement.0.marker.is_false(),
Err(_) => true,
}),
)
}
/// Convert back into a [`Requirement`].
pub fn into_inner(self) -> Requirement {
self.0
}
}
/// An error parsing and merging `tool.uv.sources` with
/// `project.{dependencies,optional-dependencies}`.
#[derive(Debug, Error)]
pub enum LoweringError {
#[error(
"`{0}` is included as a workspace member, but is missing an entry in `tool.uv.sources` (e.g., `{0} = {{ workspace = true }}`)"
)]
MissingWorkspaceSource(PackageName),
#[error(
"`{0}` is included as a workspace member, but references a {1} in `tool.uv.sources`. Workspace members must be declared as workspace sources (e.g., `{0} = {{ workspace = true }}`)."
)]
NonWorkspaceSource(PackageName, SourceKind),
#[error(
"`{0}` references a workspace in `tool.uv.sources` (e.g., `{0} = {{ workspace = true }}`), but is not a workspace member"
)]
UndeclaredWorkspacePackage(PackageName),
#[error("Can only specify one of: `rev`, `tag`, or `branch`")]
MoreThanOneGitRef,
#[error(transparent)]
GitUrlParse(#[from] GitUrlParseError),
#[error("Package `{0}` references an undeclared index: `{1}`")]
MissingIndex(PackageName, IndexName),
#[error("Workspace members are not allowed in non-workspace contexts")]
WorkspaceMember,
#[error(transparent)]
InvalidUrl(#[from] DisplaySafeUrlError),
#[error(transparent)]
InvalidVerbatimUrl(#[from] uv_pep508::VerbatimUrlError),
#[error("Fragments are not allowed in URLs: `{0}`")]
ForbiddenFragment(DisplaySafeUrl),
#[error(
"`{0}` is associated with a URL source, but references a Git repository. Consider using a Git source instead (e.g., `{0} = {{ git = \"{1}\" }}`)"
)]
MissingGitSource(PackageName, DisplaySafeUrl),
#[error("`workspace = false` is not yet supported")]
WorkspaceFalse,
#[error("Source with `editable = true` must refer to a local directory, not a file: `{0}`")]
EditableFile(String),
#[error("Source with `package = true` must refer to a local directory, not a file: `{0}`")]
PackagedFile(String),
#[error(
"Git repository references local file source, but only directories are supported as transitive Git dependencies: `{0}`"
)]
GitFile(String),
#[error(transparent)]
ParsedUrl(#[from] ParsedUrlError),
#[error("Path must be UTF-8: `{0}`")]
NonUtf8Path(PathBuf),
#[error(transparent)] // Function attaches the context
RelativeTo(io::Error),
}
#[derive(Debug, Copy, Clone)]
pub enum SourceKind {
Path,
Url,
Git,
Registry,
}
impl std::fmt::Display for SourceKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Path => write!(f, "path"),
Self::Url => write!(f, "URL"),
Self::Git => write!(f, "Git"),
Self::Registry => write!(f, "registry"),
}
}
}
/// Convert a Git source into a [`RequirementSource`].
fn git_source(
git: &DisplaySafeUrl,
subdirectory: Option<Box<Path>>,
rev: Option<String>,
tag: Option<String>,
branch: Option<String>,
lfs: Option<bool>,
) -> Result<RequirementSource, LoweringError> {
let reference = match (rev, tag, branch) {
(None, None, None) => GitReference::DefaultBranch,
(Some(rev), None, None) => GitReference::from_rev(rev),
(None, Some(tag), None) => GitReference::Tag(tag),
(None, None, Some(branch)) => GitReference::Branch(branch),
_ => return Err(LoweringError::MoreThanOneGitRef),
};
// Create a PEP 508-compatible URL.
let mut url = DisplaySafeUrl::parse(&format!("git+{git}"))?;
if let Some(rev) = reference.as_str() {
let path = format!("{}@{}", url.path(), rev);
url.set_path(&path);
}
let mut frags: Vec<String> = Vec::new();
if let Some(subdirectory) = subdirectory.as_ref() {
let subdirectory = subdirectory
.to_str()
.ok_or_else(|| LoweringError::NonUtf8Path(subdirectory.to_path_buf()))?;
frags.push(format!("subdirectory={subdirectory}"));
}
// Loads Git LFS Enablement according to priority.
// First: lfs = true, lfs = false from pyproject.toml
// Second: UV_GIT_LFS from environment
let lfs = GitLfs::from(lfs);
// Preserve that we're using Git LFS in the Verbatim Url representations
if lfs.enabled() {
frags.push("lfs=true".to_string());
}
if !frags.is_empty() {
url.set_fragment(Some(&frags.join("&")));
}
let url = VerbatimUrl::from_url(url);
let repository = git.clone();
Ok(RequirementSource::Git {
url,
git: GitUrl::from_fields(repository, reference, None, lfs)?,
subdirectory,
})
}
/// Convert a URL source into a [`RequirementSource`].
fn url_source(
requirement: &uv_pep508::Requirement<VerbatimParsedUrl>,
url: DisplaySafeUrl,
subdirectory: Option<Box<Path>>,
) -> Result<RequirementSource, LoweringError> {
let mut verbatim_url = url.clone();
if verbatim_url.fragment().is_some() {
return Err(LoweringError::ForbiddenFragment(url));
}
if let Some(subdirectory) = subdirectory.as_ref() {
let subdirectory = subdirectory
.to_str()
.ok_or_else(|| LoweringError::NonUtf8Path(subdirectory.to_path_buf()))?;
verbatim_url.set_fragment(Some(&format!("subdirectory={subdirectory}")));
}
let ext = match DistExtension::from_path(url.path()) {
Ok(ext) => ext,
Err(..) if looks_like_git_repository(&url) => {
return Err(LoweringError::MissingGitSource(
requirement.name.clone(),
url.clone(),
));
}
Err(err) => {
return Err(ParsedUrlError::MissingExtensionUrl(url.to_string(), err).into());
}
};
let verbatim_url = VerbatimUrl::from_url(verbatim_url);
Ok(RequirementSource::Url {
location: url,
subdirectory,
ext,
url: verbatim_url,
})
}
/// Convert a registry source into a [`RequirementSource`].
fn registry_source(
requirement: &uv_pep508::Requirement<VerbatimParsedUrl>,
index: IndexMetadata,
conflict: Option<ConflictItem>,
) -> RequirementSource {
match &requirement.version_or_url {
None => RequirementSource::Registry {
specifier: VersionSpecifiers::empty(),
index: Some(index),
conflict,
},
Some(VersionOrUrl::VersionSpecifier(version)) => RequirementSource::Registry {
specifier: version.clone(),
index: Some(index),
conflict,
},
Some(VersionOrUrl::Url(_)) => RequirementSource::Registry {
specifier: VersionSpecifiers::empty(),
index: Some(index),
conflict,
},
}
}
/// Convert a path string to a file or directory source.
fn path_source(
path: impl AsRef<Path>,
git_member: Option<&GitWorkspaceMember>,
origin: RequirementOrigin,
project_dir: &Path,
workspace_root: &Path,
editable: Option<bool>,
package: Option<bool>,
) -> Result<RequirementSource, LoweringError> {
let path = path.as_ref();
let base = match origin {
RequirementOrigin::Project => project_dir,
RequirementOrigin::Workspace => workspace_root,
};
let url = VerbatimUrl::from_path(path, base)?.with_given(path.to_string_lossy());
let install_path = url
.to_file_path()
.map_err(|()| LoweringError::RelativeTo(io::Error::other("Invalid path in file URL")))?;
let is_dir = if let Ok(metadata) = install_path.metadata() {
metadata.is_dir()
} else {
install_path.extension().is_none()
};
if is_dir {
if let Some(git_member) = git_member {
let git = git_member.git_source.git.clone();
let subdirectory = uv_fs::relative_to(install_path, git_member.fetch_root)
.expect("Workspace member must be relative");
let subdirectory = uv_fs::normalize_path_buf(subdirectory);
let subdirectory = if subdirectory == PathBuf::new() {
None
} else {
Some(subdirectory.into_boxed_path())
};
let url = DisplaySafeUrl::from(ParsedGitUrl {
url: git.clone(),
subdirectory: subdirectory.clone(),
});
return Ok(RequirementSource::Git {
git,
subdirectory,
url: VerbatimUrl::from_url(url),
});
}
if editable == Some(true) {
Ok(RequirementSource::Directory {
install_path: install_path.into_boxed_path(),
url,
editable,
r#virtual: Some(false),
})
} else {
// Determine whether the project is a package or virtual.
// If the `package` option is unset, check if `tool.uv.package` is set
// on the path source (otherwise, default to `true`).
let is_package = package.unwrap_or_else(|| {
let pyproject_path = install_path.join("pyproject.toml");
fs_err::read_to_string(&pyproject_path)
.ok()
.and_then(|contents| PyProjectToml::from_string(contents).ok())
// We don't require a build system for path dependencies
.map(|pyproject_toml| pyproject_toml.is_package(false))
.unwrap_or(true)
});
// If the project is not a package, treat it as a virtual dependency.
let r#virtual = !is_package;
Ok(RequirementSource::Directory {
install_path: install_path.into_boxed_path(),
url,
editable: Some(false),
r#virtual: Some(r#virtual),
})
}
} else {
// TODO(charlie): If a Git repo contains a source that points to a file, what should we do?
if git_member.is_some() {
return Err(LoweringError::GitFile(url.to_string()));
}
if editable == Some(true) {
| 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/src/metadata/dependency_groups.rs | crates/uv-distribution/src/metadata/dependency_groups.rs | use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use uv_auth::CredentialsCache;
use uv_configuration::SourceStrategy;
use uv_distribution_types::{IndexLocations, Requirement};
use uv_normalize::{GroupName, PackageName};
use uv_workspace::dependency_groups::FlatDependencyGroups;
use uv_workspace::pyproject::{Sources, ToolUvSources};
use uv_workspace::{
DiscoveryOptions, MemberDiscovery, VirtualProject, WorkspaceCache, WorkspaceError,
};
use crate::metadata::{GitWorkspaceMember, LoweredRequirement, MetadataError};
/// Like [`crate::RequiresDist`] but only supporting dependency-groups.
///
/// PEP 735 says:
///
/// > A pyproject.toml file with only `[dependency-groups]` and no other tables is valid.
///
/// This is a special carveout to enable users to adopt dependency-groups without having
/// to learn about projects. It is supported by `pip install --group`, and thus interfaces
/// like `uv pip install --group` must also support it for interop and conformance.
///
/// On paper this is trivial to support because dependency-groups are so self-contained
/// that they're basically a `requirements.txt` embedded within a pyproject.toml, so it's
/// fine to just grab that section and handle it independently.
///
/// However several uv extensions make this complicated, notably, as of this writing:
///
/// * tool.uv.sources
/// * tool.uv.index
///
/// These fields may also be present in the pyproject.toml, and, critically,
/// may be defined and inherited in a parent workspace pyproject.toml.
///
/// Therefore, we need to gracefully degrade from a full workspacey situation all
/// the way down to one of these stub pyproject.tomls the PEP defines. This is why
/// we avoid going through `RequiresDist` -- we don't want to muddy up the "compile a package"
/// logic with support for non-project/workspace pyproject.tomls, and we don't want to
/// muddy this logic up with setuptools fallback modes that `RequiresDist` wants.
///
/// (We used to shove this feature into that path, and then we would see there's no metadata
/// and try to run setuptools to try to desperately find any metadata, and then error out.)
#[derive(Debug, Clone)]
pub struct SourcedDependencyGroups {
pub name: Option<PackageName>,
pub dependency_groups: BTreeMap<GroupName, Box<[Requirement]>>,
}
impl SourcedDependencyGroups {
/// Lower by considering `tool.uv` in `pyproject.toml` if present, used for Git and directory
/// dependencies.
pub async fn from_virtual_project(
pyproject_path: &Path,
git_member: Option<&GitWorkspaceMember<'_>>,
locations: &IndexLocations,
source_strategy: SourceStrategy,
cache: &WorkspaceCache,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
// If the `pyproject.toml` doesn't exist, fail early.
if !pyproject_path.is_file() {
return Err(MetadataError::MissingPyprojectToml(
pyproject_path.to_path_buf(),
));
}
let discovery = DiscoveryOptions {
stop_discovery_at: git_member.map(|git_member| {
git_member
.fetch_root
.parent()
.expect("git checkout has a parent")
.to_path_buf()
}),
members: match source_strategy {
SourceStrategy::Enabled => MemberDiscovery::default(),
SourceStrategy::Disabled => MemberDiscovery::None,
},
..DiscoveryOptions::default()
};
// The subsequent API takes an absolute path to the dir the pyproject is in
let empty = PathBuf::new();
let absolute_pyproject_path =
std::path::absolute(pyproject_path).map_err(WorkspaceError::Normalize)?;
let project_dir = absolute_pyproject_path.parent().unwrap_or(&empty);
let project = VirtualProject::discover(project_dir, &discovery, cache).await?;
// Collect the dependency groups.
let dependency_groups =
FlatDependencyGroups::from_pyproject_toml(project.root(), project.pyproject_toml())?;
// If sources/indexes are disabled we can just stop here
let SourceStrategy::Enabled = source_strategy else {
return Ok(Self {
name: project.project_name().cloned(),
dependency_groups: dependency_groups
.into_iter()
.map(|(name, group)| {
let requirements = group
.requirements
.into_iter()
.map(Requirement::from)
.collect();
(name, requirements)
})
.collect(),
});
};
// Collect any `tool.uv.index` entries.
let empty = vec![];
let project_indexes = project
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.index.as_deref())
.unwrap_or(&empty);
// Collect any `tool.uv.sources` and `tool.uv.dev_dependencies` from `pyproject.toml`.
let empty = BTreeMap::default();
let project_sources = project
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.unwrap_or(&empty);
// Now that we've resolved the dependency groups, we can validate that each source references
// a valid extra or group, if present.
Self::validate_sources(project_sources, &dependency_groups)?;
// Lower the dependency groups.
let dependency_groups = dependency_groups
.into_iter()
.map(|(name, group)| {
let requirements = group
.requirements
.into_iter()
.flat_map(|requirement| {
let requirement_name = requirement.name.clone();
let group = name.clone();
let extra = None;
LoweredRequirement::from_requirement(
requirement,
project.project_name(),
project.root(),
project_sources,
project_indexes,
extra,
Some(&group),
locations,
project.workspace(),
git_member,
credentials_cache,
)
.map(move |requirement| match requirement {
Ok(requirement) => Ok(requirement.into_inner()),
Err(err) => Err(MetadataError::GroupLoweringError(
group.clone(),
requirement_name.clone(),
Box::new(err),
)),
})
})
.collect::<Result<Box<_>, _>>()?;
Ok::<(GroupName, Box<_>), MetadataError>((name, requirements))
})
.collect::<Result<BTreeMap<_, _>, _>>()?;
Ok(Self {
name: project.project_name().cloned(),
dependency_groups,
})
}
/// Validate the sources.
///
/// If a source is requested with `group`, ensure that the relevant dependency is
/// present in the relevant `dependency-groups` section.
fn validate_sources(
sources: &BTreeMap<PackageName, Sources>,
dependency_groups: &FlatDependencyGroups,
) -> Result<(), MetadataError> {
for (name, sources) in sources {
for source in sources.iter() {
if let Some(group) = source.group() {
// If the group doesn't exist at all, error.
let Some(flat_group) = dependency_groups.get(group) else {
return Err(MetadataError::MissingSourceGroup(
name.clone(),
group.clone(),
));
};
// If there is no such requirement with the group, error.
if !flat_group
.requirements
.iter()
.any(|requirement| requirement.name == *name)
{
return Err(MetadataError::IncompleteSourceGroup(
name.clone(),
group.clone(),
));
}
}
}
}
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-distribution/src/metadata/requires_dist.rs | crates/uv-distribution/src/metadata/requires_dist.rs | use std::collections::{BTreeMap, VecDeque};
use std::path::Path;
use std::slice;
use rustc_hash::FxHashSet;
use uv_auth::CredentialsCache;
use uv_configuration::SourceStrategy;
use uv_distribution_types::{IndexLocations, Requirement};
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_pep508::MarkerTree;
use uv_workspace::dependency_groups::FlatDependencyGroups;
use uv_workspace::pyproject::{Sources, ToolUvSources};
use uv_workspace::{DiscoveryOptions, MemberDiscovery, ProjectWorkspace, WorkspaceCache};
use crate::Metadata;
use crate::metadata::{GitWorkspaceMember, LoweredRequirement, MetadataError};
#[derive(Debug, Clone)]
pub struct RequiresDist {
pub name: PackageName,
pub requires_dist: Box<[Requirement]>,
pub provides_extra: Box<[ExtraName]>,
pub dependency_groups: BTreeMap<GroupName, Box<[Requirement]>>,
pub dynamic: bool,
}
impl RequiresDist {
/// Lower without considering `tool.uv` in `pyproject.toml`, used for index and other archive
/// dependencies.
pub fn from_metadata23(metadata: uv_pypi_types::RequiresDist) -> Self {
Self {
name: metadata.name,
requires_dist: Box::into_iter(metadata.requires_dist)
.map(Requirement::from)
.collect(),
provides_extra: metadata.provides_extra,
dependency_groups: BTreeMap::default(),
dynamic: metadata.dynamic,
}
}
/// Lower by considering `tool.uv` in `pyproject.toml` if present, used for Git and directory
/// dependencies.
pub async fn from_project_maybe_workspace(
metadata: uv_pypi_types::RequiresDist,
install_path: &Path,
git_member: Option<&GitWorkspaceMember<'_>>,
locations: &IndexLocations,
sources: SourceStrategy,
cache: &WorkspaceCache,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
let discovery = DiscoveryOptions {
stop_discovery_at: git_member.map(|git_member| {
git_member
.fetch_root
.parent()
.expect("git checkout has a parent")
.to_path_buf()
}),
members: match sources {
SourceStrategy::Enabled => MemberDiscovery::default(),
SourceStrategy::Disabled => MemberDiscovery::None,
},
..DiscoveryOptions::default()
};
let Some(project_workspace) =
ProjectWorkspace::from_maybe_project_root(install_path, &discovery, cache).await?
else {
return Ok(Self::from_metadata23(metadata));
};
Self::from_project_workspace(
metadata,
&project_workspace,
git_member,
locations,
sources,
credentials_cache,
)
}
fn from_project_workspace(
metadata: uv_pypi_types::RequiresDist,
project_workspace: &ProjectWorkspace,
git_member: Option<&GitWorkspaceMember<'_>>,
locations: &IndexLocations,
source_strategy: SourceStrategy,
credentials_cache: &CredentialsCache,
) -> Result<Self, MetadataError> {
// Collect any `tool.uv.index` entries.
let empty = vec![];
let project_indexes = match source_strategy {
SourceStrategy::Enabled => project_workspace
.current_project()
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.index.as_deref())
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
// Collect any `tool.uv.sources` and `tool.uv.dev_dependencies` from `pyproject.toml`.
let empty = BTreeMap::default();
let project_sources = match source_strategy {
SourceStrategy::Enabled => project_workspace
.current_project()
.pyproject_toml()
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.map(ToolUvSources::inner)
.unwrap_or(&empty),
SourceStrategy::Disabled => &empty,
};
let dependency_groups = FlatDependencyGroups::from_pyproject_toml(
project_workspace.current_project().root(),
project_workspace.current_project().pyproject_toml(),
)?;
// Now that we've resolved the dependency groups, we can validate that each source references
// a valid extra or group, if present.
Self::validate_sources(project_sources, &metadata, &dependency_groups)?;
// Lower the dependency groups.
let dependency_groups = dependency_groups
.into_iter()
.map(|(name, flat_group)| {
let requirements = match source_strategy {
SourceStrategy::Enabled => flat_group
.requirements
.into_iter()
.flat_map(|requirement| {
let requirement_name = requirement.name.clone();
let group = name.clone();
let extra = None;
LoweredRequirement::from_requirement(
requirement,
Some(&metadata.name),
project_workspace.project_root(),
project_sources,
project_indexes,
extra,
Some(&group),
locations,
project_workspace.workspace(),
git_member,
credentials_cache,
)
.map(
move |requirement| match requirement {
Ok(requirement) => Ok(requirement.into_inner()),
Err(err) => Err(MetadataError::GroupLoweringError(
group.clone(),
requirement_name.clone(),
Box::new(err),
)),
},
)
})
.collect::<Result<Box<_>, _>>(),
SourceStrategy::Disabled => Ok(flat_group
.requirements
.into_iter()
.map(Requirement::from)
.collect()),
}?;
Ok::<(GroupName, Box<_>), MetadataError>((name, requirements))
})
.collect::<Result<BTreeMap<_, _>, _>>()?;
// Lower the requirements.
let requires_dist = Box::into_iter(metadata.requires_dist);
let requires_dist = match source_strategy {
SourceStrategy::Enabled => requires_dist
.flat_map(|requirement| {
let requirement_name = requirement.name.clone();
let extra = requirement.marker.top_level_extra_name();
let group = None;
LoweredRequirement::from_requirement(
requirement,
Some(&metadata.name),
project_workspace.project_root(),
project_sources,
project_indexes,
extra.as_deref(),
group,
locations,
project_workspace.workspace(),
git_member,
credentials_cache,
)
.map(move |requirement| match requirement {
Ok(requirement) => Ok(requirement.into_inner()),
Err(err) => Err(MetadataError::LoweringError(
requirement_name.clone(),
Box::new(err),
)),
})
})
.collect::<Result<Box<_>, _>>()?,
SourceStrategy::Disabled => requires_dist.into_iter().map(Requirement::from).collect(),
};
Ok(Self {
name: metadata.name,
requires_dist,
dependency_groups,
provides_extra: metadata.provides_extra,
dynamic: metadata.dynamic,
})
}
/// Validate the sources for a given [`uv_pypi_types::RequiresDist`].
///
/// If a source is requested with an `extra` or `group`, ensure that the relevant dependency is
/// present in the relevant `project.optional-dependencies` or `dependency-groups` section.
fn validate_sources(
sources: &BTreeMap<PackageName, Sources>,
metadata: &uv_pypi_types::RequiresDist,
dependency_groups: &FlatDependencyGroups,
) -> Result<(), MetadataError> {
for (name, sources) in sources {
for source in sources.iter() {
if let Some(extra) = source.extra() {
// If the extra doesn't exist at all, error.
if !metadata.provides_extra.contains(extra) {
return Err(MetadataError::MissingSourceExtra(
name.clone(),
extra.clone(),
));
}
// If there is no such requirement with the extra, error.
if !metadata.requires_dist.iter().any(|requirement| {
requirement.name == *name
&& requirement.marker.top_level_extra_name().as_deref() == Some(extra)
}) {
return Err(MetadataError::IncompleteSourceExtra(
name.clone(),
extra.clone(),
));
}
}
if let Some(group) = source.group() {
// If the group doesn't exist at all, error.
let Some(flat_group) = dependency_groups.get(group) else {
return Err(MetadataError::MissingSourceGroup(
name.clone(),
group.clone(),
));
};
// If there is no such requirement with the group, error.
if !flat_group
.requirements
.iter()
.any(|requirement| requirement.name == *name)
{
return Err(MetadataError::IncompleteSourceGroup(
name.clone(),
group.clone(),
));
}
}
}
}
Ok(())
}
}
impl From<Metadata> for RequiresDist {
fn from(metadata: Metadata) -> Self {
Self {
name: metadata.name,
requires_dist: metadata.requires_dist,
provides_extra: metadata.provides_extra,
dependency_groups: metadata.dependency_groups,
dynamic: metadata.dynamic,
}
}
}
/// Like [`uv_pypi_types::RequiresDist`], but with any recursive (or self-referential) dependencies
/// resolved.
///
/// For example, given:
/// ```toml
/// [project]
/// name = "example"
/// version = "0.1.0"
/// requires-python = ">=3.13.0"
/// dependencies = []
///
/// [project.optional-dependencies]
/// all = [
/// "example[async]",
/// ]
/// async = [
/// "fastapi",
/// ]
/// ```
///
/// A build backend could return:
/// ```txt
/// Metadata-Version: 2.2
/// Name: example
/// Version: 0.1.0
/// Requires-Python: >=3.13.0
/// Provides-Extra: all
/// Requires-Dist: example[async]; extra == "all"
/// Provides-Extra: async
/// Requires-Dist: fastapi; extra == "async"
/// ```
///
/// Or:
/// ```txt
/// Metadata-Version: 2.4
/// Name: example
/// Version: 0.1.0
/// Requires-Python: >=3.13.0
/// Provides-Extra: all
/// Requires-Dist: fastapi; extra == 'all'
/// Provides-Extra: async
/// Requires-Dist: fastapi; extra == 'async'
/// ```
///
/// The [`FlatRequiresDist`] struct is used to flatten out the recursive dependencies, i.e., convert
/// from the former to the latter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlatRequiresDist(Box<[Requirement]>);
impl FlatRequiresDist {
/// Flatten a set of requirements, resolving any self-references.
pub fn from_requirements(requirements: Box<[Requirement]>, name: &PackageName) -> Self {
// If there are no self-references, we can return early.
if requirements.iter().all(|req| req.name != *name) {
return Self(requirements);
}
// Memoize the top level extras, in the same order as `requirements`
let top_level_extras: Vec<_> = requirements
.iter()
.map(|req| req.marker.top_level_extra_name())
.collect();
// Transitively process all extras that are recursively included.
let mut flattened = requirements.to_vec();
let mut seen = FxHashSet::<(ExtraName, MarkerTree)>::default();
let mut queue: VecDeque<_> = flattened
.iter()
.filter(|req| req.name == *name)
.flat_map(|req| req.extras.iter().cloned().map(|extra| (extra, req.marker)))
.collect();
while let Some((extra, marker)) = queue.pop_front() {
if !seen.insert((extra.clone(), marker)) {
continue;
}
// Find the requirements for the extra.
for (requirement, top_level_extra) in requirements.iter().zip(top_level_extras.iter()) {
if top_level_extra.as_deref() != Some(&extra) {
continue;
}
let requirement = {
let mut marker = marker;
marker.and(requirement.marker);
Requirement {
name: requirement.name.clone(),
extras: requirement.extras.clone(),
groups: requirement.groups.clone(),
source: requirement.source.clone(),
origin: requirement.origin.clone(),
marker: marker.simplify_extras(slice::from_ref(&extra)),
}
};
if requirement.name == *name {
// Add each transitively included extra.
queue.extend(
requirement
.extras
.iter()
.cloned()
.map(|extra| (extra, requirement.marker)),
);
} else {
// Add the requirements for that extra.
flattened.push(requirement);
}
}
}
// Drop all the self-references now that we've flattened them out.
flattened.retain(|req| req.name != *name);
// Retain any self-constraints for that extra, e.g., if `project[foo]` includes
// `project[bar]>1.0`, as a dependency, we need to propagate `project>1.0`, in addition to
// transitively expanding `project[bar]`.
for req in &requirements {
if req.name == *name {
if !req.source.is_empty() {
flattened.push(Requirement {
name: req.name.clone(),
extras: Box::new([]),
groups: req.groups.clone(),
source: req.source.clone(),
origin: req.origin.clone(),
marker: req.marker,
});
}
}
}
Self(flattened.into_boxed_slice())
}
/// Consume the [`FlatRequiresDist`] and return the inner requirements.
pub fn into_inner(self) -> Box<[Requirement]> {
self.0
}
}
impl IntoIterator for FlatRequiresDist {
type Item = Requirement;
type IntoIter = <Box<[Requirement]> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
Box::into_iter(self.0)
}
}
#[cfg(test)]
mod test {
use std::path::Path;
use std::str::FromStr;
use anyhow::Context;
use indoc::indoc;
use insta::assert_snapshot;
use uv_auth::CredentialsCache;
use uv_configuration::SourceStrategy;
use uv_distribution_types::IndexLocations;
use uv_normalize::PackageName;
use uv_pep508::Requirement;
use uv_workspace::pyproject::PyProjectToml;
use uv_workspace::{DiscoveryOptions, ProjectWorkspace, WorkspaceCache};
use crate::RequiresDist;
use crate::metadata::requires_dist::FlatRequiresDist;
async fn requires_dist_from_pyproject_toml(contents: &str) -> anyhow::Result<RequiresDist> {
let pyproject_toml = PyProjectToml::from_string(contents.to_string())?;
let path = Path::new("pyproject.toml");
let project_workspace = ProjectWorkspace::from_project(
path,
pyproject_toml
.project
.as_ref()
.context("metadata field project not found")?,
&pyproject_toml,
&DiscoveryOptions {
stop_discovery_at: Some(path.to_path_buf()),
..DiscoveryOptions::default()
},
&WorkspaceCache::default(),
)
.await?;
let pyproject_toml = uv_pypi_types::PyProjectToml::from_toml(contents)?;
let requires_dist = uv_pypi_types::RequiresDist::from_pyproject_toml(pyproject_toml)?;
Ok(RequiresDist::from_project_workspace(
requires_dist,
&project_workspace,
None,
&IndexLocations::default(),
SourceStrategy::default(),
&CredentialsCache::new(),
)?)
}
async fn format_err(input: &str) -> String {
use std::fmt::Write;
let err = requires_dist_from_pyproject_toml(input).await.unwrap_err();
let mut causes = err.chain();
let mut message = String::new();
let _ = writeln!(message, "error: {}", causes.next().unwrap());
for err in causes {
let _ = writeln!(message, " Caused by: {err}");
}
message
}
#[tokio::test]
async fn wrong_type() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm",
]
[tool.uv.sources]
tqdm = true
"#};
assert_snapshot!(format_err(input).await, @r###"
error: TOML parse error at line 8, column 8
|
8 | tqdm = true
| ^^^^
invalid type: boolean `true`, expected a single source (as a map) or list of sources
"###);
}
#[tokio::test]
async fn too_many_git_specs() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm",
]
[tool.uv.sources]
tqdm = { git = "https://github.com/tqdm/tqdm", rev = "baaaaaab", tag = "v1.0.0" }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: TOML parse error at line 8, column 8
|
8 | tqdm = { git = "https://github.com/tqdm/tqdm", rev = "baaaaaab", tag = "v1.0.0" }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
expected at most one of `rev`, `tag`, or `branch`
"###);
}
#[tokio::test]
async fn too_many_git_typo() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm",
]
[tool.uv.sources]
tqdm = { git = "https://github.com/tqdm/tqdm", ref = "baaaaaab" }
"#};
assert_snapshot!(format_err(input).await, @r#"
error: TOML parse error at line 8, column 48
|
8 | tqdm = { git = "https://github.com/tqdm/tqdm", ref = "baaaaaab" }
| ^^^
unknown field `ref`, expected one of `git`, `subdirectory`, `rev`, `tag`, `branch`, `lfs`, `url`, `path`, `editable`, `package`, `index`, `workspace`, `marker`, `extra`, `group`
"#);
}
#[tokio::test]
async fn extra_and_group() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = []
[tool.uv.sources]
tqdm = { git = "https://github.com/tqdm/tqdm", extra = "torch", group = "dev" }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: TOML parse error at line 7, column 8
|
7 | tqdm = { git = "https://github.com/tqdm/tqdm", extra = "torch", group = "dev" }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cannot specify both `extra` and `group`
"###);
}
#[tokio::test]
async fn you_cant_mix_those() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm",
]
[tool.uv.sources]
tqdm = { path = "tqdm", index = "torch" }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: TOML parse error at line 8, column 8
|
8 | tqdm = { path = "tqdm", index = "torch" }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cannot specify both `path` and `index`
"###);
}
#[tokio::test]
async fn missing_constraint() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm",
]
"#};
assert!(requires_dist_from_pyproject_toml(input).await.is_ok());
}
#[tokio::test]
async fn invalid_syntax() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm ==4.66.0",
]
[tool.uv.sources]
tqdm = { url = invalid url to tqdm-4.66.0-py3-none-any.whl" }
"#};
assert_snapshot!(format_err(input).await, @r#"
error: TOML parse error at line 8, column 16
|
8 | tqdm = { url = invalid url to tqdm-4.66.0-py3-none-any.whl" }
| ^
missing opening quote, expected `"`
"#);
}
#[tokio::test]
async fn invalid_url() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm ==4.66.0",
]
[tool.uv.sources]
tqdm = { url = "§invalid#+#*Ä" }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: TOML parse error at line 8, column 16
|
8 | tqdm = { url = "§invalid#+#*Ä" }
| ^^^^^^^^^^^^^^^^^
relative URL without a base: "§invalid#+#*Ä"
"###);
}
#[tokio::test]
async fn workspace_and_url_spec() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm @ git+https://github.com/tqdm/tqdm",
]
[tool.uv.sources]
tqdm = { workspace = true }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: Failed to parse entry: `tqdm`
Caused by: `tqdm` references a workspace in `tool.uv.sources` (e.g., `tqdm = { workspace = true }`), but is not a workspace member
"###);
}
#[tokio::test]
async fn missing_workspace_package() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dependencies = [
"tqdm ==4.66.0",
]
[tool.uv.sources]
tqdm = { workspace = true }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: Failed to parse entry: `tqdm`
Caused by: `tqdm` references a workspace in `tool.uv.sources` (e.g., `tqdm = { workspace = true }`), but is not a workspace member
"###);
}
#[tokio::test]
async fn cant_be_dynamic() {
let input = indoc! {r#"
[project]
name = "foo"
version = "0.0.0"
dynamic = [
"dependencies"
]
[tool.uv.sources]
tqdm = { workspace = true }
"#};
assert_snapshot!(format_err(input).await, @r###"
error: The following field was marked as dynamic: dependencies
"###);
}
#[tokio::test]
async fn missing_project_section() {
let input = indoc! {"
[tool.uv.sources]
tqdm = { workspace = true }
"};
assert_snapshot!(format_err(input).await, @r###"
error: metadata field project not found
"###);
}
#[test]
fn test_flat_requires_dist_noop() {
let name = PackageName::from_str("pkg").unwrap();
let requirements = [
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
];
let expected = FlatRequiresDist(
[
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
]
.into(),
);
let actual = FlatRequiresDist::from_requirements(requirements.into(), &name);
assert_eq!(actual, expected);
}
#[test]
fn test_flat_requires_dist_basic() {
let name = PackageName::from_str("pkg").unwrap();
let requirements = [
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("pkg[dev]; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
];
let expected = FlatRequiresDist(
[
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'test'")
.unwrap()
.into(),
]
.into(),
);
let actual = FlatRequiresDist::from_requirements(requirements.into(), &name);
assert_eq!(actual, expected);
}
#[test]
fn test_flat_requires_dist_with_markers() {
let name = PackageName::from_str("pkg").unwrap();
let requirements = vec![
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("pkg[dev]; extra == 'test' and sys_platform == 'win32'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev' and sys_platform == 'win32'")
.unwrap()
.into(),
];
let expected = FlatRequiresDist(
[
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev' and sys_platform == 'win32'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'test' and sys_platform == 'win32'")
.unwrap()
.into(),
]
.into(),
);
let actual = FlatRequiresDist::from_requirements(requirements.into(), &name);
assert_eq!(actual, expected);
}
#[test]
fn test_flat_requires_dist_self_constraint() {
let name = PackageName::from_str("pkg").unwrap();
let requirements = [
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
Requirement::from_str("pkg[async]==1.0.0").unwrap().into(),
];
let expected = FlatRequiresDist(
[
Requirement::from_str("requests>=2.0.0").unwrap().into(),
Requirement::from_str("pytest; extra == 'test'")
.unwrap()
.into(),
Requirement::from_str("black; extra == 'dev'")
.unwrap()
.into(),
Requirement::from_str("pkg==1.0.0").unwrap().into(),
]
.into(),
);
let actual = FlatRequiresDist::from_requirements(requirements.into(), &name);
assert_eq!(actual, 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-distribution/src/source/revision.rs | crates/uv-distribution/src/source/revision.rs | use serde::{Deserialize, Serialize};
use std::path::Path;
use uv_distribution_types::Hashed;
use uv_pypi_types::{HashDigest, HashDigests};
/// The [`Revision`] is a thin wrapper around a unique identifier for the source distribution.
///
/// A revision represents a unique version of a source distribution, at a level more granular than
/// (e.g.) the version number of the distribution itself. For example, a source distribution hosted
/// at a URL or a local file path may have multiple revisions, each representing a unique state of
/// the distribution, despite the reported version number remaining the same.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Revision {
id: RevisionId,
hashes: HashDigests,
}
impl Revision {
/// Initialize a new [`Revision`] with a random UUID.
pub(crate) fn new() -> Self {
Self {
id: RevisionId::new(),
hashes: HashDigests::empty(),
}
}
/// Return the unique ID of the manifest.
pub(crate) fn id(&self) -> &RevisionId {
&self.id
}
/// Return the computed hashes of the archive.
pub(crate) fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
/// Return the computed hashes of the archive.
pub(crate) fn into_hashes(self) -> HashDigests {
self.hashes
}
/// Set the computed hashes of the archive.
#[must_use]
pub(crate) fn with_hashes(mut self, hashes: HashDigests) -> Self {
self.hashes = hashes;
self
}
}
impl Hashed for Revision {
fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
}
/// A unique identifier for a revision of a source distribution.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct RevisionId(String);
impl RevisionId {
/// Generate a new unique identifier for an archive.
fn new() -> Self {
Self(nanoid::nanoid!())
}
pub(crate) fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl AsRef<str> for RevisionId {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl AsRef<Path> for RevisionId {
fn as_ref(&self) -> &Path {
self.0.as_ref()
}
}
| 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/src/source/mod.rs | crates/uv-distribution/src/source/mod.rs | //! Fetch and build source distributions from remote sources.
// This is to squash warnings about `|r| r.into_git_reporter()`. Clippy wants
// me to eta-reduce that and write it as
// `<(dyn reporter::Reporter + 'static)>::into_git_reporter`
// instead. But that's a monster. On the other hand, applying this suppression
// instruction more granularly is annoying. So we just slap it on the module
// for now. ---AG
#![allow(clippy::redundant_closure_for_method_calls)]
use std::borrow::Cow;
use std::ops::Bound;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use fs_err::tokio as fs;
use futures::{FutureExt, TryStreamExt};
use reqwest::{Response, StatusCode};
use tokio_util::compat::FuturesAsyncReadCompatExt;
use tracing::{Instrument, debug, info_span, instrument, warn};
use url::Url;
use zip::ZipArchive;
use uv_auth::CredentialsCache;
use uv_cache::{Cache, CacheBucket, CacheEntry, CacheShard, Removal, WheelCache};
use uv_cache_info::CacheInfo;
use uv_client::{
CacheControl, CachedClientError, Connectivity, DataWithCachePolicy, RegistryClient,
};
use uv_configuration::{BuildKind, BuildOutput, SourceStrategy};
use uv_distribution_filename::{SourceDistExtension, WheelFilename};
use uv_distribution_types::{
BuildInfo, BuildVariables, BuildableSource, ConfigSettings, DirectorySourceUrl,
ExtraBuildRequirement, GitSourceUrl, HashPolicy, Hashed, IndexUrl, PathSourceUrl, SourceDist,
SourceUrl,
};
use uv_extract::hash::Hasher;
use uv_fs::{rename_with_retry, write_atomic};
use uv_git::{GIT_LFS, GitError};
use uv_git_types::{GitHubRepository, GitOid};
use uv_metadata::read_archive_metadata;
use uv_normalize::PackageName;
use uv_pep440::{Version, release_specifiers_to_ranges};
use uv_platform_tags::Tags;
use uv_pypi_types::{HashAlgorithm, HashDigest, HashDigests, PyProjectToml, ResolutionMetadata};
use uv_redacted::DisplaySafeUrl;
use uv_types::{BuildContext, BuildKey, BuildStack, SourceBuildTrait};
use uv_workspace::pyproject::ToolUvSources;
use crate::distribution_database::ManagedClient;
use crate::error::Error;
use crate::metadata::{ArchiveMetadata, GitWorkspaceMember, Metadata};
use crate::source::built_wheel_metadata::{BuiltWheelFile, BuiltWheelMetadata};
use crate::source::revision::Revision;
use crate::{Reporter, RequiresDist};
mod built_wheel_metadata;
mod revision;
/// Fetch and build a source distribution from a remote source, or from a local cache.
pub(crate) struct SourceDistributionBuilder<'a, T: BuildContext> {
build_context: &'a T,
build_stack: Option<&'a BuildStack>,
reporter: Option<Arc<dyn Reporter>>,
}
/// The name of the file that contains the revision ID for a remote distribution, encoded via `MsgPack`.
pub(crate) const HTTP_REVISION: &str = "revision.http";
/// The name of the file that contains the revision ID for a local distribution, encoded via `MsgPack`.
pub(crate) const LOCAL_REVISION: &str = "revision.rev";
/// The name of the file that contains the cached distribution metadata, encoded via `MsgPack`.
pub(crate) const METADATA: &str = "metadata.msgpack";
/// The directory within each entry under which to store the unpacked source distribution.
pub(crate) const SOURCE: &str = "src";
impl<'a, T: BuildContext> SourceDistributionBuilder<'a, T> {
/// Initialize a [`SourceDistributionBuilder`] from a [`BuildContext`].
pub(crate) fn new(build_context: &'a T) -> Self {
Self {
build_context,
build_stack: None,
reporter: None,
}
}
/// Set the [`BuildStack`] to use for the [`SourceDistributionBuilder`].
#[must_use]
pub(crate) fn with_build_stack(self, build_stack: &'a BuildStack) -> Self {
Self {
build_stack: Some(build_stack),
..self
}
}
/// Set the [`Reporter`] to use for the [`SourceDistributionBuilder`].
#[must_use]
pub(crate) fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
reporter: Some(reporter),
..self
}
}
/// Download and build a [`SourceDist`].
pub(crate) async fn download_and_build(
&self,
source: &BuildableSource<'_>,
tags: &Tags,
hashes: HashPolicy<'_>,
client: &ManagedClient<'_>,
) -> Result<BuiltWheelMetadata, Error> {
let built_wheel_metadata = match &source {
BuildableSource::Dist(SourceDist::Registry(dist)) => {
// For registry source distributions, shard by package, then version, for
// convenience in debugging.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Index(&dist.index)
.wheel_dir(dist.name.as_ref())
.join(dist.version.to_string()),
);
let url = dist.file.url.to_url()?;
// If the URL is a file URL, use the local path directly.
if url.scheme() == "file" {
let path = url
.to_file_path()
.map_err(|()| Error::NonFileUrl(url.clone()))?;
return self
.archive(
source,
&PathSourceUrl {
url: &url,
path: Cow::Owned(path),
ext: dist.ext,
},
&cache_shard,
tags,
hashes,
)
.boxed_local()
.await;
}
self.url(
source,
&url,
Some(&dist.index),
&cache_shard,
None,
dist.ext,
tags,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::DirectUrl(dist)) => {
// For direct URLs, cache directly under the hash of the URL itself.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Url(&dist.url).root(),
);
self.url(
source,
&dist.url,
None,
&cache_shard,
dist.subdirectory.as_deref(),
dist.ext,
tags,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Git(dist)) => {
self.git(source, &GitSourceUrl::from(dist), tags, hashes, client)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Directory(dist)) => {
self.source_tree(source, &DirectorySourceUrl::from(dist), tags, hashes)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Path(dist)) => {
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Path(&dist.url).root(),
);
self.archive(
source,
&PathSourceUrl::from(dist),
&cache_shard,
tags,
hashes,
)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Direct(resource)) => {
// For direct URLs, cache directly under the hash of the URL itself.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Url(resource.url).root(),
);
self.url(
source,
resource.url,
None,
&cache_shard,
resource.subdirectory,
resource.ext,
tags,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Git(resource)) => {
self.git(source, resource, tags, hashes, client)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Directory(resource)) => {
self.source_tree(source, resource, tags, hashes)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Path(resource)) => {
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Path(resource.url).root(),
);
self.archive(source, resource, &cache_shard, tags, hashes)
.boxed_local()
.await?
}
};
Ok(built_wheel_metadata)
}
/// Download a [`SourceDist`] and determine its metadata. This typically involves building the
/// source distribution into a wheel; however, some build backends support determining the
/// metadata without building the source distribution.
pub(crate) async fn download_and_build_metadata(
&self,
source: &BuildableSource<'_>,
hashes: HashPolicy<'_>,
client: &ManagedClient<'_>,
) -> Result<ArchiveMetadata, Error> {
let metadata = match &source {
BuildableSource::Dist(SourceDist::Registry(dist)) => {
// For registry source distributions, shard by package, then version.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Index(&dist.index)
.wheel_dir(dist.name.as_ref())
.join(dist.version.to_string()),
);
let url = dist.file.url.to_url()?;
// If the URL is a file URL, use the local path directly.
if url.scheme() == "file" {
let path = url
.to_file_path()
.map_err(|()| Error::NonFileUrl(url.clone()))?;
return self
.archive_metadata(
source,
&PathSourceUrl {
url: &url,
path: Cow::Owned(path),
ext: dist.ext,
},
&cache_shard,
hashes,
)
.boxed_local()
.await;
}
self.url_metadata(
source,
&url,
Some(&dist.index),
&cache_shard,
None,
dist.ext,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::DirectUrl(dist)) => {
// For direct URLs, cache directly under the hash of the URL itself.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Url(&dist.url).root(),
);
self.url_metadata(
source,
&dist.url,
None,
&cache_shard,
dist.subdirectory.as_deref(),
dist.ext,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Git(dist)) => {
self.git_metadata(
source,
&GitSourceUrl::from(dist),
hashes,
client,
client.unmanaged.credentials_cache(),
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Directory(dist)) => {
self.source_tree_metadata(
source,
&DirectorySourceUrl::from(dist),
hashes,
client.unmanaged.credentials_cache(),
)
.boxed_local()
.await?
}
BuildableSource::Dist(SourceDist::Path(dist)) => {
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Path(&dist.url).root(),
);
self.archive_metadata(source, &PathSourceUrl::from(dist), &cache_shard, hashes)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Direct(resource)) => {
// For direct URLs, cache directly under the hash of the URL itself.
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Url(resource.url).root(),
);
self.url_metadata(
source,
resource.url,
None,
&cache_shard,
resource.subdirectory,
resource.ext,
hashes,
client,
)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Git(resource)) => {
self.git_metadata(
source,
resource,
hashes,
client,
client.unmanaged.credentials_cache(),
)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Directory(resource)) => {
self.source_tree_metadata(
source,
resource,
hashes,
client.unmanaged.credentials_cache(),
)
.boxed_local()
.await?
}
BuildableSource::Url(SourceUrl::Path(resource)) => {
let cache_shard = self.build_context.cache().shard(
CacheBucket::SourceDistributions,
WheelCache::Path(resource.url).root(),
);
self.archive_metadata(source, resource, &cache_shard, hashes)
.boxed_local()
.await?
}
};
Ok(metadata)
}
/// Determine the [`ConfigSettings`] for the given package name.
fn config_settings_for(&self, name: Option<&PackageName>) -> Cow<'_, ConfigSettings> {
if let Some(name) = name {
if let Some(package_settings) = self.build_context.config_settings_package().get(name) {
Cow::Owned(
package_settings
.clone()
.merge(self.build_context.config_settings().clone()),
)
} else {
Cow::Borrowed(self.build_context.config_settings())
}
} else {
Cow::Borrowed(self.build_context.config_settings())
}
}
/// Determine the extra build dependencies for the given package name.
fn extra_build_dependencies_for(&self, name: Option<&PackageName>) -> &[ExtraBuildRequirement] {
name.and_then(|name| {
self.build_context
.extra_build_requires()
.get(name)
.map(Vec::as_slice)
})
.unwrap_or(&[])
}
/// Determine the extra build variables for the given package name.
fn extra_build_variables_for(&self, name: Option<&PackageName>) -> Option<&BuildVariables> {
name.and_then(|name| self.build_context.extra_build_variables().get(name))
}
/// Build a source distribution from a remote URL.
async fn url<'data>(
&self,
source: &BuildableSource<'data>,
url: &'data DisplaySafeUrl,
index: Option<&'data IndexUrl>,
cache_shard: &CacheShard,
subdirectory: Option<&'data Path>,
ext: SourceDistExtension,
tags: &Tags,
hashes: HashPolicy<'_>,
client: &ManagedClient<'_>,
) -> Result<BuiltWheelMetadata, Error> {
let _lock = cache_shard.lock().await.map_err(Error::CacheLock)?;
// Fetch the revision for the source distribution.
let revision = self
.url_revision(source, ext, url, index, cache_shard, hashes, client)
.await?;
// Before running the build, check that the hashes match.
if !revision.satisfies(hashes) {
return Err(Error::hash_mismatch(
source.to_string(),
hashes.digests(),
revision.hashes(),
));
}
// Scope all operations to the revision. Within the revision, there's no need to check for
// freshness, since entries have to be fresher than the revision itself.
let cache_shard = cache_shard.shard(revision.id());
let source_dist_entry = cache_shard.entry(SOURCE);
// We don't track any cache information for URL-based source distributions; they're assumed
// to be immutable.
let cache_info = CacheInfo::default();
// If there are build settings or extra build dependencies, we need to scope to a cache shard.
let config_settings = self.config_settings_for(source.name());
let extra_build_deps = self.extra_build_dependencies_for(source.name());
let extra_build_variables = self.extra_build_variables_for(source.name());
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_variables);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
// If the cache contains a compatible wheel, return it.
if let Some(file) = BuiltWheelFile::find_in_cache(tags, &cache_shard)
.ok()
.flatten()
.filter(|file| file.matches(source.name(), source.version()))
{
return Ok(BuiltWheelMetadata::from_file(
file,
revision.into_hashes(),
cache_info,
build_info,
));
}
// Otherwise, we need to build a wheel. Before building, ensure that the source is present.
let revision = if source_dist_entry.path().is_dir() {
revision
} else {
self.heal_url_revision(
source,
ext,
url,
index,
&source_dist_entry,
revision,
hashes,
client,
)
.await?
};
// Validate that the subdirectory exists.
if let Some(subdirectory) = subdirectory {
if !source_dist_entry.path().join(subdirectory).is_dir() {
return Err(Error::MissingSubdirectory(
url.clone(),
subdirectory.to_path_buf(),
));
}
}
let task = self
.reporter
.as_ref()
.map(|reporter| reporter.on_build_start(source));
// Build the source distribution.
let (disk_filename, wheel_filename, metadata) = self
.build_distribution(
source,
source_dist_entry.path(),
subdirectory,
&cache_shard,
SourceStrategy::Disabled,
)
.await?;
if let Some(task) = task {
if let Some(reporter) = self.reporter.as_ref() {
reporter.on_build_complete(source, task);
}
}
// Store the metadata.
let metadata_entry = cache_shard.entry(METADATA);
write_atomic(metadata_entry.path(), rmp_serde::to_vec(&metadata)?)
.await
.map_err(Error::CacheWrite)?;
Ok(BuiltWheelMetadata {
path: cache_shard.join(&disk_filename).into_boxed_path(),
target: cache_shard.join(wheel_filename.stem()).into_boxed_path(),
filename: wheel_filename,
hashes: revision.into_hashes(),
cache_info,
build_info,
})
}
/// Build the source distribution's metadata from a local path.
///
/// If the build backend supports `prepare_metadata_for_build_wheel`, this method will avoid
/// building the wheel.
async fn url_metadata<'data>(
&self,
source: &BuildableSource<'data>,
url: &'data DisplaySafeUrl,
index: Option<&'data IndexUrl>,
cache_shard: &CacheShard,
subdirectory: Option<&'data Path>,
ext: SourceDistExtension,
hashes: HashPolicy<'_>,
client: &ManagedClient<'_>,
) -> Result<ArchiveMetadata, Error> {
let _lock = cache_shard.lock().await.map_err(Error::CacheLock)?;
// Fetch the revision for the source distribution.
let revision = self
.url_revision(source, ext, url, index, cache_shard, hashes, client)
.await?;
// Before running the build, check that the hashes match.
if !revision.satisfies(hashes) {
return Err(Error::hash_mismatch(
source.to_string(),
hashes.digests(),
revision.hashes(),
));
}
// Scope all operations to the revision. Within the revision, there's no need to check for
// freshness, since entries have to be fresher than the revision itself.
let cache_shard = cache_shard.shard(revision.id());
let source_dist_entry = cache_shard.entry(SOURCE);
// If the metadata is static, return it.
let dynamic =
match StaticMetadata::read(source, source_dist_entry.path(), subdirectory).await? {
StaticMetadata::Some(metadata) => {
return Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata),
hashes: revision.into_hashes(),
});
}
StaticMetadata::Dynamic => true,
StaticMetadata::None => false,
};
// If the cache contains compatible metadata, return it.
let metadata_entry = cache_shard.entry(METADATA);
match CachedMetadata::read(&metadata_entry).await {
Ok(Some(metadata)) => {
if metadata.matches(source.name(), source.version()) {
debug!("Using cached metadata for: {source}");
return Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata.into()),
hashes: revision.into_hashes(),
});
}
debug!("Cached metadata does not match expected name and version for: {source}");
}
Ok(None) => {}
Err(err) => {
debug!("Failed to deserialize cached metadata for: {source} ({err})");
}
}
// Otherwise, we need a wheel.
let revision = if source_dist_entry.path().is_dir() {
revision
} else {
self.heal_url_revision(
source,
ext,
url,
index,
&source_dist_entry,
revision,
hashes,
client,
)
.await?
};
// Validate that the subdirectory exists.
if let Some(subdirectory) = subdirectory {
if !source_dist_entry.path().join(subdirectory).is_dir() {
return Err(Error::MissingSubdirectory(
url.clone(),
subdirectory.to_path_buf(),
));
}
}
// Otherwise, we either need to build the metadata.
// If the backend supports `prepare_metadata_for_build_wheel`, use it.
if let Some(metadata) = self
.build_metadata(
source,
source_dist_entry.path(),
subdirectory,
SourceStrategy::Disabled,
)
.boxed_local()
.await?
{
// If necessary, mark the metadata as dynamic.
let metadata = if dynamic {
ResolutionMetadata {
dynamic: true,
..metadata
}
} else {
metadata
};
// Store the metadata.
fs::create_dir_all(metadata_entry.dir())
.await
.map_err(Error::CacheWrite)?;
write_atomic(metadata_entry.path(), rmp_serde::to_vec(&metadata)?)
.await
.map_err(Error::CacheWrite)?;
return Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata),
hashes: revision.into_hashes(),
});
}
// If there are build settings or extra build dependencies, we need to scope to a cache shard.
let config_settings = self.config_settings_for(source.name());
let extra_build_deps = self.extra_build_dependencies_for(source.name());
let extra_build_variables = self.extra_build_variables_for(source.name());
let build_info =
BuildInfo::from_settings(&config_settings, extra_build_deps, extra_build_variables);
let cache_shard = build_info
.cache_shard()
.map(|digest| cache_shard.shard(digest))
.unwrap_or(cache_shard);
let task = self
.reporter
.as_ref()
.map(|reporter| reporter.on_build_start(source));
// Build the source distribution.
let (_disk_filename, _wheel_filename, metadata) = self
.build_distribution(
source,
source_dist_entry.path(),
subdirectory,
&cache_shard,
SourceStrategy::Disabled,
)
.await?;
if let Some(task) = task {
if let Some(reporter) = self.reporter.as_ref() {
reporter.on_build_complete(source, task);
}
}
// If necessary, mark the metadata as dynamic.
let metadata = if dynamic {
ResolutionMetadata {
dynamic: true,
..metadata
}
} else {
metadata
};
// Store the metadata.
write_atomic(metadata_entry.path(), rmp_serde::to_vec(&metadata)?)
.await
.map_err(Error::CacheWrite)?;
Ok(ArchiveMetadata {
metadata: Metadata::from_metadata23(metadata),
hashes: revision.into_hashes(),
})
}
/// Return the [`Revision`] for a remote URL, refreshing it if necessary.
async fn url_revision(
&self,
source: &BuildableSource<'_>,
ext: SourceDistExtension,
url: &DisplaySafeUrl,
index: Option<&IndexUrl>,
cache_shard: &CacheShard,
hashes: HashPolicy<'_>,
client: &ManagedClient<'_>,
) -> Result<Revision, Error> {
let cache_entry = cache_shard.entry(HTTP_REVISION);
// Determine the cache control policy for the request.
let cache_control = match client.unmanaged.connectivity() {
Connectivity::Online => {
if let Some(header) = index.and_then(|index| {
self.build_context
.locations()
.artifact_cache_control_for(index)
}) {
CacheControl::Override(header)
} else {
CacheControl::from(
self.build_context
.cache()
.freshness(&cache_entry, source.name(), source.source_tree())
.map_err(Error::CacheRead)?,
)
}
}
Connectivity::Offline => CacheControl::AllowStale,
};
let download = |response| {
async {
// At this point, we're seeing a new or updated source distribution. Initialize a
// new revision, to collect the source and built artifacts.
let revision = Revision::new();
// Download the source distribution.
debug!("Downloading source distribution: {source}");
let entry = cache_shard.shard(revision.id()).entry(SOURCE);
let algorithms = hashes.algorithms();
let hashes = self
.download_archive(response, source, ext, entry.path(), &algorithms)
.await?;
Ok(revision.with_hashes(HashDigests::from(hashes)))
}
.boxed_local()
.instrument(info_span!("download", source_dist = %source))
};
let req = Self::request(url.clone(), client.unmanaged)?;
let revision = client
.managed(|client| {
client.cached_client().get_serde_with_retry(
req,
&cache_entry,
cache_control,
download,
)
})
.await
.map_err(|err| match err {
CachedClientError::Callback { err, .. } => err,
CachedClientError::Client(err) => Error::Client(err),
})?;
// If the archive is missing the required hashes, force a refresh.
if revision.has_digests(hashes) {
Ok(revision)
} else {
client
.managed(async |client| {
client
.cached_client()
.skip_cache_with_retry(
Self::request(url.clone(), client)?,
&cache_entry,
cache_control,
download,
)
.await
.map_err(|err| match err {
CachedClientError::Callback { err, .. } => err,
CachedClientError::Client(err) => Error::Client(err),
})
})
.await
}
}
/// Build a source distribution from a local archive (e.g., `.tar.gz` or `.zip`).
async fn archive(
&self,
source: &BuildableSource<'_>,
resource: &PathSourceUrl<'_>,
cache_shard: &CacheShard,
tags: &Tags,
hashes: HashPolicy<'_>,
) -> Result<BuiltWheelMetadata, Error> {
let _lock = cache_shard.lock().await.map_err(Error::CacheLock)?;
// Fetch the revision for the source distribution.
let LocalRevisionPointer {
cache_info,
revision,
} = self
.archive_revision(source, resource, cache_shard, hashes)
.await?;
// Before running the build, check that the hashes match.
if !revision.satisfies(hashes) {
return Err(Error::hash_mismatch(
source.to_string(),
hashes.digests(),
revision.hashes(),
));
}
// Scope all operations to the revision. Within the revision, there's no need to check for
// freshness, since entries have to be fresher than the revision itself.
| 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/src/source/built_wheel_metadata.rs | crates/uv-distribution/src/source/built_wheel_metadata.rs | use std::path::{Path, PathBuf};
use std::str::FromStr;
use uv_cache::CacheShard;
use uv_cache_info::CacheInfo;
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{BuildInfo, Hashed};
use uv_fs::files;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_platform_tags::Tags;
use uv_pypi_types::{HashDigest, HashDigests};
/// The information about the wheel we either just built or got from the cache.
#[derive(Debug, Clone)]
pub(crate) struct BuiltWheelMetadata {
/// The path to the built wheel.
pub(crate) path: Box<Path>,
/// The expected path to the downloaded wheel's entry in the cache.
pub(crate) target: Box<Path>,
/// The parsed filename.
pub(crate) filename: WheelFilename,
/// The computed hashes of the source distribution from which the wheel was built.
pub(crate) hashes: HashDigests,
/// The cache information for the underlying source distribution.
pub(crate) cache_info: CacheInfo,
/// The build information for the wheel.
pub(crate) build_info: BuildInfo,
}
impl BuiltWheelMetadata {
/// Create a [`BuiltWheelMetadata`] from a [`BuiltWheelFile`].
pub(crate) fn from_file(
file: BuiltWheelFile,
hashes: HashDigests,
cache_info: CacheInfo,
build_info: BuildInfo,
) -> Self {
Self {
path: file.path,
target: file.target,
filename: file.filename,
hashes,
cache_info,
build_info,
}
}
}
impl Hashed for BuiltWheelMetadata {
fn hashes(&self) -> &[HashDigest] {
self.hashes.as_slice()
}
}
/// The path to a built wheel file, along with its parsed filename.
#[derive(Debug, Clone)]
pub(crate) struct BuiltWheelFile {
/// The path to the built wheel.
pub(crate) path: Box<Path>,
/// The expected path to the downloaded wheel's entry in the cache.
pub(crate) target: Box<Path>,
/// The parsed filename.
pub(crate) filename: WheelFilename,
}
impl BuiltWheelFile {
/// Find a compatible wheel in the cache.
pub(crate) fn find_in_cache(
tags: &Tags,
cache_shard: &CacheShard,
) -> Result<Option<Self>, std::io::Error> {
for file in files(cache_shard)? {
if let Some(metadata) = Self::from_path(file, cache_shard) {
// Validate that the wheel is compatible with the target platform.
if metadata.filename.is_compatible(tags) {
return Ok(Some(metadata));
}
}
}
Ok(None)
}
/// Try to parse a distribution from a cached directory name (like `typing-extensions-4.8.0-py3-none-any.whl`).
fn from_path(path: PathBuf, cache_shard: &CacheShard) -> Option<Self> {
let filename = path.file_name()?.to_str()?;
let filename = WheelFilename::from_str(filename).ok()?;
Some(Self {
target: cache_shard.join(filename.stem()).into_boxed_path(),
path: path.into_boxed_path(),
filename,
})
}
/// Returns `true` if the wheel matches the given package name and version.
pub(crate) fn matches(&self, name: Option<&PackageName>, version: Option<&Version>) -> bool {
name.is_none_or(|name| self.filename.name == *name)
&& version.is_none_or(|version| self.filename.version == *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/supported_environments.rs | crates/uv-pypi-types/src/supported_environments.rs | use std::str::FromStr;
use serde::ser::SerializeSeq;
use uv_pep508::MarkerTree;
/// A list of supported marker environments.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct SupportedEnvironments(Vec<MarkerTree>);
impl SupportedEnvironments {
/// Create a new [`SupportedEnvironments`] struct from a list of marker trees.
pub fn from_markers(markers: Vec<MarkerTree>) -> Self {
Self(markers)
}
/// Return the list of marker trees.
pub fn as_markers(&self) -> &[MarkerTree] {
&self.0
}
/// Convert the [`SupportedEnvironments`] struct into a list of marker trees.
pub fn into_markers(self) -> Vec<MarkerTree> {
self.0
}
/// Returns an iterator over the marker trees.
pub fn iter(&self) -> std::slice::Iter<'_, MarkerTree> {
self.0.iter()
}
/// Returns `true` if there are no supported environments.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the number of supported environments.
pub fn len(&self) -> usize {
self.0.len()
}
}
impl<'a> IntoIterator for &'a SupportedEnvironments {
type IntoIter = std::slice::Iter<'a, MarkerTree>;
type Item = &'a MarkerTree;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Serialize a [`SupportedEnvironments`] struct into a list of marker strings.
impl serde::Serialize for SupportedEnvironments {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for element in &self.0 {
if let Some(contents) = element.contents() {
seq.serialize_element(&contents)?;
}
}
seq.end()
}
}
/// Deserialize a marker string or list of marker strings into a [`SupportedEnvironments`] struct.
impl<'de> serde::Deserialize<'de> for SupportedEnvironments {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct StringOrVecVisitor;
impl<'de> serde::de::Visitor<'de> for StringOrVecVisitor {
type Value = SupportedEnvironments;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string or a list of strings")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let marker = MarkerTree::from_str(value).map_err(serde::de::Error::custom)?;
Ok(SupportedEnvironments(vec![marker]))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut markers = Vec::new();
while let Some(elem) = seq.next_element::<String>()? {
let marker = MarkerTree::from_str(&elem).map_err(serde::de::Error::custom)?;
markers.push(marker);
}
Ok(SupportedEnvironments(markers))
}
}
deserializer.deserialize_any(StringOrVecVisitor)
}
}
| 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/lib.rs | crates/uv-pypi-types/src/lib.rs | pub use base_url::*;
pub use conflicts::*;
pub use dependency_groups::*;
pub use direct_url::*;
pub use identifier::*;
pub use lenient_requirement::*;
pub use marker_environment::*;
pub use metadata::*;
pub use parsed_url::*;
pub use scheme::*;
pub use simple_json::*;
pub use supported_environments::*;
mod base_url;
mod conflicts;
mod dependency_groups;
mod direct_url;
mod identifier;
mod lenient_requirement;
mod marker_environment;
mod metadata;
mod parsed_url;
mod scheme;
mod simple_json;
mod supported_environments;
| 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/simple_json.rs | crates/uv-pypi-types/src/simple_json.rs | use std::borrow::Cow;
use std::str::FromStr;
use jiff::Timestamp;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Deserializer, Serialize};
use uv_normalize::{ExtraName, PackageName};
use uv_pep440::{Version, VersionSpecifiers, VersionSpecifiersParseError};
use uv_pep508::Requirement;
use uv_small_str::SmallString;
use crate::VerbatimParsedUrl;
use crate::lenient_requirement::LenientVersionSpecifiers;
/// A collection of "files" from `PyPI`'s JSON API for a single package, as served by the
/// `vnd.pypi.simple.v1` media type.
#[derive(Debug, Clone, Deserialize)]
pub struct PypiSimpleDetail {
/// The list of [`PypiFile`]s available for download sorted by filename.
#[serde(deserialize_with = "sorted_simple_json_files")]
pub files: Vec<PypiFile>,
}
/// Deserializes a sequence of "simple" files from `PyPI` and ensures that they
/// are sorted in a stable order.
fn sorted_simple_json_files<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<PypiFile>, D::Error> {
let mut files = <Vec<PypiFile>>::deserialize(d)?;
// While it has not been positively observed, we sort the files
// to ensure we have a defined ordering. Otherwise, if we rely on
// the API to provide a stable ordering and doesn't, it can lead
// non-deterministic behavior elsewhere. (This is somewhat hand-wavy
// and a bit of a band-aide, since arguably, the order of this API
// response probably shouldn't have an impact on things downstream from
// this. That is, if something depends on ordering, then it should
// probably be the thing that does the sorting.)
files.sort_unstable_by(|f1, f2| f1.filename.cmp(&f2.filename));
Ok(files)
}
/// A single (remote) file belonging to a package, either a wheel or a source distribution, as
/// served by the `vnd.pypi.simple.v1` media type.
///
/// <https://peps.python.org/pep-0691/#project-detail>
#[derive(Debug, Clone)]
pub struct PypiFile {
pub core_metadata: Option<CoreMetadata>,
pub filename: SmallString,
pub hashes: Hashes,
pub requires_python: Option<Result<VersionSpecifiers, VersionSpecifiersParseError>>,
pub size: Option<u64>,
pub upload_time: Option<Timestamp>,
pub url: SmallString,
pub yanked: Option<Box<Yanked>>,
}
impl<'de> Deserialize<'de> for PypiFile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FileVisitor;
impl<'de> serde::de::Visitor<'de> for FileVisitor {
type Value = PypiFile;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a map containing file metadata")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
let mut core_metadata = None;
let mut filename = None;
let mut hashes = None;
let mut requires_python = None;
let mut size = None;
let mut upload_time = None;
let mut url = None;
let mut yanked = None;
while let Some(key) = access.next_key::<&str>()? {
match key {
"core-metadata" | "dist-info-metadata" | "data-dist-info-metadata" => {
if core_metadata.is_none() {
core_metadata = access.next_value()?;
} else {
let _: serde::de::IgnoredAny = access.next_value()?;
}
}
"filename" => filename = Some(access.next_value()?),
"hashes" => hashes = Some(access.next_value()?),
"requires-python" => {
requires_python =
access.next_value::<Option<Cow<'_, str>>>()?.map(|s| {
LenientVersionSpecifiers::from_str(s.as_ref())
.map(VersionSpecifiers::from)
});
}
"size" => size = Some(access.next_value()?),
"upload-time" => upload_time = Some(access.next_value()?),
"url" => url = Some(access.next_value()?),
"yanked" => yanked = Some(access.next_value()?),
_ => {
let _: serde::de::IgnoredAny = access.next_value()?;
}
}
}
Ok(PypiFile {
core_metadata,
filename: filename
.ok_or_else(|| serde::de::Error::missing_field("filename"))?,
hashes: hashes.ok_or_else(|| serde::de::Error::missing_field("hashes"))?,
requires_python,
size,
upload_time,
url: url.ok_or_else(|| serde::de::Error::missing_field("url"))?,
yanked,
})
}
}
deserializer.deserialize_map(FileVisitor)
}
}
/// A collection of "files" from the Simple API.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct PyxSimpleDetail {
/// The list of [`PyxFile`]s available for download sorted by filename.
pub files: Vec<PyxFile>,
/// The core metadata for the project, keyed by version.
#[serde(default)]
pub core_metadata: FxHashMap<Version, CoreMetadatum>,
}
/// A single (remote) file belonging to a package, either a wheel or a source distribution,
/// as served by the Simple API.
#[derive(Debug, Clone)]
pub struct PyxFile {
pub core_metadata: Option<CoreMetadata>,
pub filename: Option<SmallString>,
pub hashes: Hashes,
pub requires_python: Option<Result<VersionSpecifiers, VersionSpecifiersParseError>>,
pub size: Option<u64>,
pub upload_time: Option<Timestamp>,
pub url: SmallString,
pub yanked: Option<Box<Yanked>>,
pub zstd: Option<Zstd>,
}
impl<'de> Deserialize<'de> for PyxFile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FileVisitor;
impl<'de> serde::de::Visitor<'de> for FileVisitor {
type Value = PyxFile;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a map containing file metadata")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
let mut core_metadata = None;
let mut filename = None;
let mut hashes = None;
let mut requires_python = None;
let mut size = None;
let mut upload_time = None;
let mut url = None;
let mut yanked = None;
let mut zstd = None;
while let Some(key) = access.next_key::<&str>()? {
match key {
"core-metadata" | "dist-info-metadata" | "data-dist-info-metadata" => {
if core_metadata.is_none() {
core_metadata = access.next_value()?;
} else {
let _: serde::de::IgnoredAny = access.next_value()?;
}
}
"filename" => filename = Some(access.next_value()?),
"hashes" => hashes = Some(access.next_value()?),
"requires-python" => {
requires_python =
access.next_value::<Option<Cow<'_, str>>>()?.map(|s| {
LenientVersionSpecifiers::from_str(s.as_ref())
.map(VersionSpecifiers::from)
});
}
"size" => size = Some(access.next_value()?),
"upload-time" => upload_time = Some(access.next_value()?),
"url" => url = Some(access.next_value()?),
"yanked" => yanked = Some(access.next_value()?),
"zstd" => {
zstd = Some(access.next_value()?);
}
_ => {
let _: serde::de::IgnoredAny = access.next_value()?;
}
}
}
Ok(PyxFile {
core_metadata,
filename,
hashes: hashes.ok_or_else(|| serde::de::Error::missing_field("hashes"))?,
requires_python,
size,
upload_time,
url: url.ok_or_else(|| serde::de::Error::missing_field("url"))?,
yanked,
zstd,
})
}
}
deserializer.deserialize_map(FileVisitor)
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct CoreMetadatum {
#[serde(default)]
pub requires_python: Option<VersionSpecifiers>,
#[serde(default)]
pub requires_dist: Box<[Requirement<VerbatimParsedUrl>]>,
#[serde(default, alias = "provides-extras")]
pub provides_extra: Box<[ExtraName]>,
}
#[derive(Debug, Clone)]
pub enum CoreMetadata {
Bool(bool),
Hashes(Hashes),
}
impl<'de> Deserialize<'de> for CoreMetadata {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
serde_untagged::UntaggedEnumVisitor::new()
.bool(|bool| Ok(Self::Bool(bool)))
.map(|map| map.deserialize().map(CoreMetadata::Hashes))
.deserialize(deserializer)
}
}
impl Serialize for CoreMetadata {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::Bool(is_available) => serializer.serialize_bool(*is_available),
Self::Hashes(hashes) => hashes.serialize(serializer),
}
}
}
impl CoreMetadata {
pub fn is_available(&self) -> bool {
match self {
Self::Bool(is_available) => *is_available,
Self::Hashes(_) => true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)]
#[rkyv(derive(Debug))]
pub enum Yanked {
Bool(bool),
Reason(SmallString),
}
impl<'de> Deserialize<'de> for Yanked {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
serde_untagged::UntaggedEnumVisitor::new()
.bool(|bool| Ok(Self::Bool(bool)))
.string(|string| Ok(Self::Reason(SmallString::from(string))))
.deserialize(deserializer)
}
}
impl Serialize for Yanked {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::Bool(is_yanked) => serializer.serialize_bool(*is_yanked),
Self::Reason(reason) => serializer.serialize_str(reason.as_ref()),
}
}
}
impl Yanked {
pub fn is_yanked(&self) -> bool {
match self {
Self::Bool(is_yanked) => *is_yanked,
Self::Reason(_) => true,
}
}
}
impl Default for Yanked {
fn default() -> Self {
Self::Bool(false)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)]
pub struct Zstd {
pub hashes: Hashes,
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
}
/// A dictionary mapping a hash name to a hex encoded digest of the file.
///
/// PEP 691 says multiple hashes can be included and the interpretation is left to the client.
#[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)]
pub struct Hashes {
#[serde(skip_serializing_if = "Option::is_none")]
pub md5: Option<SmallString>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sha256: Option<SmallString>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sha384: Option<SmallString>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sha512: Option<SmallString>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blake2b: Option<SmallString>,
}
impl Hashes {
/// Parse the hash from a fragment, as in: `sha256=6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61`
pub fn parse_fragment(fragment: &str) -> Result<Self, HashError> {
let mut parts = fragment.split('=');
// Extract the key and value.
let name = parts
.next()
.ok_or_else(|| HashError::InvalidFragment(fragment.to_string()))?;
let value = parts
.next()
.ok_or_else(|| HashError::InvalidFragment(fragment.to_string()))?;
// Ensure there are no more parts.
if parts.next().is_some() {
return Err(HashError::InvalidFragment(fragment.to_string()));
}
match name {
"md5" => Ok(Self {
md5: Some(SmallString::from(value)),
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
}),
"sha256" => Ok(Self {
md5: None,
sha256: Some(SmallString::from(value)),
sha384: None,
sha512: None,
blake2b: None,
}),
"sha384" => Ok(Self {
md5: None,
sha256: None,
sha384: Some(SmallString::from(value)),
sha512: None,
blake2b: None,
}),
"sha512" => Ok(Self {
md5: None,
sha256: None,
sha384: None,
sha512: Some(SmallString::from(value)),
blake2b: None,
}),
"blake2b" => Ok(Self {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: Some(SmallString::from(value)),
}),
_ => Err(HashError::UnsupportedHashAlgorithm(fragment.to_string())),
}
}
}
impl FromStr for Hashes {
type Err = HashError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split(':');
// Extract the key and value.
let name = parts
.next()
.ok_or_else(|| HashError::InvalidStructure(s.to_string()))?;
let value = parts
.next()
.ok_or_else(|| HashError::InvalidStructure(s.to_string()))?;
// Ensure there are no more parts.
if parts.next().is_some() {
return Err(HashError::InvalidStructure(s.to_string()));
}
match name {
"md5" => Ok(Self {
md5: Some(SmallString::from(value)),
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
}),
"sha256" => Ok(Self {
md5: None,
sha256: Some(SmallString::from(value)),
sha384: None,
sha512: None,
blake2b: None,
}),
"sha384" => Ok(Self {
md5: None,
sha256: None,
sha384: Some(SmallString::from(value)),
sha512: None,
blake2b: None,
}),
"sha512" => Ok(Self {
md5: None,
sha256: None,
sha384: None,
sha512: Some(SmallString::from(value)),
blake2b: None,
}),
"blake2b" => Ok(Self {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: Some(SmallString::from(value)),
}),
_ => Err(HashError::UnsupportedHashAlgorithm(s.to_string())),
}
}
}
#[derive(
Debug,
Clone,
Copy,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Serialize,
Deserialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub enum HashAlgorithm {
Md5,
Sha256,
Sha384,
Sha512,
Blake2b,
}
impl FromStr for HashAlgorithm {
type Err = HashError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"md5" => Ok(Self::Md5),
"sha256" => Ok(Self::Sha256),
"sha384" => Ok(Self::Sha384),
"sha512" => Ok(Self::Sha512),
"blake2b" => Ok(Self::Blake2b),
_ => Err(HashError::UnsupportedHashAlgorithm(s.to_string())),
}
}
}
impl std::fmt::Display for HashAlgorithm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Md5 => write!(f, "md5"),
Self::Sha256 => write!(f, "sha256"),
Self::Sha384 => write!(f, "sha384"),
Self::Sha512 => write!(f, "sha512"),
Self::Blake2b => write!(f, "blake2b"),
}
}
}
/// A hash name and hex encoded digest of the file.
#[derive(
Debug,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Serialize,
Deserialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub struct HashDigest {
pub algorithm: HashAlgorithm,
pub digest: SmallString,
}
impl HashDigest {
/// Return the [`HashAlgorithm`] of the digest.
pub fn algorithm(&self) -> HashAlgorithm {
self.algorithm
}
}
impl std::fmt::Display for HashDigest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.algorithm, self.digest)
}
}
impl FromStr for HashDigest {
type Err = HashError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split(':');
// Extract the key and value.
let name = parts
.next()
.ok_or_else(|| HashError::InvalidStructure(s.to_string()))?;
let value = parts
.next()
.ok_or_else(|| HashError::InvalidStructure(s.to_string()))?;
// Ensure there are no more parts.
if parts.next().is_some() {
return Err(HashError::InvalidStructure(s.to_string()));
}
let algorithm = HashAlgorithm::from_str(name)?;
let digest = SmallString::from(value);
Ok(Self { algorithm, digest })
}
}
/// A collection of [`HashDigest`] entities.
#[derive(
Debug,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Serialize,
Deserialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub struct HashDigests(Box<[HashDigest]>);
impl HashDigests {
/// Initialize an empty collection of [`HashDigest`] entities.
pub fn empty() -> Self {
Self(Box::new([]))
}
/// Return the [`HashDigest`] entities as a slice.
pub fn as_slice(&self) -> &[HashDigest] {
self.0.as_ref()
}
/// Returns `true` if the [`HashDigests`] are empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the first [`HashDigest`] entity.
pub fn first(&self) -> Option<&HashDigest> {
self.0.first()
}
/// Return the [`HashDigest`] entities as a vector.
pub fn to_vec(&self) -> Vec<HashDigest> {
self.0.to_vec()
}
/// Returns an [`Iterator`] over the [`HashDigest`] entities.
pub fn iter(&self) -> impl Iterator<Item = &HashDigest> {
self.0.iter()
}
/// Sort the underlying [`HashDigest`] entities.
pub fn sort_unstable(&mut self) {
self.0.sort_unstable();
}
}
/// Convert a set of [`Hashes`] into a list of [`HashDigest`]s.
impl From<Hashes> for HashDigests {
fn from(value: Hashes) -> Self {
let mut digests = Vec::with_capacity(
usize::from(value.sha512.is_some())
+ usize::from(value.sha384.is_some())
+ usize::from(value.sha256.is_some())
+ usize::from(value.md5.is_some()),
);
if let Some(sha512) = value.sha512 {
digests.push(HashDigest {
algorithm: HashAlgorithm::Sha512,
digest: sha512,
});
}
if let Some(sha384) = value.sha384 {
digests.push(HashDigest {
algorithm: HashAlgorithm::Sha384,
digest: sha384,
});
}
if let Some(sha256) = value.sha256 {
digests.push(HashDigest {
algorithm: HashAlgorithm::Sha256,
digest: sha256,
});
}
if let Some(md5) = value.md5 {
digests.push(HashDigest {
algorithm: HashAlgorithm::Md5,
digest: md5,
});
}
Self::from(digests)
}
}
impl From<HashDigests> for Hashes {
fn from(value: HashDigests) -> Self {
let mut hashes = Self::default();
for digest in value {
match digest.algorithm() {
HashAlgorithm::Md5 => hashes.md5 = Some(digest.digest),
HashAlgorithm::Sha256 => hashes.sha256 = Some(digest.digest),
HashAlgorithm::Sha384 => hashes.sha384 = Some(digest.digest),
HashAlgorithm::Sha512 => hashes.sha512 = Some(digest.digest),
HashAlgorithm::Blake2b => hashes.blake2b = Some(digest.digest),
}
}
hashes
}
}
impl From<HashDigest> for HashDigests {
fn from(value: HashDigest) -> Self {
Self(Box::new([value]))
}
}
impl From<&[HashDigest]> for HashDigests {
fn from(value: &[HashDigest]) -> Self {
Self(Box::from(value))
}
}
impl From<Vec<HashDigest>> for HashDigests {
fn from(value: Vec<HashDigest>) -> Self {
Self(value.into_boxed_slice())
}
}
impl FromIterator<HashDigest> for HashDigests {
fn from_iter<T: IntoIterator<Item = HashDigest>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl IntoIterator for HashDigests {
type Item = HashDigest;
type IntoIter = std::vec::IntoIter<HashDigest>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_vec().into_iter()
}
}
#[derive(thiserror::Error, Debug)]
pub enum HashError {
#[error("Unexpected hash (expected `<algorithm>:<hash>`): {0}")]
InvalidStructure(String),
#[error("Unexpected fragment (expected `#sha256=...` or similar) on URL: {0}")]
InvalidFragment(String),
#[error(
"Unsupported hash algorithm (expected one of: `md5`, `sha256`, `sha384`, `sha512`, or `blake2b`) on: `{0}`"
)]
UnsupportedHashAlgorithm(String),
}
#[cfg(test)]
mod tests {
use crate::{HashError, Hashes};
#[test]
fn parse_hashes() -> Result<(), HashError> {
let hashes: Hashes =
"blake2b:af4793213ee66ef8fae3b93b3e29206f6b251e65c97bd91d8e1c5596ef15af0a".parse()?;
assert_eq!(
hashes,
Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: Some(
"af4793213ee66ef8fae3b93b3e29206f6b251e65c97bd91d8e1c5596ef15af0a".into()
),
}
);
let hashes: Hashes =
"sha512:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".parse()?;
assert_eq!(
hashes,
Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: Some(
"40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".into()
),
blake2b: None,
}
);
let hashes: Hashes =
"sha384:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".parse()?;
assert_eq!(
hashes,
Hashes {
md5: None,
sha256: None,
sha384: Some(
"40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".into()
),
sha512: None,
blake2b: None,
}
);
let hashes: Hashes =
"sha256:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".parse()?;
assert_eq!(
hashes,
Hashes {
md5: None,
sha256: Some(
"40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f".into()
),
sha384: None,
sha512: None,
blake2b: None,
}
);
let hashes: Hashes =
"md5:090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2".parse()?;
assert_eq!(
hashes,
Hashes {
md5: Some(
"090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2".into()
),
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
}
);
let result = "sha256=40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f"
.parse::<Hashes>();
assert!(result.is_err());
let result = "blake2:55f44b440d491028addb3b88f72207d71eeebfb7b5dbf0643f7c023ae1fba619"
.parse::<Hashes>();
assert!(result.is_err());
Ok(())
}
}
/// Response from the Simple API root endpoint (index) listing all available projects,
/// as served by the `vnd.pypi.simple.v1` media type.
///
/// <https://peps.python.org/pep-0691/#specification>
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct PypiSimpleIndex {
/// Metadata about the response.
pub meta: SimpleIndexMeta,
/// The list of projects available in the index.
pub projects: Vec<ProjectEntry>,
}
/// Response from the Pyx Simple API root endpoint listing all available projects,
/// as served by the `vnd.pyx.simple.v1` media types.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct PyxSimpleIndex {
/// Metadata about the response.
pub meta: SimpleIndexMeta,
/// The list of projects available in the index.
pub projects: Vec<ProjectEntry>,
}
/// Metadata about a Simple API index response.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SimpleIndexMeta {
/// The API version.
pub api_version: SmallString,
}
/// A single project entry in the Simple API index.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ProjectEntry {
/// The name of the project.
pub name: PackageName,
}
| 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/lenient_requirement.rs | crates/uv-pypi-types/src/lenient_requirement.rs | use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, de};
use std::borrow::Cow;
use std::str::FromStr;
use std::sync::LazyLock;
use tracing::warn;
use uv_pep440::{VersionSpecifiers, VersionSpecifiersParseError};
use uv_pep508::{Pep508Error, Pep508Url, Requirement};
use crate::VerbatimParsedUrl;
/// Ex) `>=7.2.0<8.0.0`
static MISSING_COMMA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d)([<>=~^!])").unwrap());
/// Ex) `!=~5.0`
static NOT_EQUAL_TILDE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"!=~((?:\d\.)*\d)").unwrap());
/// Ex) `>=1.9.*`, `<3.4.*`
static INVALID_TRAILING_DOT_STAR: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(<=|>=|<|>)(\d+(\.\d+)*)\.\*").unwrap());
/// Ex) `!=3.0*`
static MISSING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d\.\d)+\*").unwrap());
/// Ex) `>=3.6,`
static TRAILING_COMMA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r",\s*$").unwrap());
/// Ex) `>dev`
static GREATER_THAN_DEV: LazyLock<Regex> = LazyLock::new(|| Regex::new(r">dev").unwrap());
/// Ex) `>=9.0.0a1.0`
static TRAILING_ZERO: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\d+(\.\d)*(a|b|rc|post|dev)\d+)\.0").unwrap());
// Search and replace functions that fix invalid specifiers.
type FixUp = for<'a> fn(&'a str) -> Cow<'a, str>;
/// A list of fixups with a corresponding message about what was fixed.
static FIXUPS: &[(FixUp, &str)] = &[
// Given `>=7.2.0<8.0.0`, rewrite to `>=7.2.0,<8.0.0`.
(
|input| MISSING_COMMA.replace_all(input, r"$1,$2"),
"inserting missing comma",
),
// Given `!=~5.0,>=4.12`, rewrite to `!=5.0.*,>=4.12`.
(
|input| NOT_EQUAL_TILDE.replace_all(input, r"!=${1}.*"),
"replacing invalid tilde with wildcard",
),
// Given `>=1.9.*`, rewrite to `>=1.9`.
(
|input| INVALID_TRAILING_DOT_STAR.replace_all(input, r"${1}${2}"),
"removing star after comparison operator other than equal and not equal",
),
// Given `!=3.0*`, rewrite to `!=3.0.*`.
(
|input| MISSING_DOT.replace_all(input, r"${1}.*"),
"inserting missing dot",
),
// Given `>=3.6,`, rewrite to `>=3.6`
(
|input| TRAILING_COMMA.replace_all(input, r"${1}"),
"removing trailing comma",
),
// Given `>dev`, rewrite to `>0.0.0dev`
(
|input| GREATER_THAN_DEV.replace_all(input, r">0.0.0dev"),
"assuming 0.0.0dev",
),
// Given `>=9.0.0a1.0`, rewrite to `>=9.0.0a1`
(
|input| TRAILING_ZERO.replace_all(input, r"${1}"),
"removing trailing zero",
),
(remove_stray_quotes, "removing stray quotes"),
];
// Given `>= 2.7'`, rewrite to `>= 2.7`
fn remove_stray_quotes(input: &str) -> Cow<'_, str> {
/// Ex) `'>= 2.7'`, `>=3.6'`
static STRAY_QUOTES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"['"]"#).unwrap());
// make sure not to touch markers, which can have quotes (e.g. `python_version >= '3.7'`)
match input.find(';') {
Some(markers) => {
let requirement = STRAY_QUOTES.replace_all(&input[..markers], "");
format!("{}{}", requirement, &input[markers..]).into()
}
None => STRAY_QUOTES.replace_all(input, ""),
}
}
fn parse_with_fixups<Err, T: FromStr<Err = Err>>(input: &str, type_name: &str) -> Result<T, Err> {
match T::from_str(input) {
Ok(requirement) => Ok(requirement),
Err(err) => {
let mut patched_input = input.to_string();
let mut messages = Vec::new();
for (fixup, message) in FIXUPS {
let patched = fixup(patched_input.as_ref());
if patched != patched_input {
messages.push(*message);
if let Ok(requirement) = T::from_str(&patched) {
warn!(
"Fixing invalid {type_name} by {} (before: `{input}`; after: `{patched}`)",
messages.join(", ")
);
return Ok(requirement);
}
patched_input = patched.to_string();
}
}
Err(err)
}
}
}
/// Like [`Requirement`], but attempts to correct some common errors in user-provided requirements.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct LenientRequirement<T: Pep508Url = VerbatimParsedUrl>(Requirement<T>);
impl<T: Pep508Url> FromStr for LenientRequirement<T> {
type Err = Pep508Error<T>;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Ok(Self(parse_with_fixups(input, "requirement")?))
}
}
impl<T: Pep508Url> From<LenientRequirement<T>> for Requirement<T> {
fn from(requirement: LenientRequirement<T>) -> Self {
requirement.0
}
}
/// Like [`VersionSpecifiers`], but attempts to correct some common errors in user-provided requirements.
///
/// For example, we turn `>=3.x.*` into `>=3.x`.
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct LenientVersionSpecifiers(VersionSpecifiers);
impl FromStr for LenientVersionSpecifiers {
type Err = VersionSpecifiersParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Ok(Self(parse_with_fixups(input, "version specifier")?))
}
}
impl From<LenientVersionSpecifiers> for VersionSpecifiers {
fn from(specifiers: LenientVersionSpecifiers) -> Self {
specifiers.0
}
}
impl<'de> Deserialize<'de> for LenientVersionSpecifiers {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = LenientVersionSpecifiers;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
LenientVersionSpecifiers::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use uv_pep440::VersionSpecifiers;
use uv_pep508::Requirement;
use crate::LenientVersionSpecifiers;
use super::LenientRequirement;
#[test]
fn requirement_missing_comma() {
let actual: Requirement = LenientRequirement::from_str("elasticsearch-dsl (>=7.2.0<8.0.0)")
.unwrap()
.into();
let expected: Requirement =
Requirement::from_str("elasticsearch-dsl (>=7.2.0,<8.0.0)").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn requirement_not_equal_tile() {
let actual: Requirement = LenientRequirement::from_str("jupyter-core (!=~5.0,>=4.12)")
.unwrap()
.into();
let expected: Requirement = Requirement::from_str("jupyter-core (!=5.0.*,>=4.12)").unwrap();
assert_eq!(actual, expected);
let actual: Requirement = LenientRequirement::from_str("jupyter-core (!=~5,>=4.12)")
.unwrap()
.into();
let expected: Requirement = Requirement::from_str("jupyter-core (!=5.*,>=4.12)").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn requirement_greater_than_star() {
let actual: Requirement = LenientRequirement::from_str("torch (>=1.9.*)")
.unwrap()
.into();
let expected: Requirement = Requirement::from_str("torch (>=1.9)").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn requirement_missing_dot() {
let actual: Requirement =
LenientRequirement::from_str("pyzmq (>=2.7,!=3.0*,!=3.1*,!=3.2*)")
.unwrap()
.into();
let expected: Requirement =
Requirement::from_str("pyzmq (>=2.7,!=3.0.*,!=3.1.*,!=3.2.*)").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn requirement_trailing_comma() {
let actual: Requirement = LenientRequirement::from_str("pyzmq >=3.6,").unwrap().into();
let expected: Requirement = Requirement::from_str("pyzmq >=3.6").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_missing_comma() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=7.2.0<8.0.0")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=7.2.0,<8.0.0").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_not_equal_tile() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str("!=~5.0,>=4.12")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str("!=5.0.*,>=4.12").unwrap();
assert_eq!(actual, expected);
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str("!=~5,>=4.12")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str("!=5.*,>=4.12").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_greater_than_star() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=1.9.*")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=1.9").unwrap();
assert_eq!(actual, expected);
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=1.*").unwrap().into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=1").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_missing_dot() {
let actual: VersionSpecifiers =
LenientVersionSpecifiers::from_str(">=2.7,!=3.0*,!=3.1*,!=3.2*")
.unwrap()
.into();
let expected: VersionSpecifiers =
VersionSpecifiers::from_str(">=2.7,!=3.0.*,!=3.1.*,!=3.2.*").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_trailing_comma() {
let actual: VersionSpecifiers =
LenientVersionSpecifiers::from_str(">=3.6,").unwrap().into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=3.6").unwrap();
assert_eq!(actual, expected);
}
#[test]
fn specifier_trailing_comma_trailing_space() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=3.6, ")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=3.6").unwrap();
assert_eq!(actual, expected);
}
/// <https://pypi.org/simple/shellingham/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn specifier_invalid_single_quotes() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">= '2.7'")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">= 2.7").unwrap();
assert_eq!(actual, expected);
}
/// <https://pypi.org/simple/tensorflowonspark/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn specifier_invalid_double_quotes() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=\"3.6\"")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=3.6").unwrap();
assert_eq!(actual, expected);
}
/// <https://pypi.org/simple/celery/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn specifier_multi_fix() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(
">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*,",
)
.unwrap()
.into();
let expected: VersionSpecifiers =
VersionSpecifiers::from_str(">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*")
.unwrap();
assert_eq!(actual, expected);
}
/// <https://pypi.org/simple/wincertstore/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn smaller_than_star() {
let actual: VersionSpecifiers =
LenientVersionSpecifiers::from_str(">=2.7,!=3.0.*,!=3.1.*,<3.4.*")
.unwrap()
.into();
let expected: VersionSpecifiers =
VersionSpecifiers::from_str(">=2.7,!=3.0.*,!=3.1.*,<3.4").unwrap();
assert_eq!(actual, expected);
}
/// <https://pypi.org/simple/algoliasearch/?format=application/vnd.pypi.simple.v1+json>
/// <https://pypi.org/simple/okta/?format=application/vnd.pypi.simple.v1+json>
#[test]
fn stray_quote() {
let actual: VersionSpecifiers =
LenientVersionSpecifiers::from_str(">=2.7, !=3.0.*, !=3.1.*', !=3.2.*, !=3.3.*'")
.unwrap()
.into();
let expected: VersionSpecifiers =
VersionSpecifiers::from_str(">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*").unwrap();
assert_eq!(actual, expected);
let actual: VersionSpecifiers =
LenientVersionSpecifiers::from_str(">=3.6'").unwrap().into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=3.6").unwrap();
assert_eq!(actual, expected);
}
/// <https://files.pythonhosted.org/packages/74/49/7349527cea7f708e7d3253ab6b32c9b5bdf84a57dde8fc265a33e6a4e662/boto3-1.2.0-py2.py3-none-any.whl>
#[test]
fn trailing_comma_after_quote() {
let actual: Requirement = LenientRequirement::from_str("botocore>=1.3.0,<1.4.0',")
.unwrap()
.into();
let expected: Requirement = Requirement::from_str("botocore>=1.3.0,<1.4.0").unwrap();
assert_eq!(actual, expected);
}
/// <https://github.com/celery/celery/blob/6215f34d2675441ef2177bd850bf5f4b442e944c/requirements/default.txt#L1>
#[test]
fn greater_than_dev() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">dev").unwrap().into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">0.0.0dev").unwrap();
assert_eq!(actual, expected);
}
/// <https://github.com/astral-sh/uv/issues/1798>
#[test]
fn trailing_alpha_zero() {
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=9.0.0a1.0")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=9.0.0a1").unwrap();
assert_eq!(actual, expected);
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=9.0a1.0")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=9.0a1").unwrap();
assert_eq!(actual, expected);
let actual: VersionSpecifiers = LenientVersionSpecifiers::from_str(">=9a1.0")
.unwrap()
.into();
let expected: VersionSpecifiers = VersionSpecifiers::from_str(">=9a1").unwrap();
assert_eq!(actual, expected);
}
/// <https://github.com/astral-sh/uv/issues/2551>
#[test]
fn stray_quote_preserve_marker() {
let actual: Requirement =
LenientRequirement::from_str("numpy >=1.19; python_version >= \"3.7\"")
.unwrap()
.into();
let expected: Requirement =
Requirement::from_str("numpy >=1.19; python_version >= \"3.7\"").unwrap();
assert_eq!(actual, expected);
let actual: Requirement =
LenientRequirement::from_str("numpy \">=1.19\"; python_version >= \"3.7\"")
.unwrap()
.into();
let expected: Requirement =
Requirement::from_str("numpy >=1.19; python_version >= \"3.7\"").unwrap();
assert_eq!(actual, expected);
let actual: Requirement =
LenientRequirement::from_str("'numpy' >=1.19\"; python_version >= \"3.7\"")
.unwrap()
.into();
let expected: Requirement =
Requirement::from_str("numpy >=1.19; python_version >= \"3.7\"").unwrap();
assert_eq!(actual, 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-pypi-types/src/parsed_url.rs | crates/uv-pypi-types/src/parsed_url.rs | use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
use thiserror::Error;
use url::Url;
use uv_cache_key::{CacheKey, CacheKeyHasher};
use uv_distribution_filename::{DistExtension, ExtensionError};
use uv_git_types::{GitUrl, GitUrlParseError};
use uv_pep508::{
Pep508Url, UnnamedRequirementUrl, VerbatimUrl, VerbatimUrlError, looks_like_git_repository,
};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
use crate::{ArchiveInfo, DirInfo, DirectUrl, VcsInfo, VcsKind};
#[derive(Debug, Error)]
pub enum ParsedUrlError {
#[error("Unsupported URL prefix `{prefix}` in URL: `{url}` ({message})")]
UnsupportedUrlPrefix {
prefix: String,
url: String,
message: &'static str,
},
#[error("Invalid path in file URL: `{0}`")]
InvalidFileUrl(String),
#[error(transparent)]
GitUrlParse(#[from] GitUrlParseError),
#[error("Not a valid URL: `{0}`")]
UrlParse(String, #[source] DisplaySafeUrlError),
#[error(transparent)]
VerbatimUrl(#[from] VerbatimUrlError),
#[error(
"Direct URL (`{0}`) references a Git repository, but is missing the `git+` prefix (e.g., `git+{0}`)"
)]
MissingGitPrefix(String),
#[error("Expected direct URL (`{0}`) to end in a supported file extension: {1}")]
MissingExtensionUrl(String, ExtensionError),
#[error("Expected path (`{0}`) to end in a supported file extension: {1}")]
MissingExtensionPath(PathBuf, ExtensionError),
}
#[derive(Debug, Clone, Hash, PartialEq, PartialOrd, Eq, Ord)]
pub struct VerbatimParsedUrl {
pub parsed_url: ParsedUrl,
pub verbatim: VerbatimUrl,
}
impl CacheKey for VerbatimParsedUrl {
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.verbatim.cache_key(state);
}
}
impl VerbatimParsedUrl {
/// Returns `true` if the URL is editable.
pub fn is_editable(&self) -> bool {
self.parsed_url.is_editable()
}
}
impl Pep508Url for VerbatimParsedUrl {
type Err = ParsedUrlError;
fn parse_url(url: &str, working_dir: Option<&Path>) -> Result<Self, Self::Err> {
let verbatim = <VerbatimUrl as Pep508Url>::parse_url(url, working_dir)?;
Ok(Self {
parsed_url: ParsedUrl::try_from(verbatim.to_url())?,
verbatim,
})
}
fn displayable_with_credentials(&self) -> impl Display {
self.verbatim.displayable_with_credentials()
}
}
impl UnnamedRequirementUrl for VerbatimParsedUrl {
fn parse_path(
path: impl AsRef<Path>,
working_dir: impl AsRef<Path>,
) -> Result<Self, Self::Err> {
let verbatim = VerbatimUrl::from_path(&path, &working_dir)?;
let verbatim_path = verbatim.as_path()?;
let is_dir = if let Ok(metadata) = verbatim_path.metadata() {
metadata.is_dir()
} else {
verbatim_path.extension().is_none()
};
let url = verbatim.to_url();
let install_path = verbatim.as_path()?.into_boxed_path();
let parsed_url = if is_dir {
ParsedUrl::Directory(ParsedDirectoryUrl {
url,
install_path,
editable: None,
r#virtual: None,
})
} else {
ParsedUrl::Path(ParsedPathUrl {
url,
install_path,
ext: DistExtension::from_path(&path).map_err(|err| {
ParsedUrlError::MissingExtensionPath(path.as_ref().to_path_buf(), err)
})?,
})
};
Ok(Self {
parsed_url,
verbatim,
})
}
fn parse_absolute_path(path: impl AsRef<Path>) -> Result<Self, Self::Err> {
let verbatim = VerbatimUrl::from_absolute_path(&path)?;
let verbatim_path = verbatim.as_path()?;
let is_dir = if let Ok(metadata) = verbatim_path.metadata() {
metadata.is_dir()
} else {
verbatim_path.extension().is_none()
};
let url = verbatim.to_url();
let install_path = verbatim.as_path()?.into_boxed_path();
let parsed_url = if is_dir {
ParsedUrl::Directory(ParsedDirectoryUrl {
url,
install_path,
editable: None,
r#virtual: None,
})
} else {
ParsedUrl::Path(ParsedPathUrl {
url,
install_path,
ext: DistExtension::from_path(&path).map_err(|err| {
ParsedUrlError::MissingExtensionPath(path.as_ref().to_path_buf(), err)
})?,
})
};
Ok(Self {
parsed_url,
verbatim,
})
}
fn parse_unnamed_url(url: impl AsRef<str>) -> Result<Self, Self::Err> {
let verbatim = <VerbatimUrl as UnnamedRequirementUrl>::parse_unnamed_url(&url)?;
Ok(Self {
parsed_url: ParsedUrl::try_from(verbatim.to_url())?,
verbatim,
})
}
fn with_given(self, given: impl AsRef<str>) -> Self {
Self {
verbatim: self.verbatim.with_given(given),
..self
}
}
fn given(&self) -> Option<&str> {
self.verbatim.given()
}
}
impl Display for VerbatimParsedUrl {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.verbatim, f)
}
}
/// We support three types of URLs for distributions:
/// * The path to a file or directory (`file://`)
/// * A Git repository (`git+https://` or `git+ssh://`), optionally with a subdirectory and/or
/// string to checkout.
/// * A remote archive (`https://`), optional with a subdirectory (source dist only).
///
/// A URL in a requirement `foo @ <url>` must be one of the above.
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash, Ord)]
pub enum ParsedUrl {
/// The direct URL is a path to a local file.
Path(ParsedPathUrl),
/// The direct URL is a path to a local directory.
Directory(ParsedDirectoryUrl),
/// The direct URL is path to a Git repository.
Git(ParsedGitUrl),
/// The direct URL is a URL to a source archive (e.g., a `.tar.gz` file) or built archive
/// (i.e., a `.whl` file).
Archive(ParsedArchiveUrl),
}
impl ParsedUrl {
/// Returns `true` if the URL is editable.
pub fn is_editable(&self) -> bool {
matches!(
self,
Self::Directory(ParsedDirectoryUrl {
editable: Some(true),
..
})
)
}
}
/// A local path URL for a file (i.e., a built or source distribution).
///
/// Examples:
/// * `file:///home/ferris/my_project/my_project-0.1.0.tar.gz`
/// * `file:///home/ferris/my_project/my_project-0.1.0-py3-none-any.whl`
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash, Ord)]
pub struct ParsedPathUrl {
pub url: DisplaySafeUrl,
/// 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: DistExtension,
}
impl ParsedPathUrl {
/// Construct a [`ParsedPathUrl`] from a path requirement source.
pub fn from_source(install_path: Box<Path>, ext: DistExtension, url: DisplaySafeUrl) -> Self {
Self {
url,
install_path,
ext,
}
}
}
/// A local path URL for a source directory.
///
/// Examples:
/// * `file:///home/ferris/my_project`
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash, Ord)]
pub struct ParsedDirectoryUrl {
pub url: DisplaySafeUrl,
/// The absolute path to the distribution which we use for installing.
pub install_path: Box<Path>,
/// Whether the project at the given URL should be installed in editable mode.
pub editable: Option<bool>,
/// Whether the project at the given URL should be treated as a virtual package.
pub r#virtual: Option<bool>,
}
impl ParsedDirectoryUrl {
/// Construct a [`ParsedDirectoryUrl`] from a path requirement source.
pub fn from_source(
install_path: Box<Path>,
editable: Option<bool>,
r#virtual: Option<bool>,
url: DisplaySafeUrl,
) -> Self {
Self {
url,
install_path,
editable,
r#virtual,
}
}
}
/// A Git repository URL.
///
/// Explicit `lfs = true` or `--lfs` should be used to enable Git LFS support as
/// we do not support implicit parsing of the `lfs=true` url fragments for now.
///
/// Examples:
/// * `git+https://git.example.com/MyProject.git`
/// * `git+https://git.example.com/MyProject.git@v1.0#egg=pkg&subdirectory=pkg_dir`
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash, Ord)]
pub struct ParsedGitUrl {
pub url: GitUrl,
pub subdirectory: Option<Box<Path>>,
}
impl ParsedGitUrl {
/// Construct a [`ParsedGitUrl`] from a Git requirement source.
pub fn from_source(url: GitUrl, subdirectory: Option<Box<Path>>) -> Self {
Self { url, subdirectory }
}
}
impl TryFrom<DisplaySafeUrl> for ParsedGitUrl {
type Error = ParsedUrlError;
/// Supports URLs with and without the `git+` prefix.
///
/// When the URL includes a prefix, it's presumed to come from a PEP 508 requirement; when it's
/// excluded, it's presumed to come from `tool.uv.sources`.
fn try_from(url_in: DisplaySafeUrl) -> Result<Self, Self::Error> {
let subdirectory = get_subdirectory(&url_in).map(PathBuf::into_boxed_path);
let url = url_in
.as_str()
.strip_prefix("git+")
.unwrap_or(url_in.as_str());
let url = DisplaySafeUrl::parse(url)
.map_err(|err| ParsedUrlError::UrlParse(url.to_string(), err))?;
let url = GitUrl::try_from(url)?;
Ok(Self { url, subdirectory })
}
}
/// A URL to a source or built archive.
///
/// Examples:
/// * A built distribution: `https://files.pythonhosted.org/packages/62/06/d5604a70d160f6a6ca5fd2ba25597c24abd5c5ca5f437263d177ac242308/tqdm-4.66.1-py2.py3-none-any.whl`
/// * A source distribution with a valid name: `https://files.pythonhosted.org/packages/62/06/d5604a70d160f6a6ca5fd2ba25597c24abd5c5ca5f437263d177ac242308/tqdm-4.66.1.tar.gz`
/// * A source dist with a recognizable extension but invalid name: `https://github.com/foo-labs/foo/archive/master.zip#egg=pkg&subdirectory=packages/bar`
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct ParsedArchiveUrl {
pub url: DisplaySafeUrl,
pub subdirectory: Option<Box<Path>>,
pub ext: DistExtension,
}
impl ParsedArchiveUrl {
/// Construct a [`ParsedArchiveUrl`] from a URL requirement source.
pub fn from_source(
location: DisplaySafeUrl,
subdirectory: Option<Box<Path>>,
ext: DistExtension,
) -> Self {
Self {
url: location,
subdirectory,
ext,
}
}
}
impl TryFrom<DisplaySafeUrl> for ParsedArchiveUrl {
type Error = ParsedUrlError;
fn try_from(mut url: DisplaySafeUrl) -> Result<Self, Self::Error> {
// Extract the `#subdirectory` fragment, if present.
let subdirectory = get_subdirectory(&url).map(PathBuf::into_boxed_path);
url.set_fragment(None);
// Infer the extension from the path.
let ext = match DistExtension::from_path(url.path()) {
Ok(ext) => ext,
Err(..) if looks_like_git_repository(&url) => {
return Err(ParsedUrlError::MissingGitPrefix(url.to_string()));
}
Err(err) => return Err(ParsedUrlError::MissingExtensionUrl(url.to_string(), err)),
};
Ok(Self {
url,
subdirectory,
ext,
})
}
}
/// If the URL points to a subdirectory, extract it, as in (git):
/// `git+https://git.example.com/MyProject.git@v1.0#subdirectory=pkg_dir`
/// `git+https://git.example.com/MyProject.git@v1.0#egg=pkg&subdirectory=pkg_dir`
/// or (direct archive url):
/// `https://github.com/foo-labs/foo/archive/master.zip#subdirectory=packages/bar`
/// `https://github.com/foo-labs/foo/archive/master.zip#egg=pkg&subdirectory=packages/bar`
fn get_subdirectory(url: &Url) -> Option<PathBuf> {
let fragment = url.fragment()?;
let subdirectory = fragment
.split('&')
.find_map(|fragment| fragment.strip_prefix("subdirectory="))?;
Some(PathBuf::from(subdirectory))
}
impl TryFrom<DisplaySafeUrl> for ParsedUrl {
type Error = ParsedUrlError;
fn try_from(url: DisplaySafeUrl) -> Result<Self, Self::Error> {
if let Some((prefix, ..)) = url.scheme().split_once('+') {
match prefix {
"git" => Ok(Self::Git(ParsedGitUrl::try_from(url)?)),
"bzr" => Err(ParsedUrlError::UnsupportedUrlPrefix {
prefix: prefix.to_string(),
url: url.to_string(),
message: "Bazaar is not supported",
}),
"hg" => Err(ParsedUrlError::UnsupportedUrlPrefix {
prefix: prefix.to_string(),
url: url.to_string(),
message: "Mercurial is not supported",
}),
"svn" => Err(ParsedUrlError::UnsupportedUrlPrefix {
prefix: prefix.to_string(),
url: url.to_string(),
message: "Subversion is not supported",
}),
_ => Err(ParsedUrlError::UnsupportedUrlPrefix {
prefix: prefix.to_string(),
url: url.to_string(),
message: "Unknown scheme",
}),
}
} else if Path::new(url.path())
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("git"))
{
Ok(Self::Git(ParsedGitUrl::try_from(url)?))
} else if url.scheme().eq_ignore_ascii_case("file") {
let path = url
.to_file_path()
.map_err(|()| ParsedUrlError::InvalidFileUrl(url.to_string()))?;
let is_dir = if let Ok(metadata) = path.metadata() {
metadata.is_dir()
} else {
path.extension().is_none()
};
if is_dir {
Ok(Self::Directory(ParsedDirectoryUrl {
url,
install_path: path.into_boxed_path(),
editable: None,
r#virtual: None,
}))
} else {
Ok(Self::Path(ParsedPathUrl {
url,
ext: DistExtension::from_path(&path)
.map_err(|err| ParsedUrlError::MissingExtensionPath(path.clone(), err))?,
install_path: path.into_boxed_path(),
}))
}
} else {
Ok(Self::Archive(ParsedArchiveUrl::try_from(url)?))
}
}
}
impl From<&ParsedUrl> for DirectUrl {
fn from(value: &ParsedUrl) -> Self {
match value {
ParsedUrl::Path(value) => Self::from(value),
ParsedUrl::Directory(value) => Self::from(value),
ParsedUrl::Git(value) => Self::from(value),
ParsedUrl::Archive(value) => Self::from(value),
}
}
}
impl From<&ParsedPathUrl> for DirectUrl {
fn from(value: &ParsedPathUrl) -> Self {
Self::ArchiveUrl {
url: value.url.to_string(),
archive_info: ArchiveInfo {
hash: None,
hashes: None,
},
subdirectory: None,
}
}
}
impl From<&ParsedDirectoryUrl> for DirectUrl {
fn from(value: &ParsedDirectoryUrl) -> Self {
Self::LocalDirectory {
url: value.url.to_string(),
dir_info: DirInfo {
editable: value.editable,
},
subdirectory: None,
}
}
}
impl From<&ParsedArchiveUrl> for DirectUrl {
fn from(value: &ParsedArchiveUrl) -> Self {
Self::ArchiveUrl {
url: value.url.to_string(),
archive_info: ArchiveInfo {
hash: None,
hashes: None,
},
subdirectory: value.subdirectory.clone(),
}
}
}
impl From<&ParsedGitUrl> for DirectUrl {
fn from(value: &ParsedGitUrl) -> Self {
Self::VcsUrl {
url: value.url.repository().to_string(),
vcs_info: VcsInfo {
vcs: VcsKind::Git,
commit_id: value.url.precise().as_ref().map(ToString::to_string),
requested_revision: value.url.reference().as_str().map(ToString::to_string),
git_lfs: value.url.lfs().enabled().then_some(true),
},
subdirectory: value.subdirectory.clone(),
}
}
}
impl From<ParsedUrl> for DisplaySafeUrl {
fn from(value: ParsedUrl) -> Self {
match value {
ParsedUrl::Path(value) => value.into(),
ParsedUrl::Directory(value) => value.into(),
ParsedUrl::Git(value) => value.into(),
ParsedUrl::Archive(value) => value.into(),
}
}
}
impl From<ParsedPathUrl> for DisplaySafeUrl {
fn from(value: ParsedPathUrl) -> Self {
value.url
}
}
impl From<ParsedDirectoryUrl> for DisplaySafeUrl {
fn from(value: ParsedDirectoryUrl) -> Self {
value.url
}
}
impl From<ParsedArchiveUrl> for DisplaySafeUrl {
fn from(value: ParsedArchiveUrl) -> Self {
let mut url = value.url;
if let Some(subdirectory) = value.subdirectory {
url.set_fragment(Some(&format!("subdirectory={}", subdirectory.display())));
}
url
}
}
impl From<ParsedGitUrl> for DisplaySafeUrl {
fn from(value: ParsedGitUrl) -> Self {
let lfs = value.url.lfs().enabled();
let mut url = Self::parse(&format!("{}{}", "git+", Self::from(value.url).as_str()))
.expect("Git URL is invalid");
let mut frags: Vec<String> = Vec::new();
if let Some(subdirectory) = value.subdirectory {
frags.push(format!("subdirectory={}", subdirectory.display()));
}
// Displays nicely that lfs is used
if lfs {
frags.push("lfs=true".to_string());
}
if !frags.is_empty() {
url.set_fragment(Some(&frags.join("&")));
}
url
}
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use crate::parsed_url::ParsedUrl;
use uv_redacted::DisplaySafeUrl;
#[test]
fn direct_url_from_url() -> Result<()> {
let expected = DisplaySafeUrl::parse("git+https://github.com/pallets/flask.git")?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_eq!(expected, actual);
let expected =
DisplaySafeUrl::parse("git+https://github.com/pallets/flask.git#subdirectory=pkg_dir")?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_eq!(expected, actual);
let expected = DisplaySafeUrl::parse("git+https://github.com/pallets/flask.git@2.0.0")?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_eq!(expected, actual);
let expected = DisplaySafeUrl::parse(
"git+https://github.com/pallets/flask.git@2.0.0#subdirectory=pkg_dir",
)?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_eq!(expected, actual);
// We do not support implicit parsing of the `lfs=true` url fragments for now
let expected = DisplaySafeUrl::parse(
"git+https://github.com/pallets/flask.git#subdirectory=pkg_dir&lfs=true",
)?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_ne!(expected, actual);
// TODO(charlie): Preserve other fragments.
let expected = DisplaySafeUrl::parse(
"git+https://github.com/pallets/flask.git#egg=flask&subdirectory=pkg_dir",
)?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_ne!(expected, actual);
Ok(())
}
#[test]
#[cfg(unix)]
fn direct_url_from_url_absolute() -> Result<()> {
let expected = DisplaySafeUrl::parse("file:///path/to/directory")?;
let actual = DisplaySafeUrl::from(ParsedUrl::try_from(expected.clone())?);
assert_eq!(expected, actual);
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-pypi-types/src/identifier.rs | crates/uv-pypi-types/src/identifier.rs | use serde::{Serialize, Serializer};
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::fmt::Display;
use std::str::FromStr;
use thiserror::Error;
/// Simplified Python identifier.
///
/// We don't match Python's identifier rules
/// (<https://docs.python.org/3.13/reference/lexical_analysis.html#identifiers>) exactly
/// (we just use Rust's `is_alphabetic`) and we don't convert to NFKC, but it's good enough
/// for our validation purposes.
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Identifier(Box<str>);
#[derive(Debug, Clone, Error)]
pub enum IdentifierParseError {
#[error("An identifier must not be empty")]
Empty,
#[error(
"Invalid first character `{first}` for identifier `{identifier}`, expected an underscore or an alphabetic character"
)]
InvalidFirstChar { first: char, identifier: Box<str> },
#[error(
"Invalid character `{invalid_char}` at position {pos} for identifier `{identifier}`, \
expected an underscore or an alphanumeric character"
)]
InvalidChar {
pos: usize,
invalid_char: char,
identifier: Box<str>,
},
}
impl Identifier {
pub fn new(identifier: impl Into<Box<str>>) -> Result<Self, IdentifierParseError> {
let identifier = identifier.into();
let mut chars = identifier.chars().enumerate();
let (_, first_char) = chars.next().ok_or(IdentifierParseError::Empty)?;
if first_char != '_' && !first_char.is_alphabetic() {
return Err(IdentifierParseError::InvalidFirstChar {
first: first_char,
identifier,
});
}
for (pos, current_char) in chars {
if current_char != '_' && !current_char.is_alphanumeric() {
return Err(IdentifierParseError::InvalidChar {
// Make the position 1-indexed
pos: pos + 1,
invalid_char: current_char,
identifier,
});
}
}
Ok(Self(identifier))
}
}
impl FromStr for Identifier {
type Err = IdentifierParseError;
fn from_str(identifier: &str) -> Result<Self, Self::Err> {
Self::new(identifier.to_string())
}
}
impl Display for Identifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl AsRef<str> for Identifier {
fn as_ref(&self) -> &str {
&self.0
}
}
impl<'de> serde::de::Deserialize<'de> for Identifier {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl Serialize for Identifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Serialize::serialize(&self.0, serializer)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Identifier {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("Identifier")
}
fn json_schema(_generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": r"^[_\p{Alphabetic}][_0-9\p{Alphabetic}]*$",
"description": "An identifier in Python"
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
#[test]
fn valid() {
let valid_ids = vec![
"abc",
"_abc",
"a_bc",
"a123",
"snake_case",
"camelCase",
"PascalCase",
// A single character is valid
"_",
"a",
// Unicode
"α",
"férrîs",
"안녕하세요",
];
for valid_id in valid_ids {
assert!(Identifier::from_str(valid_id).is_ok(), "{}", valid_id);
}
}
#[test]
fn empty() {
assert_snapshot!(Identifier::from_str("").unwrap_err(), @"An identifier must not be empty");
}
#[test]
fn invalid_first_char() {
assert_snapshot!(
Identifier::from_str("1foo").unwrap_err(),
@"Invalid first character `1` for identifier `1foo`, expected an underscore or an alphabetic character"
);
assert_snapshot!(
Identifier::from_str("$foo").unwrap_err(),
@"Invalid first character `$` for identifier `$foo`, expected an underscore or an alphabetic character"
);
assert_snapshot!(
Identifier::from_str(".foo").unwrap_err(),
@"Invalid first character `.` for identifier `.foo`, expected an underscore or an alphabetic character"
);
}
#[test]
fn invalid_char() {
// A dot in module names equals a path separator, which is a separate problem.
assert_snapshot!(
Identifier::from_str("foo.bar").unwrap_err(),
@"Invalid character `.` at position 4 for identifier `foo.bar`, expected an underscore or an alphanumeric character"
);
assert_snapshot!(
Identifier::from_str("foo-bar").unwrap_err(),
@"Invalid character `-` at position 4 for identifier `foo-bar`, expected an underscore or an alphanumeric character"
);
assert_snapshot!(
Identifier::from_str("foo_bar$").unwrap_err(),
@"Invalid character `$` at position 8 for identifier `foo_bar$`, expected an underscore or an alphanumeric character"
);
assert_snapshot!(
Identifier::from_str("foo🦀bar").unwrap_err(),
@"Invalid character `🦀` at position 4 for identifier `foo🦀bar`, expected an underscore or an alphanumeric 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-pypi-types/src/conflicts.rs | crates/uv-pypi-types/src/conflicts.rs | use petgraph::{
algo::toposort,
graph::{DiGraph, NodeIndex},
};
use rustc_hash::{FxHashMap, FxHashSet};
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::{collections::BTreeSet, hash::Hash, rc::Rc};
use uv_normalize::{ExtraName, GroupName, PackageName};
use crate::dependency_groups::{DependencyGroupSpecifier, DependencyGroups};
/// A list of conflicting sets of extras/groups pre-defined by an end user.
///
/// This is useful to force the resolver to fork according to extras that have
/// unavoidable conflicts with each other. (The alternative is that resolution
/// will fail.)
#[derive(Debug, Default, Clone, Eq, PartialEq, serde::Deserialize)]
pub struct Conflicts(Vec<ConflictSet>);
impl Conflicts {
/// Returns no conflicts.
///
/// This results in no effect on resolution.
pub fn empty() -> Self {
Self::default()
}
/// Push a single set of conflicts.
pub fn push(&mut self, set: ConflictSet) {
self.0.push(set);
}
/// Returns an iterator over all sets of conflicting sets.
pub fn iter(&self) -> impl Iterator<Item = &'_ ConflictSet> + Clone + '_ {
self.0.iter()
}
/// Returns true if these conflicts contain any set that contains the given
/// package and extra name pair.
pub fn contains<'a>(
&self,
package: &PackageName,
kind: impl Into<ConflictKindRef<'a>>,
) -> bool {
let kind = kind.into();
self.iter().any(|set| set.contains(package, kind))
}
/// Returns true if there are no conflicts.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Appends the given conflicts to this one. This drains all sets from the
/// conflicts given, such that after this call, it is empty.
pub fn append(&mut self, other: &mut Self) {
self.0.append(&mut other.0);
}
/// Expand [`Conflicts`]s to include all [`ConflictSet`]s that can
/// be transitively inferred from group conflicts directly defined
/// in configuration.
///
/// A directed acyclic graph (DAG) is created representing all
/// transitive group includes, with nodes corresponding to group conflict
/// items. For every conflict item directly mentioned in configuration,
/// its node starts with a set of canonical items with itself as the only
/// member.
///
/// The graph is traversed one node at a time in topological order and
/// canonical items are propagated to each neighbor. We also update our
/// substitutions at each neighbor to reflect that this neighbor transitively
/// includes all canonical items visited so far to reach it.
///
/// Finally, we apply the substitutions to the conflict sets that were
/// directly defined in configuration to generate all transitively inferable
/// [`ConflictSet`]s.
///
/// There is an assumption that inclusion graphs will not be very large
/// or complex. This algorithm creates all combinations of substitutions.
/// Each resulting [`ConflictSet`] would also later correspond to a separate
/// resolver fork during resolution.
pub fn expand_transitive_group_includes(
&mut self,
package: &PackageName,
groups: &DependencyGroups,
) {
let mut graph = DiGraph::new();
let mut group_node_idxs: FxHashMap<&GroupName, NodeIndex> = FxHashMap::default();
let mut node_conflict_items: FxHashMap<NodeIndex, Rc<ConflictItem>> = FxHashMap::default();
// Used for transitively deriving new conflict sets with substitutions.
// The keys are canonical items (mentioned directly in configured conflicts).
// The values correspond to groups that transitively include them.
let mut substitutions: FxHashMap<Rc<ConflictItem>, FxHashSet<Rc<ConflictItem>>> =
FxHashMap::default();
// Track all existing conflict sets to avoid duplicates.
let mut conflict_sets: FxHashSet<ConflictSet> = FxHashSet::default();
// Add groups in directly defined conflict sets to the graph.
let mut seen: FxHashSet<&GroupName> = FxHashSet::default();
for set in &self.0 {
conflict_sets.insert(set.clone());
for item in set.iter() {
let ConflictKind::Group(group) = &item.kind else {
// TODO(john): Do we also want to handle extras here?
continue;
};
if !seen.insert(group) {
continue;
}
let item = Rc::new(item.clone());
let mut canonical_items = FxHashSet::default();
canonical_items.insert(item.clone());
let node_id = graph.add_node(canonical_items);
group_node_idxs.insert(group, node_id);
node_conflict_items.insert(node_id, item.clone());
}
}
// Create conflict items for remaining groups and add them to the graph.
for group in groups.keys() {
if !seen.insert(group) {
continue;
}
let group_conflict_item = ConflictItem {
package: package.clone(),
kind: ConflictKind::Group(group.clone()),
};
let node_id = graph.add_node(FxHashSet::default());
group_node_idxs.insert(group, node_id);
node_conflict_items.insert(node_id, Rc::new(group_conflict_item));
}
// Create edges representing group inclusion (with edges reversed so that
// included groups point to including groups).
for (group, specifiers) in groups {
if let Some(includer) = group_node_idxs.get(group) {
for specifier in specifiers {
if let DependencyGroupSpecifier::IncludeGroup { include_group } = specifier {
if let Some(included) = group_node_idxs.get(include_group) {
graph.add_edge(*included, *includer, ());
}
}
}
}
}
let Ok(topo_nodes) = toposort(&graph, None) else {
return;
};
// Propagate canonical items through the graph and populate substitutions.
for node in topo_nodes {
for neighbor_idx in graph.neighbors(node).collect::<Vec<_>>() {
let mut neighbor_canonical_items = Vec::new();
if let Some(canonical_items) = graph.node_weight(node) {
let neighbor_item = node_conflict_items
.get(&neighbor_idx)
.expect("ConflictItem should already be in graph")
.clone();
for canonical_item in canonical_items {
neighbor_canonical_items.push(canonical_item.clone());
substitutions
.entry(canonical_item.clone())
.or_default()
.insert(neighbor_item.clone());
}
}
graph
.node_weight_mut(neighbor_idx)
.expect("Graph node should have weight")
.extend(neighbor_canonical_items.into_iter());
}
}
// Create new conflict sets for all possible replacements of canonical
// items by substitution items.
// Note that new sets are (potentially) added to transitive_conflict_sets
// at the end of each iteration.
for (canonical_item, subs) in substitutions {
let mut new_conflict_sets = FxHashSet::default();
for conflict_set in conflict_sets
.iter()
.filter(|set| set.contains_item(&canonical_item))
.cloned()
.collect::<Vec<_>>()
{
for sub in &subs {
let new_set = conflict_set
.replaced_item(&canonical_item, (**sub).clone())
.expect("`ConflictItem` should be in `ConflictSet`");
if !conflict_sets.contains(&new_set) {
new_conflict_sets.insert(new_set);
}
}
}
conflict_sets.extend(new_conflict_sets.into_iter());
}
// Add all newly discovered conflict sets (excluding the originals already in self.0)
for set in conflict_sets {
if !self.0.contains(&set) {
self.0.push(set);
}
}
}
}
/// A single set of package-extra pairs that conflict with one another.
///
/// Within each set of conflicts, the resolver should isolate the requirements
/// corresponding to each extra from the requirements of other extras in
/// this set. That is, the resolver should put each set of requirements in a
/// different fork.
///
/// A `TryFrom<Vec<ConflictItem>>` impl may be used to build a set from a
/// sequence. Note though that at least 2 items are required.
#[derive(Debug, Default, Clone, Hash, Eq, PartialEq)]
pub struct ConflictSet {
set: BTreeSet<ConflictItem>,
}
impl ConflictSet {
/// Create a pair of items that conflict with one another.
pub fn pair(item1: ConflictItem, item2: ConflictItem) -> Self {
Self {
set: BTreeSet::from_iter(vec![item1, item2]),
}
}
/// Returns an iterator over all conflicting items.
pub fn iter(&self) -> impl Iterator<Item = &'_ ConflictItem> + Clone + '_ {
self.set.iter()
}
/// Returns true if this conflicting item contains the given package and
/// extra name pair.
pub fn contains<'a>(
&self,
package: &PackageName,
kind: impl Into<ConflictKindRef<'a>>,
) -> bool {
let kind = kind.into();
self.iter()
.any(|set| set.package() == package && *set.kind() == kind)
}
/// Returns true if these conflicts contain any set that contains the given
/// [`ConflictItem`].
pub fn contains_item(&self, conflict_item: &ConflictItem) -> bool {
self.set.contains(conflict_item)
}
/// Replace an old [`ConflictItem`] with a new one.
pub fn replaced_item(
&self,
old: &ConflictItem,
new: ConflictItem,
) -> Result<Self, ConflictError> {
let mut new_set = self.set.clone();
if !new_set.contains(old) {
return Err(ConflictError::ReplaceMissingConflictItem);
}
new_set.remove(old);
new_set.insert(new);
Ok(Self { set: new_set })
}
}
impl<'de> serde::Deserialize<'de> for ConflictSet {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let set = Vec::<ConflictItem>::deserialize(deserializer)?;
Self::try_from(set).map_err(serde::de::Error::custom)
}
}
impl TryFrom<Vec<ConflictItem>> for ConflictSet {
type Error = ConflictError;
fn try_from(items: Vec<ConflictItem>) -> Result<Self, ConflictError> {
match items.len() {
0 => return Err(ConflictError::ZeroItems),
1 => return Err(ConflictError::OneItem),
_ => {}
}
Ok(Self {
set: BTreeSet::from_iter(items),
})
}
}
/// A single item in a conflicting set.
///
/// Each item is a pair of a package and a corresponding extra or group name
/// for that package.
#[derive(
Debug, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize, serde::Serialize,
)]
#[serde(
deny_unknown_fields,
try_from = "ConflictItemWire",
into = "ConflictItemWire"
)]
pub struct ConflictItem {
package: PackageName,
kind: ConflictKind,
}
impl ConflictItem {
/// Returns the package name of this conflicting item.
pub fn package(&self) -> &PackageName {
&self.package
}
/// Returns the package-specific conflict.
///
/// i.e., Either an extra or a group name.
pub fn kind(&self) -> &ConflictKind {
&self.kind
}
/// Returns the extra name of this conflicting item.
pub fn extra(&self) -> Option<&ExtraName> {
self.kind.extra()
}
/// Returns the group name of this conflicting item.
pub fn group(&self) -> Option<&GroupName> {
self.kind.group()
}
/// Returns this item as a new type with its fields borrowed.
pub fn as_ref(&self) -> ConflictItemRef<'_> {
ConflictItemRef {
package: self.package(),
kind: self.kind.as_ref(),
}
}
}
impl From<PackageName> for ConflictItem {
fn from(package: PackageName) -> Self {
let kind = ConflictKind::Project;
Self { package, kind }
}
}
impl From<(PackageName, ExtraName)> for ConflictItem {
fn from((package, extra): (PackageName, ExtraName)) -> Self {
let kind = ConflictKind::Extra(extra);
Self { package, kind }
}
}
impl From<(PackageName, GroupName)> for ConflictItem {
fn from((package, group): (PackageName, GroupName)) -> Self {
let kind = ConflictKind::Group(group);
Self { package, kind }
}
}
/// A single item in a conflicting set, by reference.
///
/// Each item is a pair of a package and a corresponding extra name for that
/// package.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct ConflictItemRef<'a> {
package: &'a PackageName,
kind: ConflictKindRef<'a>,
}
impl<'a> ConflictItemRef<'a> {
/// Returns the package name of this conflicting item.
pub fn package(&self) -> &'a PackageName {
self.package
}
/// Returns the package-specific conflict.
///
/// i.e., Either an extra or a group name.
pub fn kind(&self) -> ConflictKindRef<'a> {
self.kind
}
/// Returns the extra name of this conflicting item.
pub fn extra(&self) -> Option<&'a ExtraName> {
self.kind.extra()
}
/// Returns the group name of this conflicting item.
pub fn group(&self) -> Option<&'a GroupName> {
self.kind.group()
}
/// Converts this borrowed conflicting item to its owned variant.
pub fn to_owned(&self) -> ConflictItem {
ConflictItem {
package: self.package().clone(),
kind: self.kind.to_owned(),
}
}
}
impl<'a> From<&'a PackageName> for ConflictItemRef<'a> {
fn from(package: &'a PackageName) -> Self {
let kind = ConflictKindRef::Project;
Self { package, kind }
}
}
impl<'a> From<(&'a PackageName, &'a ExtraName)> for ConflictItemRef<'a> {
fn from((package, extra): (&'a PackageName, &'a ExtraName)) -> Self {
let kind = ConflictKindRef::Extra(extra);
ConflictItemRef { package, kind }
}
}
impl<'a> From<(&'a PackageName, &'a GroupName)> for ConflictItemRef<'a> {
fn from((package, group): (&'a PackageName, &'a GroupName)) -> Self {
let kind = ConflictKindRef::Group(group);
ConflictItemRef { package, kind }
}
}
impl hashbrown::Equivalent<ConflictItem> for ConflictItemRef<'_> {
fn equivalent(&self, key: &ConflictItem) -> bool {
key.as_ref() == *self
}
}
/// The actual conflicting data for a package.
///
/// That is, either an extra or a group name, or the entire project itself.
#[derive(Debug, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ConflictKind {
Extra(ExtraName),
Group(GroupName),
Project,
}
impl ConflictKind {
/// If this conflict corresponds to an extra, then return the
/// extra name.
pub fn extra(&self) -> Option<&ExtraName> {
match self {
Self::Extra(extra) => Some(extra),
Self::Group(_) | Self::Project => None,
}
}
/// If this conflict corresponds to a group, then return the
/// group name.
pub fn group(&self) -> Option<&GroupName> {
match self {
Self::Group(group) => Some(group),
Self::Extra(_) | Self::Project => None,
}
}
/// Returns this conflict as a new type with its fields borrowed.
pub fn as_ref(&self) -> ConflictKindRef<'_> {
match self {
Self::Extra(extra) => ConflictKindRef::Extra(extra),
Self::Group(group) => ConflictKindRef::Group(group),
Self::Project => ConflictKindRef::Project,
}
}
}
/// The actual conflicting data for a package, by reference.
///
/// That is, either a borrowed extra name or a borrowed group name.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum ConflictKindRef<'a> {
Extra(&'a ExtraName),
Group(&'a GroupName),
Project,
}
impl<'a> ConflictKindRef<'a> {
/// If this conflict corresponds to an extra, then return the
/// extra name.
pub fn extra(&self) -> Option<&'a ExtraName> {
match self {
Self::Extra(extra) => Some(extra),
Self::Group(_) | Self::Project => None,
}
}
/// If this conflict corresponds to a group, then return the
/// group name.
pub fn group(&self) -> Option<&'a GroupName> {
match self {
Self::Group(group) => Some(group),
Self::Extra(_) | Self::Project => None,
}
}
/// Converts this borrowed conflict to its owned variant.
pub fn to_owned(&self) -> ConflictKind {
match self {
Self::Extra(extra) => ConflictKind::Extra((*extra).clone()),
Self::Group(group) => ConflictKind::Group((*group).clone()),
Self::Project => ConflictKind::Project,
}
}
}
impl<'a> From<&'a ExtraName> for ConflictKindRef<'a> {
fn from(extra: &'a ExtraName) -> Self {
Self::Extra(extra)
}
}
impl<'a> From<&'a GroupName> for ConflictKindRef<'a> {
fn from(group: &'a GroupName) -> Self {
Self::Group(group)
}
}
impl PartialEq<ConflictKind> for ConflictKindRef<'_> {
fn eq(&self, other: &ConflictKind) -> bool {
other.as_ref() == *self
}
}
impl<'a> PartialEq<ConflictKindRef<'a>> for ConflictKind {
fn eq(&self, other: &ConflictKindRef<'a>) -> bool {
self.as_ref() == *other
}
}
impl hashbrown::Equivalent<ConflictKind> for ConflictKindRef<'_> {
fn equivalent(&self, key: &ConflictKind) -> bool {
key.as_ref() == *self
}
}
/// An error that occurs when the given conflicting set is invalid somehow.
#[derive(Debug, thiserror::Error)]
pub enum ConflictError {
/// An error for when there are zero conflicting items.
#[error("Each set of conflicts must have at least two entries, but found none")]
ZeroItems,
/// An error for when there is one conflicting items.
#[error("Each set of conflicts must have at least two entries, but found only one")]
OneItem,
/// An error that occurs when the `package` field is missing.
///
/// (This is only applicable when deserializing from the lock file.
/// When deserializing from `pyproject.toml`, the `package` field is
/// optional.)
#[error("Expected `package` field in conflicting entry")]
MissingPackage,
/// An error that occurs when all of `package`, `extra` and `group` are missing.
#[error("Expected `package`, `extra` or `group` field in conflicting entry")]
MissingPackageAndExtraAndGroup,
/// An error that occurs when both `extra` and `group` are present.
#[error("Expected one of `extra` or `group` in conflicting entry, but found both")]
FoundExtraAndGroup,
#[error("Expected `ConflictSet` to contain `ConflictItem` to replace")]
ReplaceMissingConflictItem,
}
/// Like [`Conflicts`], but for deserialization in `pyproject.toml`.
///
/// The schema format is different from the in-memory format. Specifically, the
/// schema format does not allow specifying the package name (or will make it
/// optional in the future), where as the in-memory format needs the package
/// name.
///
/// N.B. `Conflicts` is still used for (de)serialization. Specifically, in the
/// lock file, where the package name is required.
#[derive(Debug, Default, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SchemaConflicts(Vec<SchemaConflictSet>);
impl SchemaConflicts {
/// Convert the public schema "conflicting" type to our internal fully
/// resolved type. Effectively, this pairs the corresponding package name
/// with each conflict.
///
/// If a conflict has an explicit package name (written by the end user),
/// then that takes precedence over the given package name, which is only
/// used when there is no explicit package name written.
pub fn to_conflicts_with_package_name(&self, package: &PackageName) -> Conflicts {
let mut conflicting = Conflicts::empty();
for tool_uv_set in &self.0 {
let mut set = vec![];
for item in &tool_uv_set.0 {
let package = item.package.clone().unwrap_or_else(|| package.clone());
set.push(ConflictItem {
package: package.clone(),
kind: item.kind.clone(),
});
}
// OK because we guarantee that
// `SchemaConflictingGroupList` is valid and there aren't
// any new errors that can occur here.
let set = ConflictSet::try_from(set).unwrap();
conflicting.push(set);
}
conflicting
}
}
/// Like [`ConflictSet`], but for deserialization in `pyproject.toml`.
///
/// The schema format is different from the in-memory format. Specifically, the
/// schema format does not allow specifying the package name (or will make it
/// optional in the future), where as the in-memory format needs the package
/// name.
#[derive(Debug, Default, Clone, Eq, PartialEq, serde::Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SchemaConflictSet(Vec<SchemaConflictItem>);
/// Like [`ConflictItem`], but for deserialization in `pyproject.toml`.
///
/// The schema format is different from the in-memory format. Specifically, the
/// schema format does not allow specifying the package name (or will make it
/// optional in the future), where as the in-memory format needs the package
/// name.
#[derive(
Debug, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize, serde::Serialize,
)]
#[serde(
deny_unknown_fields,
try_from = "ConflictItemWire",
into = "ConflictItemWire"
)]
pub struct SchemaConflictItem {
package: Option<PackageName>,
kind: ConflictKind,
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for SchemaConflictItem {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("SchemaConflictItem")
}
fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
<ConflictItemWire as schemars::JsonSchema>::json_schema(generator)
}
}
impl<'de> serde::Deserialize<'de> for SchemaConflictSet {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let items = Vec::<SchemaConflictItem>::deserialize(deserializer)?;
Self::try_from(items).map_err(serde::de::Error::custom)
}
}
impl TryFrom<Vec<SchemaConflictItem>> for SchemaConflictSet {
type Error = ConflictError;
fn try_from(items: Vec<SchemaConflictItem>) -> Result<Self, ConflictError> {
match items.len() {
0 => return Err(ConflictError::ZeroItems),
1 => return Err(ConflictError::OneItem),
_ => {}
}
Ok(Self(items))
}
}
/// A single item in a conflicting set.
///
/// Each item is a pair of an (optional) package and a corresponding extra or group name for that
/// package.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
struct ConflictItemWire {
#[serde(default)]
package: Option<PackageName>,
#[serde(default)]
extra: Option<ExtraName>,
#[serde(default)]
group: Option<GroupName>,
}
impl TryFrom<ConflictItemWire> for ConflictItem {
type Error = ConflictError;
fn try_from(wire: ConflictItemWire) -> Result<Self, ConflictError> {
let Some(package) = wire.package else {
return Err(ConflictError::MissingPackage);
};
match (wire.extra, wire.group) {
(Some(_), Some(_)) => Err(ConflictError::FoundExtraAndGroup),
(None, None) => Ok(Self::from(package)),
(Some(extra), None) => Ok(Self::from((package, extra))),
(None, Some(group)) => Ok(Self::from((package, group))),
}
}
}
impl From<ConflictItem> for ConflictItemWire {
fn from(item: ConflictItem) -> Self {
match item.kind {
ConflictKind::Extra(extra) => Self {
package: Some(item.package),
extra: Some(extra),
group: None,
},
ConflictKind::Group(group) => Self {
package: Some(item.package),
extra: None,
group: Some(group),
},
ConflictKind::Project => Self {
package: Some(item.package),
extra: None,
group: None,
},
}
}
}
impl TryFrom<ConflictItemWire> for SchemaConflictItem {
type Error = ConflictError;
fn try_from(wire: ConflictItemWire) -> Result<Self, ConflictError> {
let package = wire.package;
match (wire.extra, wire.group) {
(Some(_), Some(_)) => Err(ConflictError::FoundExtraAndGroup),
(None, None) => {
let Some(package) = package else {
return Err(ConflictError::MissingPackageAndExtraAndGroup);
};
Ok(Self {
package: Some(package),
kind: ConflictKind::Project,
})
}
(Some(extra), None) => Ok(Self {
package,
kind: ConflictKind::Extra(extra),
}),
(None, Some(group)) => Ok(Self {
package,
kind: ConflictKind::Group(group),
}),
}
}
}
impl From<SchemaConflictItem> for ConflictItemWire {
fn from(item: SchemaConflictItem) -> Self {
match item.kind {
ConflictKind::Extra(extra) => Self {
package: item.package,
extra: Some(extra),
group: None,
},
ConflictKind::Group(group) => Self {
package: item.package,
extra: None,
group: Some(group),
},
ConflictKind::Project => Self {
package: item.package,
extra: None,
group: None,
},
}
}
}
/// An inference about whether a conflicting item is always included or
/// excluded.
///
/// We collect these for each node in the graph after determining which
/// extras/groups are activated for each node. Once we know what's
/// activated, we can infer what must also be *inactivated* based on what's
/// conflicting with it. So for example, if we have a conflict marker like
/// `extra == 'foo' and extra != 'bar'`, and `foo` and `bar` have been
/// declared as conflicting, and we are in a part of the graph where we
/// know `foo` must be activated, then it follows that `extra != 'bar'`
/// must always be true. Because if it were false, it would imply both
/// `foo` and `bar` were activated simultaneously, which uv guarantees
/// won't happen.
///
/// We then use these inferences to simplify the conflict markers.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Inference {
pub included: bool,
pub item: ConflictItem,
}
| 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/direct_url.rs | crates/uv-pypi-types/src/direct_url.rs | use std::collections::BTreeMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
/// Metadata for a distribution that was installed via a direct URL.
///
/// See: <https://packaging.python.org/en/latest/specifications/direct-url-data-structure/>
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", untagged)]
pub enum DirectUrl {
/// The direct URL is a local directory. For example:
/// ```json
/// {"url": "file:///home/user/project", "dir_info": {}}
/// ```
LocalDirectory {
url: String,
dir_info: DirInfo,
#[serde(skip_serializing_if = "Option::is_none")]
subdirectory: Option<Box<Path>>,
},
/// The direct URL is a path to an archive. For example:
/// ```json
/// {"archive_info": {"hash": "sha256=75909db2664838d015e3d9139004ee16711748a52c8f336b52882266540215d8", "hashes": {"sha256": "75909db2664838d015e3d9139004ee16711748a52c8f336b52882266540215d8"}}, "url": "https://files.pythonhosted.org/packages/b8/8b/31273bf66016be6ad22bb7345c37ff350276cfd46e389a0c2ac5da9d9073/wheel-0.41.2-py3-none-any.whl"}
/// ```
ArchiveUrl {
/// The URL without parsed information (such as the Git revision or subdirectory).
///
/// For example, for `pip install git+https://github.com/tqdm/tqdm@cc372d09dcd5a5eabdc6ed4cf365bdb0be004d44#subdirectory=.`,
/// the URL is `https://github.com/tqdm/tqdm`.
url: String,
archive_info: ArchiveInfo,
#[serde(skip_serializing_if = "Option::is_none")]
subdirectory: Option<Box<Path>>,
},
/// The direct URL is path to a VCS repository. For example:
/// ```json
/// {"url": "https://github.com/pallets/flask.git", "vcs_info": {"commit_id": "8d9519df093864ff90ca446d4af2dc8facd3c542", "vcs": "git", "git_lfs": true }}
/// ```
VcsUrl {
url: String,
vcs_info: VcsInfo,
#[serde(skip_serializing_if = "Option::is_none")]
subdirectory: Option<Box<Path>>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct DirInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub editable: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ArchiveInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hashes: Option<BTreeMap<String, String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct VcsInfo {
pub vcs: VcsKind,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub requested_revision: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub git_lfs: Option<bool>, // Prefix lfs with VcsKind::Git per PEP 610
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VcsKind {
Git,
Hg,
Bzr,
Svn,
}
impl std::fmt::Display for VcsKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Git => write!(f, "git"),
Self::Hg => write!(f, "hg"),
Self::Bzr => write!(f, "bzr"),
Self::Svn => write!(f, "svn"),
}
}
}
impl TryFrom<&DirectUrl> for DisplaySafeUrl {
type Error = DisplaySafeUrlError;
fn try_from(value: &DirectUrl) -> Result<Self, Self::Error> {
match value {
DirectUrl::LocalDirectory {
url,
subdirectory,
dir_info: _,
} => {
let mut url = Self::parse(url)?;
if let Some(subdirectory) = subdirectory {
url.set_fragment(Some(&format!("subdirectory={}", subdirectory.display())));
}
Ok(url)
}
DirectUrl::ArchiveUrl {
url,
subdirectory,
archive_info: _,
} => {
let mut url = Self::parse(url)?;
if let Some(subdirectory) = subdirectory {
url.set_fragment(Some(&format!("subdirectory={}", subdirectory.display())));
}
Ok(url)
}
DirectUrl::VcsUrl {
url,
vcs_info,
subdirectory,
} => {
let mut url = Self::parse(&format!("{}+{}", vcs_info.vcs, url))?;
if let Some(commit_id) = &vcs_info.commit_id {
let path = format!("{}@{commit_id}", url.path());
url.set_path(&path);
} else if let Some(requested_revision) = &vcs_info.requested_revision {
let path = format!("{}@{requested_revision}", url.path());
url.set_path(&path);
}
let mut frags: Vec<String> = Vec::new();
if let Some(subdirectory) = subdirectory {
frags.push(format!("subdirectory={}", subdirectory.display()));
}
// Displays nicely that lfs was used
if let Some(true) = vcs_info.git_lfs {
frags.push("lfs=true".to_string());
}
if !frags.is_empty() {
url.set_fragment(Some(&frags.join("&")));
}
Ok(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-pypi-types/src/base_url.rs | crates/uv-pypi-types/src/base_url.rs | use serde::{Deserialize, Serialize};
use uv_redacted::DisplaySafeUrl;
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct BaseUrl(
#[serde(
serialize_with = "DisplaySafeUrl::serialize_internal",
deserialize_with = "DisplaySafeUrl::deserialize_internal"
)]
DisplaySafeUrl,
);
impl BaseUrl {
/// Return the underlying [`DisplaySafeUrl`].
pub fn as_url(&self) -> &DisplaySafeUrl {
&self.0
}
/// Return the underlying [`DisplaySafeUrl`] as a serialized string.
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<DisplaySafeUrl> for BaseUrl {
fn from(url: DisplaySafeUrl) -> Self {
Self(url)
}
}
impl std::fmt::Display for BaseUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.