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 |
|---|---|---|---|---|---|---|---|---|
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/main.rs | src/main.rs | use std::net::IpAddr;
use std::path::Path;
use anyhow::{Result, bail};
use clap::{Parser, error::ErrorKind};
use flowd::{
agents, ai,
cli::{Cli, Commands, RerunOpts, TaskRunOpts, TasksOpts},
commit, commits, daemon, deploy, docs, doctor, env, fixup, history, hub, init, init_tracing,
log_server, notify, palette, parallel, processes, projects, publish, release, repos, skills,
start, storage, task_match, tasks, todo, tools, upstream, deps,
};
fn main() -> Result<()> {
init_tracing();
flowd::config::load_global_secrets();
let raw_args: Vec<String> = std::env::args().collect();
let cli = match Cli::try_parse_from(&raw_args) {
Ok(cli) => cli,
Err(err) => {
if matches!(
err.kind(),
ErrorKind::UnknownArgument | ErrorKind::InvalidSubcommand
) {
// Fallback: treat first positional as task name and rest as args.
let mut iter = raw_args.into_iter();
let _bin = iter.next();
if let Some(task_name) = iter.next() {
let args: Vec<String> = iter.collect();
return tasks::run_with_discovery(&task_name, args);
}
}
err.exit()
}
};
match cli.command {
Some(Commands::Hub(cmd)) => {
hub::run(cmd)?;
}
Some(Commands::Init(opts)) => {
init::run(opts)?;
}
Some(Commands::Doctor(opts)) => {
doctor::run(opts)?;
}
Some(Commands::Tasks(opts)) => {
tasks::list(opts)?;
}
Some(Commands::Global(cmd)) => {
tasks::run_global(cmd)?;
}
Some(Commands::Run(opts)) => {
tasks::run(opts)?;
}
Some(Commands::Search) => {
palette::run_global()?;
}
Some(Commands::LastCmd) => {
history::print_last_record()?;
}
Some(Commands::LastCmdFull) => {
history::print_last_record_full()?;
}
Some(Commands::Rerun(opts)) => {
rerun(opts)?;
}
Some(Commands::Ps(opts)) => {
processes::show_project_processes(opts)?;
}
Some(Commands::Kill(opts)) => {
processes::kill_processes(opts)?;
}
Some(Commands::Logs(opts)) => {
processes::show_task_logs(opts)?;
}
Some(Commands::Projects) => {
projects::show_projects()?;
}
Some(Commands::Sessions(opts)) => {
ai::run_sessions(&opts)?;
}
Some(Commands::Active(opts)) => {
projects::handle_active(opts)?;
}
Some(Commands::Server(opts)) => {
log_server::run(opts)?;
}
Some(Commands::Match(opts)) => {
task_match::run(task_match::MatchOpts {
args: opts.query,
model: opts.model,
port: Some(opts.port),
execute: !opts.dry_run,
})?;
}
Some(Commands::Commit(opts)) => {
// Default: Claude review, no context, gitedit sync
let review_selection =
commit::resolve_review_selection_v2(opts.codex, opts.review_model.clone());
if opts.dry {
commit::dry_run_context()?;
} else if opts.sync {
commit::run_with_check_sync(
!opts.no_push,
opts.context,
review_selection,
opts.message.as_deref(),
opts.tokens,
true,
)?;
} else {
commit::run_with_check_with_gitedit(
!opts.no_push,
opts.context,
review_selection,
opts.message.as_deref(),
opts.tokens,
)?;
}
}
Some(Commands::CommitSimple(opts)) => {
// Simple commit without review
if opts.sync {
commit::run_sync(!opts.no_push)?;
} else {
commit::run(!opts.no_push)?;
}
}
Some(Commands::CommitWithCheck(opts)) => {
// Review but no gitedit sync
let review_selection =
commit::resolve_review_selection_v2(opts.codex, opts.review_model.clone());
if opts.dry {
commit::dry_run_context()?;
} else if opts.sync {
commit::run_with_check_sync(
!opts.no_push,
opts.context,
review_selection,
opts.message.as_deref(),
opts.tokens,
false,
)?;
} else {
commit::run_with_check(
!opts.no_push,
opts.context,
review_selection,
opts.message.as_deref(),
opts.tokens,
)?;
}
}
Some(Commands::Fixup(opts)) => {
fixup::run(opts)?;
}
Some(Commands::Daemon(cmd)) => {
daemon::run(cmd)?;
}
Some(Commands::Ai(cmd)) => {
ai::run(cmd.action)?;
}
Some(Commands::Env(cmd)) => {
env::run(cmd.action)?;
}
Some(Commands::Todo(cmd)) => {
todo::run(cmd)?;
}
Some(Commands::Skills(cmd)) => {
skills::run(cmd)?;
}
Some(Commands::Deps(cmd)) => {
deps::run(cmd)?;
}
Some(Commands::Storage(cmd)) => {
storage::run(cmd)?;
}
Some(Commands::Tools(cmd)) => {
tools::run(cmd)?;
}
Some(Commands::Notify(cmd)) => {
notify::run(cmd)?;
}
Some(Commands::Commits(opts)) => {
commits::run(opts)?;
}
Some(Commands::Start) => {
start::run()?;
}
Some(Commands::Agents(cmd)) => {
agents::run(cmd)?;
}
Some(Commands::Upstream(cmd)) => {
upstream::run(cmd)?;
}
Some(Commands::Deploy(cmd)) => {
deploy::run(cmd)?;
}
Some(Commands::Release(opts)) => {
release::run(opts)?;
}
Some(Commands::Publish(opts)) => {
publish::run(opts)?;
}
Some(Commands::Repos(cmd)) => {
repos::run(cmd)?;
}
Some(Commands::Parallel(cmd)) => {
parallel::run(cmd)?;
}
Some(Commands::Docs(cmd)) => {
docs::run(cmd)?;
}
Some(Commands::TaskShortcut(args)) => {
let Some(task_name) = args.first() else {
bail!("no task name provided");
};
tasks::run_with_discovery(task_name, args[1..].to_vec())?;
}
None => {
palette::run(TasksOpts::default())?;
}
}
Ok(())
}
fn rerun(opts: RerunOpts) -> Result<()> {
let project_root = if opts.config.is_absolute() {
opts.config.parent().unwrap_or(Path::new(".")).to_path_buf()
} else {
std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf())
};
let record = history::load_last_record_for_project(&project_root)?;
let Some(rec) = record else {
bail!("no previous task found for this project");
};
// Parse user_input to extract task name and args (respecting shell quoting)
let parts = shell_words::split(&rec.user_input).unwrap_or_else(|_| vec![rec.task_name.clone()]);
let task_name = parts.first().cloned().unwrap_or(rec.task_name.clone());
let args: Vec<String> = parts.into_iter().skip(1).collect();
println!("Re-running: {}", rec.user_input);
tasks::run(TaskRunOpts {
config: opts.config,
delegate_to_hub: false,
hub_host: IpAddr::from([127, 0, 0, 1]),
hub_port: 9050,
name: task_name,
args,
})
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/daemon.rs | src/daemon.rs | //! Generic daemon management for flow.
//!
//! Allows starting, stopping, and monitoring background daemons defined in flow.toml.
use std::{
fs,
path::{Path, PathBuf},
process::Command,
time::Duration,
};
use anyhow::{Context, Result, bail};
use reqwest::blocking::Client;
use crate::{
cli::{DaemonAction, DaemonCommand},
config::{self, DaemonConfig},
};
/// Run the daemon command.
pub fn run(cmd: DaemonCommand) -> Result<()> {
let action = cmd.action.unwrap_or(DaemonAction::Status);
match action {
DaemonAction::Start { name } => start_daemon(&name)?,
DaemonAction::Stop { name } => stop_daemon(&name)?,
DaemonAction::Restart { name } => {
stop_daemon(&name).ok();
std::thread::sleep(Duration::from_millis(500));
start_daemon(&name)?;
}
DaemonAction::Status => show_status()?,
DaemonAction::List => list_daemons()?,
}
Ok(())
}
/// Start a daemon by name.
pub fn start_daemon(name: &str) -> Result<()> {
let daemon = find_daemon_config(name)?;
// Check if already running
if let Some(url) = daemon.effective_health_url() {
if check_health(&url) {
println!("β {} is already running", name);
return Ok(());
}
}
// Check if there's a stale PID
if let Some(pid) = load_daemon_pid(name)? {
if process_alive(pid)? {
terminate_process(pid).ok();
}
remove_daemon_pid(name).ok();
}
// Find the binary
let binary = find_binary(&daemon.binary)?;
// Build the command
let mut cmd = Command::new(&binary);
if let Some(subcommand) = &daemon.command {
cmd.arg(subcommand);
}
for arg in &daemon.args {
cmd.arg(arg);
}
// Set working directory
if let Some(wd) = &daemon.working_dir {
let expanded = config::expand_path(wd);
if expanded.exists() {
cmd.current_dir(&expanded);
}
}
// Set environment variables
for (key, value) in &daemon.env {
cmd.env(key, value);
}
// Detach from terminal
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
// Start in own process group so we can kill all children
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
println!(
"Starting {} using {}{}",
name,
binary.display(),
daemon
.command
.as_ref()
.map(|c| format!(" {}", c))
.unwrap_or_default()
);
let child = cmd
.spawn()
.with_context(|| format!("failed to start {} from {}", name, binary.display()))?;
persist_daemon_pid(name, child.id())?;
// Wait a moment and check health
std::thread::sleep(Duration::from_millis(500));
if let Some(url) = daemon.effective_health_url() {
if check_health(&url) {
println!("β {} started successfully", name);
} else {
println!(
"β {} started but health check failed (may need more time)",
name
);
}
} else {
println!("β {} started (no health check configured)", name);
}
Ok(())
}
/// Stop a daemon by name.
pub fn stop_daemon(name: &str) -> Result<()> {
let daemon = find_daemon_config(name).ok();
if let Some(pid) = load_daemon_pid(name)? {
if process_alive(pid)? {
terminate_process(pid)?;
println!("β {} stopped (PID {})", name, pid);
} else {
println!("β {} was not running", name);
}
remove_daemon_pid(name).ok();
} else {
println!("β {} was not running (no PID file)", name);
}
// Also try to kill any process listening on the daemon's port
// This handles cases where child processes outlive the parent
if let Some(daemon) = daemon {
if let Some(port) = daemon.port {
kill_process_on_port(port).ok();
} else if let Some(url) = &daemon.health_url {
if let Some(port) = extract_port_from_url(url) {
kill_process_on_port(port).ok();
}
}
}
Ok(())
}
/// Show status of all configured daemons.
pub fn show_status() -> Result<()> {
let config = load_merged_config()?;
if config.daemons.is_empty() {
println!("No daemons configured.");
println!();
println!("Add daemons to ~/.config/flow/flow.toml or project flow.toml:");
println!();
println!(" [[daemon]]");
println!(" name = \"my-daemon\"");
println!(" binary = \"my-app\"");
println!(" command = \"serve\"");
println!(" health_url = \"http://127.0.0.1:8080/health\"");
return Ok(());
}
println!("Daemon Status:");
println!();
for daemon in &config.daemons {
let status = get_daemon_status(&daemon);
let icon = if status.running { "β" } else { "β" };
let state = if status.running { "running" } else { "stopped" };
print!(" {} {}: {}", icon, daemon.name, state);
if let Some(url) = daemon.effective_health_url() {
if status.running {
print!(" ({})", url.replace("/health", ""));
}
}
if let Some(pid) = status.pid {
print!(" [PID {}]", pid);
}
println!();
if let Some(desc) = &daemon.description {
println!(" {}", desc);
}
}
Ok(())
}
/// List available daemons.
pub fn list_daemons() -> Result<()> {
let config = load_merged_config()?;
if config.daemons.is_empty() {
println!("No daemons configured.");
return Ok(());
}
println!("Available daemons:");
println!();
for daemon in &config.daemons {
print!(" {}", daemon.name);
if let Some(desc) = &daemon.description {
print!(" - {}", desc);
}
println!();
}
Ok(())
}
/// Status of a daemon.
#[derive(Debug)]
pub struct DaemonStatus {
pub running: bool,
pub pid: Option<u32>,
}
/// Get the status of a specific daemon.
pub fn get_daemon_status(daemon: &DaemonConfig) -> DaemonStatus {
let pid = load_daemon_pid(&daemon.name).ok().flatten();
let running = if let Some(url) = daemon.effective_health_url() {
check_health(&url)
} else if let Some(pid) = pid {
process_alive(pid).unwrap_or(false)
} else {
false
};
DaemonStatus { running, pid }
}
/// Find a daemon config by name from merged configs.
fn find_daemon_config(name: &str) -> Result<DaemonConfig> {
let config = load_merged_config()?;
config
.daemons
.into_iter()
.find(|d| d.name == name)
.ok_or_else(|| anyhow::anyhow!("daemon '{}' not found in config", name))
}
/// Load merged config from global and local sources.
fn load_merged_config() -> Result<config::Config> {
let mut merged = config::Config::default();
// Load global config
let global_path = config::default_config_path();
if global_path.exists() {
if let Ok(global_cfg) = config::load(&global_path) {
merged.daemons.extend(global_cfg.daemons);
}
}
// Load local config if it exists
let local_path = std::env::current_dir()
.map(|d| d.join("flow.toml"))
.unwrap_or_else(|_| PathBuf::from("flow.toml"));
if local_path.exists() {
if let Ok(local_cfg) = config::load(&local_path) {
merged.daemons.extend(local_cfg.daemons);
}
}
Ok(merged)
}
/// Find a binary on PATH or as an absolute path.
fn find_binary(name: &str) -> Result<PathBuf> {
// If it's an absolute path, use it directly
let path = Path::new(name);
if path.is_absolute() && path.exists() {
return Ok(path.to_path_buf());
}
// Expand ~ if present
let expanded = config::expand_path(name);
if expanded.exists() {
return Ok(expanded);
}
// Try to find on PATH using `which`
let output = Command::new("which")
.arg(name)
.output()
.with_context(|| format!("failed to find binary '{}'", name))?;
if output.status.success() {
let path_str = String::from_utf8_lossy(&output.stdout);
let path = PathBuf::from(path_str.trim());
if path.exists() {
return Ok(path);
}
}
bail!("binary '{}' not found", name)
}
/// Check if a health endpoint is responding.
fn check_health(url: &str) -> bool {
let client = Client::builder()
.timeout(Duration::from_millis(750))
.build();
let Ok(client) = client else {
return false;
};
client
.get(url)
.send()
.and_then(|resp| resp.error_for_status())
.map(|_| true)
.unwrap_or(false)
}
// ============================================================================
// PID file management
// ============================================================================
fn daemon_pid_path(name: &str) -> PathBuf {
if let Some(home) = std::env::var_os("HOME") {
PathBuf::from(home).join(format!(".config/flow/{}.pid", name))
} else {
PathBuf::from(format!(".config/flow/{}.pid", name))
}
}
fn load_daemon_pid(name: &str) -> Result<Option<u32>> {
let path = daemon_pid_path(name);
if !path.exists() {
return Ok(None);
}
let contents =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
let pid: u32 = contents.trim().parse().ok().unwrap_or(0);
if pid == 0 { Ok(None) } else { Ok(Some(pid)) }
}
fn persist_daemon_pid(name: &str, pid: u32) -> Result<()> {
let path = daemon_pid_path(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create pid dir {}", parent.display()))?;
}
fs::write(&path, pid.to_string())
.with_context(|| format!("failed to write {}", path.display()))?;
Ok(())
}
fn remove_daemon_pid(name: &str) -> Result<()> {
let path = daemon_pid_path(name);
if path.exists() {
fs::remove_file(path).ok();
}
Ok(())
}
// ============================================================================
// Process management
// ============================================================================
fn process_alive(pid: u32) -> Result<bool> {
#[cfg(unix)]
{
let status = Command::new("kill").arg("-0").arg(pid.to_string()).status();
return Ok(status.map(|s| s.success()).unwrap_or(false));
}
#[cfg(windows)]
{
let output = Command::new("tasklist")
.output()
.context("failed to invoke tasklist")?;
if !output.status.success() {
return Ok(false);
}
let needle = pid.to_string();
let body = String::from_utf8_lossy(&output.stdout);
Ok(body.lines().any(|line| line.contains(&needle)))
}
}
fn terminate_process(pid: u32) -> Result<()> {
#[cfg(unix)]
{
// First try to kill the process group (negative PID)
// This ensures child processes are also terminated
let pgid_kill = Command::new("kill")
.arg(format!("-{pid}"))
.stderr(std::process::Stdio::null())
.status();
// Also kill the process directly
let status = Command::new("kill")
.arg(format!("{pid}"))
.stderr(std::process::Stdio::null())
.status()
.context("failed to invoke kill command")?;
// If either succeeded, we're good
if status.success() || pgid_kill.map(|s| s.success()).unwrap_or(false) {
return Ok(());
}
bail!(
"kill command exited with status {}",
status.code().unwrap_or(-1)
);
}
#[cfg(windows)]
{
let status = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/F", "/T"]) // /T kills child processes too
.status()
.context("failed to invoke taskkill")?;
if status.success() {
return Ok(());
}
bail!(
"taskkill exited with status {}",
status.code().unwrap_or(-1)
);
}
}
/// Extract port number from a URL like "http://127.0.0.1:7201/health"
fn extract_port_from_url(url: &str) -> Option<u16> {
// Simple extraction: find the port after the last colon before any path
let url = url
.strip_prefix("http://")
.or_else(|| url.strip_prefix("https://"))?;
let host_port = url.split('/').next()?;
let port_str = host_port.rsplit(':').next()?;
port_str.parse().ok()
}
/// Kill any process listening on the given port.
#[cfg(unix)]
fn kill_process_on_port(port: u16) -> Result<()> {
// Use lsof to find the process
let output = Command::new("lsof")
.args(["-ti", &format!(":{}", port)])
.output()
.context("failed to run lsof")?;
if !output.status.success() {
return Ok(()); // No process found on port
}
let pids = String::from_utf8_lossy(&output.stdout);
for pid_str in pids.lines() {
if let Ok(pid) = pid_str.trim().parse::<u32>() {
terminate_process(pid).ok();
}
}
Ok(())
}
#[cfg(windows)]
fn kill_process_on_port(port: u16) -> Result<()> {
// Use netstat to find the process
let output = Command::new("netstat")
.args(["-ano"])
.output()
.context("failed to run netstat")?;
if !output.status.success() {
return Ok(());
}
let port_pattern = format!(":{}", port);
let lines = String::from_utf8_lossy(&output.stdout);
for line in lines.lines() {
if line.contains(&port_pattern) && line.contains("LISTENING") {
// Last column is PID
if let Some(pid_str) = line.split_whitespace().last() {
if let Ok(pid) = pid_str.parse::<u32>() {
terminate_process(pid).ok();
}
}
}
}
Ok(())
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/ai.rs | src/ai.rs | //! AI session management for Claude Code and Codex integration.
//!
//! Tracks and manages AI coding sessions per project, allowing users to:
//! - List sessions for the current project (Claude, Codex, or both)
//! - Save/bookmark sessions with names
//! - Resume sessions
//! - Add notes to sessions
//! - Copy session history to clipboard
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use anyhow::{Context, Result, bail};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing::debug;
use crate::cli::{AiAction, ProviderAiAction};
/// AI provider type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provider {
Claude,
Codex,
All,
}
/// Stored session metadata in .ai/sessions/<provider>/index.json
#[derive(Debug, Serialize, Deserialize, Default)]
struct SessionIndex {
/// Map of user-friendly names to session metadata
sessions: HashMap<String, SavedSession>,
}
/// Commit checkpoint stored in .ai/commit-checkpoints.json
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct CommitCheckpoints {
/// Last commit checkpoint
pub last_commit: Option<CommitCheckpoint>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CommitCheckpoint {
/// When this checkpoint was created
pub timestamp: String,
/// Session ID that was active
pub session_id: Option<String>,
/// Timestamp of the last entry included in that commit
pub last_entry_timestamp: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct SavedSession {
/// Session ID (UUID)
id: String,
/// Which provider this session is from
#[serde(default = "default_provider")]
provider: String,
/// Optional description
description: Option<String>,
/// When this session was saved
saved_at: String,
/// Last resumed timestamp
last_resumed: Option<String>,
}
fn default_provider() -> String {
"claude".to_string()
}
/// Session info extracted from session files
#[derive(Debug, Clone)]
struct AiSession {
/// Session ID (UUID)
session_id: String,
/// Which provider (claude, codex)
provider: Provider,
/// First message timestamp
timestamp: Option<String>,
/// First user message (as summary)
first_message: Option<String>,
/// First error summary (for sessions that never produced a user message)
error_summary: Option<String>,
}
/// Entry from a session .jsonl file (we only parse what we need)
#[derive(Debug, Deserialize)]
struct JsonlEntry {
timestamp: Option<String>,
message: Option<SessionMessage>,
#[serde(rename = "type")]
entry_type: Option<String>,
subtype: Option<String>,
level: Option<String>,
error: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
struct CodexEntry {
timestamp: Option<String>,
#[serde(rename = "type")]
entry_type: Option<String>,
payload: Option<serde_json::Value>,
role: Option<String>,
content: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
struct SessionMessage {
role: Option<String>,
content: Option<serde_json::Value>,
}
/// Run the ai subcommand.
pub fn run(action: Option<AiAction>) -> Result<()> {
let action = action.unwrap_or(AiAction::List);
match action {
AiAction::List => list_sessions(Provider::All)?,
AiAction::Claude { action } => match action.unwrap_or(ProviderAiAction::List) {
ProviderAiAction::List => list_sessions(Provider::Claude)?,
ProviderAiAction::Resume { session } => resume_session(session, Provider::Claude)?,
ProviderAiAction::Copy { session } => copy_session(session, Provider::Claude)?,
ProviderAiAction::Context {
session,
count,
path,
} => copy_context(session, Provider::Claude, count, path)?,
},
AiAction::Codex { action } => match action.unwrap_or(ProviderAiAction::List) {
ProviderAiAction::List => list_sessions(Provider::Codex)?,
ProviderAiAction::Resume { session } => resume_session(session, Provider::Codex)?,
ProviderAiAction::Copy { session } => copy_session(session, Provider::Codex)?,
ProviderAiAction::Context {
session,
count,
path,
} => copy_context(session, Provider::Codex, count, path)?,
},
AiAction::Resume { session } => resume_session(session, Provider::All)?,
AiAction::Save { name, id } => save_session(&name, id)?,
AiAction::Notes { session } => open_notes(&session)?,
AiAction::Remove { session } => remove_session(&session)?,
AiAction::Init => init_ai_folder()?,
AiAction::Import => import_sessions()?,
AiAction::Copy { session } => copy_session(session, Provider::All)?,
AiAction::Context {
session,
count,
path,
} => copy_context(session, Provider::All, count, path)?,
}
Ok(())
}
/// Get checkpoint file path for a project.
fn get_checkpoint_path(project_path: &PathBuf) -> PathBuf {
project_path
.join(".ai")
.join("internal")
.join("commit-checkpoints.json")
}
/// Load commit checkpoints.
pub fn load_checkpoints(project_path: &PathBuf) -> Result<CommitCheckpoints> {
let path = get_checkpoint_path(project_path);
if !path.exists() {
return Ok(CommitCheckpoints::default());
}
let content =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
serde_json::from_str(&content).context("failed to parse commit-checkpoints.json")
}
/// Save commit checkpoints.
pub fn save_checkpoint(project_path: &PathBuf, checkpoint: CommitCheckpoint) -> Result<()> {
let path = get_checkpoint_path(project_path);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let checkpoints = CommitCheckpoints {
last_commit: Some(checkpoint),
};
let content = serde_json::to_string_pretty(&checkpoints)?;
fs::write(&path, content)?;
Ok(())
}
/// Log review result for tracking async commits.
pub fn log_review_result(
project_path: &PathBuf,
issues_found: bool,
issues: &[String],
context_chars: usize,
review_time_secs: u64,
) {
let log_path = project_path.join(".ai").join("internal").join("review-log.jsonl");
if let Some(parent) = log_path.parent() {
let _ = fs::create_dir_all(parent);
}
let entry = json!({
"timestamp": chrono::Utc::now().to_rfc3339(),
"issues_found": issues_found,
"issue_count": issues.len(),
"context_chars": context_chars,
"review_time_secs": review_time_secs,
});
if let Ok(mut file) = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)
{
let _ = writeln!(file, "{}", entry);
}
}
/// Get AI session context since the last commit checkpoint.
/// Returns all exchanges from the checkpoint timestamp to now.
pub fn get_context_since_checkpoint() -> Result<Option<String>> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
get_context_since_checkpoint_for_path(&cwd)
}
/// Get AI session context since the last commit checkpoint for a specific path.
pub fn get_context_since_checkpoint_for_path(project_path: &PathBuf) -> Result<Option<String>> {
let checkpoints = load_checkpoints(project_path).unwrap_or_default();
// Get sessions for both Claude and Codex
let sessions = read_sessions_for_path(Provider::All, project_path)?;
if sessions.is_empty() {
return Ok(None);
}
// Read context since checkpoint
let since_ts = checkpoints
.last_commit
.as_ref()
.and_then(|c| c.last_entry_timestamp.clone());
let mut combined = String::new();
let since_info = if since_ts.is_some() {
" (since last commit)"
} else {
" (full session - no previous commit)"
};
for session in sessions {
let provider_name = match session.provider {
Provider::Claude => "Claude Code",
Provider::Codex => "Codex",
Provider::All => "AI",
};
if let Ok((context, last_ts)) = read_context_since(
&session.session_id,
session.provider,
since_ts.as_deref(),
project_path,
) {
if context.trim().is_empty() {
continue;
}
if !combined.is_empty() {
combined.push_str("\n\n");
}
combined.push_str(&format!(
"=== {} Session Context{} ===\nLast entry: {}\n\n{}\n\n=== End Session Context ===",
provider_name,
since_info,
last_ts.unwrap_or_else(|| "unknown".to_string()),
context
));
}
}
if combined.trim().is_empty() {
Ok(None)
} else {
Ok(Some(combined))
}
}
/// Structured AI session data for GitEdit sync.
#[derive(Debug, Serialize, Clone)]
pub struct GitEditSessionData {
pub session_id: String,
pub provider: String,
pub started_at: Option<String>,
pub last_activity_at: Option<String>,
pub exchanges: Vec<GitEditExchange>,
pub context_summary: Option<String>,
}
#[derive(Debug, Serialize, Clone)]
pub struct GitEditExchange {
pub user_message: String,
pub assistant_message: String,
pub timestamp: String,
}
/// Get session IDs quickly for early hash generation.
/// Returns (session_ids, checkpoint_timestamp) for hashing before full data load.
pub fn get_session_ids_for_hash(project_path: &PathBuf) -> Result<(Vec<String>, Option<String>)> {
let checkpoints = load_checkpoints(project_path).unwrap_or_default();
let sessions = read_sessions_for_path(Provider::All, project_path)?;
let checkpoint_ts = checkpoints
.last_commit
.as_ref()
.and_then(|c| c.last_entry_timestamp.clone());
let session_ids: Vec<String> = sessions
.iter()
.map(|s| s.session_id.clone())
.collect();
Ok((session_ids, checkpoint_ts))
}
/// Get structured AI session data for GitEdit sync.
/// Returns sessions with full exchange history since the last checkpoint.
pub fn get_sessions_for_gitedit(project_path: &PathBuf) -> Result<Vec<GitEditSessionData>> {
let checkpoints = load_checkpoints(project_path).unwrap_or_default();
let sessions = read_sessions_for_path(Provider::All, project_path)?;
if sessions.is_empty() {
return Ok(vec![]);
}
let since_ts = checkpoints
.last_commit
.as_ref()
.and_then(|c| c.last_entry_timestamp.clone());
let mut result = Vec::new();
for session in sessions {
let provider_name = match session.provider {
Provider::Claude => "claude",
Provider::Codex => "codex",
Provider::All => "unknown",
};
// Get full exchanges (not summarized)
let exchanges = get_session_exchanges_since(
&session.session_id,
session.provider,
since_ts.as_deref(),
project_path,
)?;
if exchanges.is_empty() {
continue;
}
// Get last timestamp from exchanges
let last_activity = exchanges.last().map(|e| e.timestamp.clone());
// Create context summary (first few words of first user message)
let context_summary = exchanges.first().map(|e| {
let msg = &e.user_message;
let words: Vec<&str> = msg.split_whitespace().take(10).collect();
let summary = words.join(" ");
if msg.split_whitespace().count() > 10 {
format!("{}...", summary)
} else {
summary
}
});
result.push(GitEditSessionData {
session_id: session.session_id.clone(),
provider: provider_name.to_string(),
started_at: session.timestamp.clone(),
last_activity_at: last_activity,
exchanges,
context_summary,
});
}
Ok(result)
}
/// Get full exchanges from a session since a timestamp.
fn get_session_exchanges_since(
session_id: &str,
provider: Provider,
since_ts: Option<&str>,
project_path: &PathBuf,
) -> Result<Vec<GitEditExchange>> {
if provider == Provider::Codex {
let session_file = find_codex_session_file(session_id);
if let Some(session_file) = session_file {
let (exchanges, _) = read_codex_exchanges(&session_file, since_ts)?;
return Ok(exchanges
.into_iter()
.map(|(user, assistant, ts)| GitEditExchange {
user_message: user,
assistant_message: assistant,
timestamp: ts,
})
.collect());
}
return Ok(vec![]);
}
let path_str = project_path.to_string_lossy().to_string();
let project_folder = path_to_project_name(&path_str);
let projects_dir = get_claude_projects_dir();
let session_file = projects_dir
.join(&project_folder)
.join(format!("{}.jsonl", session_id));
if !session_file.exists() {
return Ok(vec![]);
}
let content = fs::read_to_string(&session_file).context("failed to read session file")?;
let mut exchanges: Vec<GitEditExchange> = Vec::new();
let mut current_user: Option<String> = None;
let mut current_ts: Option<String> = None;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
if let Ok(entry) = serde_json::from_str::<JsonlEntry>(line) {
let entry_ts = entry.timestamp.clone();
// Skip entries before checkpoint
if let (Some(since), Some(ts)) = (since_ts, &entry_ts) {
if ts.as_str() <= since {
continue;
}
}
if let Some(ref msg) = entry.message {
let role = msg.role.as_deref().unwrap_or("unknown");
let content_text = if let Some(ref content) = msg.content {
match content {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Array(arr) => arr
.iter()
.filter_map(|v| {
v.get("text").and_then(|t| t.as_str()).map(|s| s.to_string())
})
.collect::<Vec<_>>()
.join("\n"),
_ => continue,
}
} else {
continue;
};
if content_text.is_empty() {
continue;
}
match role {
"user" => {
current_user = Some(content_text);
current_ts = entry_ts.clone();
}
"assistant" => {
let clean_text = strip_thinking_blocks(&content_text);
if clean_text.trim().is_empty() {
continue;
}
if let Some(user_msg) = current_user.take() {
let ts = current_ts.take().or(entry_ts).unwrap_or_default();
exchanges.push(GitEditExchange {
user_message: user_msg,
assistant_message: clean_text,
timestamp: ts,
});
}
}
_ => {}
}
}
}
}
Ok(exchanges)
}
/// Get the last entry timestamp from the current session (for saving checkpoint).
pub fn get_last_entry_timestamp() -> Result<Option<(String, String)>> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
get_last_entry_timestamp_for_path(&cwd)
}
/// Get the last entry timestamp for sessions associated with a specific path.
pub fn get_last_entry_timestamp_for_path(
project_path: &PathBuf,
) -> Result<Option<(String, String)>> {
let sessions = read_sessions_for_path(Provider::All, project_path)?;
if sessions.is_empty() {
return Ok(None);
}
let mut best: Option<(String, String)> = None;
for session in sessions {
if let Some(ts) =
get_session_last_timestamp(&session.session_id, session.provider, project_path)?
{
let is_newer = best.as_ref().map_or(true, |(_, best_ts)| ts > *best_ts);
if is_newer {
best = Some((session.session_id.clone(), ts));
}
}
}
Ok(best)
}
/// Get the last timestamp from a session file.
fn get_session_last_timestamp(
session_id: &str,
provider: Provider,
project_path: &PathBuf,
) -> Result<Option<String>> {
if provider == Provider::Codex {
let session_file = find_codex_session_file(session_id);
let Some(session_file) = session_file else {
return Ok(None);
};
return get_codex_last_timestamp(&session_file);
}
let path_str = project_path.to_string_lossy().to_string();
let project_folder = path_to_project_name(&path_str);
let projects_dir = match provider {
Provider::Claude | Provider::All => get_claude_projects_dir(),
Provider::Codex => get_codex_projects_dir(),
};
let session_file = projects_dir
.join(&project_folder)
.join(format!("{}.jsonl", session_id));
if !session_file.exists() {
return Ok(None);
}
let content = fs::read_to_string(&session_file).context("failed to read session file")?;
let mut last_ts: Option<String> = None;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
if let Ok(entry) = serde_json::from_str::<JsonlEntry>(line) {
if let Some(ts) = entry.timestamp {
last_ts = Some(ts);
}
}
}
Ok(last_ts)
}
/// Read context from session since a given timestamp.
fn read_context_since(
session_id: &str,
provider: Provider,
since_ts: Option<&str>,
project_path: &PathBuf,
) -> Result<(String, Option<String>)> {
if provider == Provider::Codex {
let session_file = find_codex_session_file(session_id).ok_or_else(|| {
anyhow::anyhow!("Session file not found for Codex session {}", session_id)
})?;
return read_codex_context_since(&session_file, since_ts);
}
let path_str = project_path.to_string_lossy().to_string();
let project_folder = path_to_project_name(&path_str);
let projects_dir = match provider {
Provider::Claude | Provider::All => get_claude_projects_dir(),
Provider::Codex => get_codex_projects_dir(),
};
let session_file = projects_dir
.join(&project_folder)
.join(format!("{}.jsonl", session_id));
if !session_file.exists() {
bail!("Session file not found: {}", session_file.display());
}
let content = fs::read_to_string(&session_file).context("failed to read session file")?;
// Collect exchanges after the checkpoint timestamp
let mut exchanges: Vec<(String, String, String)> = Vec::new(); // (user_msg, assistant_msg, timestamp)
let mut current_user: Option<String> = None;
let mut current_ts: Option<String> = None;
let mut last_ts: Option<String> = None;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
if let Ok(entry) = serde_json::from_str::<JsonlEntry>(line) {
let entry_ts = entry.timestamp.clone();
// Skip entries before checkpoint
if let (Some(since), Some(ts)) = (since_ts, &entry_ts) {
if ts.as_str() <= since {
continue;
}
}
if let Some(ref msg) = entry.message {
let role = msg.role.as_deref().unwrap_or("unknown");
let content_text = if let Some(ref content) = msg.content {
match content {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Array(arr) => arr
.iter()
.filter_map(|v| {
if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
Some(text.to_string())
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n"),
_ => continue,
}
} else {
continue;
};
if content_text.is_empty() {
continue;
}
match role {
"user" => {
current_user = Some(content_text);
current_ts = entry_ts.clone();
}
"assistant" => {
let clean_text = strip_thinking_blocks(&content_text);
if clean_text.trim().is_empty() {
continue;
}
if let Some(user_msg) = current_user.take() {
let ts = current_ts.take().or(entry_ts.clone()).unwrap_or_default();
exchanges.push((user_msg, clean_text, ts.clone()));
last_ts = Some(ts);
}
}
_ => {}
}
}
if entry_ts.is_some() {
last_ts = entry_ts;
}
}
}
if exchanges.is_empty() {
return Ok((String::new(), last_ts));
}
// Optimization: prioritize recent exchanges, fit within reasonable budget
// Keep it compact - extract intent, not full conversation
const MAX_EXCHANGES: usize = 5;
const MAX_USER_CHARS: usize = 500; // User requests are short
const MAX_ASSIST_CHARS: usize = 300; // Just capture what was done, not full response
let total_exchanges = exchanges.len();
let exchanges_to_use: Vec<_> = if total_exchanges > MAX_EXCHANGES {
exchanges
.into_iter()
.skip(total_exchanges - MAX_EXCHANGES)
.collect()
} else {
exchanges
};
// Format compact context - focus on intent
let mut context = String::new();
if total_exchanges > MAX_EXCHANGES {
context.push_str(&format!("[+{} earlier]\n", total_exchanges - MAX_EXCHANGES));
}
for (user_msg, assistant_msg, _ts) in &exchanges_to_use {
// Extract first line/sentence of user msg as intent
let user_intent = extract_intent(user_msg, MAX_USER_CHARS);
let assist_summary = extract_intent(assistant_msg, MAX_ASSIST_CHARS);
context.push_str(">");
context.push_str(&user_intent);
context.push('\n');
context.push_str(&assist_summary);
context.push_str("\n\n");
}
context = context.trim().to_string();
Ok((context, last_ts))
}
/// Find the largest valid UTF-8 char boundary at or before `pos`.
fn floor_char_boundary(s: &str, pos: usize) -> usize {
let mut end = pos.min(s.len());
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
end
}
/// Truncate a message to max chars, preserving meaningful content
fn truncate_message(msg: &str, max_chars: usize) -> String {
if msg.len() <= max_chars {
return msg.to_string();
}
let end = floor_char_boundary(msg, max_chars);
format!("{}...", &msg[..end])
}
/// Extract intent from a message - first meaningful content, truncated
fn extract_intent(msg: &str, max_chars: usize) -> String {
// Skip common prefixes and get to the meat
let clean = msg
.trim()
.trim_start_matches("I'll ")
.trim_start_matches("I will ")
.trim_start_matches("Let me ")
.trim_start_matches("Sure, ")
.trim_start_matches("Okay, ")
.trim_start_matches("I'm going to ")
.trim();
// Take first line or sentence
let first_part = clean
.lines()
.next()
.unwrap_or(clean)
.split(". ")
.next()
.unwrap_or(clean);
truncate_message(first_part, max_chars)
}
fn read_codex_context_since(
session_file: &PathBuf,
since_ts: Option<&str>,
) -> Result<(String, Option<String>)> {
let (exchanges, last_ts) = read_codex_exchanges(session_file, since_ts)?;
if exchanges.is_empty() {
return Ok((String::new(), last_ts));
}
// Optimization: only keep last N exchanges for efficiency
const MAX_EXCHANGES: usize = 8;
const MAX_MSG_CHARS: usize = 2000;
let total_exchanges = exchanges.len();
let exchanges_to_use: Vec<_> = if total_exchanges > MAX_EXCHANGES {
exchanges
.into_iter()
.skip(total_exchanges - MAX_EXCHANGES)
.collect()
} else {
exchanges
};
let mut context = String::new();
// Add summary if we skipped older exchanges
if total_exchanges > MAX_EXCHANGES {
context.push_str(&format!(
"[{} earlier exchanges omitted for brevity]\n\n",
total_exchanges - MAX_EXCHANGES
));
}
for (user_msg, assistant_msg, _ts) in &exchanges_to_use {
context.push_str("H: ");
context.push_str(&truncate_message(user_msg, MAX_MSG_CHARS));
context.push_str("\n\n");
context.push_str("A: ");
context.push_str(&truncate_message(assistant_msg, MAX_MSG_CHARS));
context.push_str("\n\n");
}
while context.ends_with('\n') {
context.pop();
}
context.push('\n');
Ok((context, last_ts))
}
fn read_codex_last_context(session_file: &PathBuf, count: usize) -> Result<String> {
let (exchanges, _last_ts) = read_codex_exchanges(session_file, None)?;
if exchanges.is_empty() {
bail!("No exchanges found in session");
}
let start = exchanges.len().saturating_sub(count);
let last_exchanges = &exchanges[start..];
let mut context = String::new();
for (user_msg, assistant_msg, _ts) in last_exchanges {
context.push_str("Human: ");
context.push_str(user_msg);
context.push_str("\n\n");
context.push_str("Assistant: ");
context.push_str(assistant_msg);
context.push_str("\n\n");
}
while context.ends_with('\n') {
context.pop();
}
context.push('\n');
Ok(context)
}
fn read_codex_exchanges(
session_file: &PathBuf,
since_ts: Option<&str>,
) -> Result<(Vec<(String, String, String)>, Option<String>)> {
let content = fs::read_to_string(session_file).context("failed to read session file")?;
let mut exchanges: Vec<(String, String, String)> = Vec::new();
let mut current_user: Option<String> = None;
let mut current_ts: Option<String> = None;
let mut last_ts: Option<String> = None;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
let entry: CodexEntry = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let entry_ts = entry.timestamp.clone();
if let Some(ts) = entry_ts.as_deref() {
if let Some(since) = since_ts {
if ts <= since {
continue;
}
}
}
if let Some((role, text)) = extract_codex_message(&entry) {
if text.trim().is_empty() {
continue;
}
match role.as_str() {
"user" => {
current_user = Some(text);
current_ts = entry_ts.clone();
}
"assistant" => {
let clean_text = strip_thinking_blocks(&text);
if clean_text.trim().is_empty() {
continue;
}
if let Some(user_msg) = current_user.take() {
let ts = current_ts.take().or(entry_ts.clone()).unwrap_or_default();
exchanges.push((user_msg, clean_text, ts.clone()));
last_ts = Some(ts);
}
}
_ => {}
}
}
if entry_ts.is_some() {
last_ts = entry_ts;
}
}
Ok((exchanges, last_ts))
}
fn get_codex_last_timestamp(session_file: &PathBuf) -> Result<Option<String>> {
let content = fs::read_to_string(session_file).context("failed to read session file")?;
let mut last_ts: Option<String> = None;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
let entry: CodexEntry = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
if let Some(ts) = entry.timestamp {
last_ts = Some(ts);
continue;
}
if let Some(payload_ts) = entry
.payload
.as_ref()
.and_then(|p| p.get("timestamp"))
.and_then(|v| v.as_str())
{
last_ts = Some(payload_ts.to_string());
}
}
Ok(last_ts)
}
fn extract_codex_message(entry: &CodexEntry) -> Option<(String, String)> {
let entry_type = entry.entry_type.as_deref();
if entry_type == Some("response_item") {
let payload = entry.payload.as_ref()?;
if payload.get("type").and_then(|v| v.as_str()) != Some("message") {
return None;
}
let role = payload.get("role").and_then(|v| v.as_str())?.to_string();
let content = payload.get("content")?;
let text = extract_codex_content_text(content)?;
return Some((role, text));
}
if entry_type == Some("event_msg") {
let payload = entry.payload.as_ref()?;
let payload_type = payload.get("type").and_then(|v| v.as_str());
if payload_type == Some("user_message") {
let text = payload.get("message").and_then(|v| v.as_str())?.to_string();
return Some(("user".to_string(), text));
}
if payload_type == Some("agent_message") {
let text = payload.get("message").and_then(|v| v.as_str())?.to_string();
return Some(("assistant".to_string(), text));
}
}
if entry_type == Some("message") {
let role = entry.role.as_deref()?.to_string();
let content = entry.content.as_ref()?;
let text = extract_codex_content_text(content)?;
return Some((role, text));
}
None
}
/// Get recent AI session context for the current project.
/// Used by commit workflow to provide context for code review.
/// Returns the last N exchanges from the most recent sessions.
pub fn get_recent_session_context(max_exchanges: usize) -> Result<Option<String>> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
// Get sessions for both Claude and Codex
let sessions = read_sessions_for_path(Provider::All, &cwd)?;
if sessions.is_empty() {
return Ok(None);
}
// Get the most recent session
let recent_session = &sessions[0];
// Read context from the most recent session
match read_last_context(
&recent_session.session_id,
recent_session.provider,
max_exchanges,
&cwd,
) {
Ok(context) => {
if context.trim().is_empty() {
Ok(None)
} else {
let provider_name = match recent_session.provider {
Provider::Claude => "Claude Code",
Provider::Codex => "Codex",
Provider::All => "AI",
};
Ok(Some(format!(
"=== Recent {} Session Context ===\n\n{}\n\n=== End Session Context ===",
provider_name, context
)))
}
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | true |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/running.rs | src/running.rs | use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
/// A process started by flow
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunningProcess {
/// Process ID of the main task process
pub pid: u32,
/// Process group ID (for killing child processes)
pub pgid: u32,
/// Name of the task from flow.toml
pub task_name: String,
/// Full command that was executed
pub command: String,
/// Timestamp when the process was started (ms since epoch)
pub started_at: u128,
/// Canonical path to the flow.toml that defines this task
pub config_path: PathBuf,
/// Canonical path to the project root directory
pub project_root: PathBuf,
/// Whether flox environment was used
pub used_flox: bool,
/// Optional project name from flow.toml
#[serde(default)]
pub project_name: Option<String>,
}
/// All running processes tracked by flow
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RunningProcesses {
/// Map from project config path to list of running processes
pub projects: HashMap<String, Vec<RunningProcess>>,
}
/// Returns ~/.config/flow/running.json
pub fn running_processes_path() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
.join(".config/flow/running.json")
}
/// Load running processes, validating that PIDs are still alive
pub fn load_running_processes() -> Result<RunningProcesses> {
let path = running_processes_path();
if !path.exists() {
return Ok(RunningProcesses::default());
}
let contents =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
let mut processes: RunningProcesses = serde_json::from_str(&contents)
.with_context(|| format!("failed to parse {}", path.display()))?;
// Validate and clean up dead processes
let mut changed = false;
for procs in processes.projects.values_mut() {
let before = procs.len();
procs.retain(|p| process_alive(p.pid));
if procs.len() != before {
changed = true;
}
}
processes.projects.retain(|_, v| !v.is_empty());
if changed {
save_running_processes(&processes)?;
}
Ok(processes)
}
/// Atomically save running processes (write to temp, then rename)
pub fn save_running_processes(processes: &RunningProcesses) -> Result<()> {
let path = running_processes_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let temp_path = path.with_extension("json.tmp");
let contents = serde_json::to_string_pretty(processes)?;
fs::write(&temp_path, contents)?;
fs::rename(&temp_path, &path)?;
Ok(())
}
/// Register a new running process
pub fn register_process(entry: RunningProcess) -> Result<()> {
let mut processes = load_running_processes()?;
let key = entry.config_path.display().to_string();
processes.projects.entry(key).or_default().push(entry);
save_running_processes(&processes)
}
/// Unregister a process by PID
pub fn unregister_process(pid: u32) -> Result<()> {
let mut processes = load_running_processes()?;
for procs in processes.projects.values_mut() {
procs.retain(|p| p.pid != pid);
}
processes.projects.retain(|_, v| !v.is_empty());
save_running_processes(&processes)
}
/// Get processes for a specific project
pub fn get_project_processes(config_path: &Path) -> Result<Vec<RunningProcess>> {
let processes = load_running_processes()?;
let key = config_path.display().to_string();
Ok(processes.projects.get(&key).cloned().unwrap_or_default())
}
/// Check if a process is alive
pub fn process_alive(pid: u32) -> bool {
#[cfg(unix)]
{
use std::process::Stdio;
Command::new("kill")
.arg("-0")
.arg(pid.to_string())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[cfg(windows)]
{
use std::process::Stdio;
Command::new("tasklist")
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()
.map(|o| {
o.status.success() && String::from_utf8_lossy(&o.stdout).contains(&pid.to_string())
})
.unwrap_or(false)
}
}
/// Get process group ID for a PID
#[cfg(unix)]
pub fn get_pgid(pid: u32) -> Option<u32> {
let output = Command::new("ps")
.args(["-o", "pgid=", "-p", &pid.to_string()])
.output()
.ok()?;
String::from_utf8_lossy(&output.stdout).trim().parse().ok()
}
#[cfg(not(unix))]
pub fn get_pgid(pid: u32) -> Option<u32> {
Some(pid)
}
/// Get current timestamp in milliseconds
pub fn now_ms() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/release.rs | src/release.rs | use anyhow::{bail, Result};
use crate::{
cli::ReleaseOpts,
tasks::{self, find_task},
};
fn available_tasks(cfg: &crate::config::Config) -> String {
let mut names: Vec<_> = cfg.tasks.iter().map(|task| task.name.clone()).collect();
names.sort();
names.join(", ")
}
fn resolve_release_task(cfg: &crate::config::Config) -> Result<String> {
if let Some(name) = cfg.flow.release_task.as_deref() {
if find_task(cfg, name).is_some() {
return Ok(name.to_string());
}
bail!(
"release_task '{}' not found. Available tasks: {}",
name,
available_tasks(cfg)
);
}
for fallback in ["release", "release-build"] {
if find_task(cfg, fallback).is_some() {
return Ok(fallback.to_string());
}
}
if let Some(name) = cfg.flow.primary_task.as_deref() {
if find_task(cfg, name).is_some() {
return Ok(name.to_string());
}
}
bail!(
"no release task found. Configure flow.release_task or add a 'release' task. Available tasks: {}",
available_tasks(cfg)
);
}
pub fn run(opts: ReleaseOpts) -> Result<()> {
let (config_path, cfg) = tasks::load_project_config(opts.config)?;
let task_name = resolve_release_task(&cfg)?;
tasks::run(crate::cli::TaskRunOpts {
config: config_path,
delegate_to_hub: false,
hub_host: std::net::IpAddr::from([127, 0, 0, 1]),
hub_port: 9050,
name: task_name,
args: opts.args,
})
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/logs.rs | src/logs.rs | use std::{
io::{BufRead, BufReader},
thread,
time::Duration,
};
use anyhow::{Context, Result, bail};
use reqwest::blocking::Client;
use crate::{
cli::LogsOpts,
servers::{LogLine, LogStream, ServerSnapshot},
};
pub fn run(opts: LogsOpts) -> Result<()> {
if opts.follow && opts.server.is_none() {
bail!("--follow requires specifying --server <name>");
}
let base_url = format!("http://{}:{}", opts.host, opts.port);
let use_color = !opts.no_color;
let client = Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()
.context("failed to build HTTP client")?;
if let Some(server) = opts.server.as_deref() {
if opts.follow {
stream_server_logs(server, opts.host, opts.port, use_color)?;
} else {
let logs = fetch_logs(&client, &base_url, server, opts.limit)?;
print_logs(&logs, use_color);
}
return Ok(());
}
match fetch_all_logs(&client, &base_url, opts.limit) {
Ok(logs) => print_logs(&logs, use_color),
Err(err) => {
eprintln!(
"failed to load aggregated logs: {err:?}\nfallback: fetching per-server logs..."
);
let servers = list_servers(&client, &base_url)?;
for snapshot in servers {
println!("== {} ==", snapshot.name);
let logs = fetch_logs(&client, &base_url, &snapshot.name, opts.limit)?;
print_logs(&logs, use_color);
println!();
}
}
}
Ok(())
}
fn list_servers(client: &Client, base: &str) -> Result<Vec<ServerSnapshot>> {
client
.get(format!("{base}/servers"))
.send()
.context("failed to fetch server list")?
.error_for_status()
.context("server list returned non-success status")?
.json::<Vec<ServerSnapshot>>()
.context("failed to decode server list json")
}
fn fetch_logs(client: &Client, base: &str, server: &str, limit: usize) -> Result<Vec<LogLine>> {
client
.get(format!("{base}/servers/{server}/logs"))
.query(&[("limit", limit.to_string())])
.send()
.with_context(|| format!("failed to request logs for {server}"))?
.error_for_status()
.with_context(|| format!("server {server} returned error status"))?
.json::<Vec<LogLine>>()
.with_context(|| format!("failed to decode log payload for {server}"))
}
fn fetch_all_logs(client: &Client, base: &str, limit: usize) -> Result<Vec<LogLine>> {
client
.get(format!("{base}/logs"))
.query(&[("limit", limit.to_string())])
.send()
.context("failed to request aggregated logs")?
.error_for_status()
.context("aggregated logs endpoint returned error status")?
.json::<Vec<LogLine>>()
.context("failed to decode aggregated logs payload")
}
fn stream_server_logs(server: &str, host: std::net::IpAddr, port: u16, color: bool) -> Result<()> {
println!("Streaming logs for {server} (Ctrl+C to stop)...");
let client = Client::builder()
.timeout(None)
.build()
.context("failed to build streaming client")?;
let url = format!("http://{host}:{port}/servers/{server}/logs/stream");
let mut backoff = Duration::from_secs(1);
loop {
match client.get(&url).send() {
Ok(response) => match response.error_for_status() {
Ok(resp) => {
backoff = Duration::from_secs(1);
let mut reader = BufReader::new(resp);
let mut line = String::new();
while reader.read_line(&mut line)? != 0 {
if let Some(payload) = line.trim().strip_prefix("data:") {
let trimmed = payload.trim();
if trimmed.is_empty() {
line.clear();
continue;
}
match serde_json::from_str::<LogLine>(trimmed) {
Ok(entry) => print_log_line(&entry, color),
Err(err) => eprintln!("failed to decode log entry: {err:?}"),
}
}
line.clear();
}
eprintln!("log stream closed, reconnecting...");
}
Err(err) => {
eprintln!("log stream error: {err}; retrying...");
}
},
Err(err) => {
eprintln!("failed to connect to log stream: {err:?}");
}
}
thread::sleep(backoff);
backoff = (backoff * 2).min(Duration::from_secs(30));
}
}
fn print_logs(logs: &[LogLine], color: bool) {
if logs.is_empty() {
println!("(no logs)\n");
return;
}
for line in logs {
print_log_line(line, color);
}
}
fn print_log_line(line: &LogLine, color: bool) {
let stream = match line.stream {
LogStream::Stdout => "stdout",
LogStream::Stderr => "stderr",
};
if color {
match line.stream {
LogStream::Stdout => {
println!(
"\x1b[38;5;36m[{}][stdout]\x1b[0m {}",
line.server,
line.line.trim_end()
);
}
LogStream::Stderr => {
println!("π΄ {}", line.line.trim_end());
}
}
} else {
println!("[{}][{}] {}", line.server, stream, line.line.trim_end());
}
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/tools.rs | src/tools.rs | //! AI tools management - execute TypeScript tools via localcode/bun.
//!
//! Tools are stored in .ai/tools/<name>.ts
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::cli::{ToolsAction, ToolsCommand};
/// Run the tools subcommand.
pub fn run(cmd: ToolsCommand) -> Result<()> {
let action = cmd.action.unwrap_or(ToolsAction::List);
match action {
ToolsAction::List => list_tools()?,
ToolsAction::Run { name, args } => run_tool(&name, args)?,
ToolsAction::New { name, description, ai } => new_tool(&name, description.as_deref(), ai)?,
ToolsAction::Edit { name } => edit_tool(&name)?,
ToolsAction::Remove { name } => remove_tool(&name)?,
}
Ok(())
}
/// Get the tools directory for the current project.
fn get_tools_dir() -> Result<PathBuf> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
Ok(cwd.join(".ai").join("tools"))
}
/// Find the localcode binary (our opencode fork).
fn find_localcode() -> Option<PathBuf> {
// Check ~/.local/bin/localcode first
if let Some(home) = dirs::home_dir() {
let local_bin = home.join(".local/bin/localcode");
if local_bin.exists() {
return Some(local_bin);
}
}
// Fall back to PATH
which::which("localcode").ok()
}
/// List all tools in the project.
fn list_tools() -> Result<()> {
let tools_dir = get_tools_dir()?;
if !tools_dir.exists() {
println!("No tools found. Create one with: f tools new <name>");
return Ok(());
}
let entries = fs::read_dir(&tools_dir).context("failed to read tools directory")?;
let mut tools: Vec<(String, Option<String>)> = Vec::new();
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.extension().map_or(false, |e| e == "ts") {
let name = path
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("")
.to_string();
let description = parse_tool_description(&path);
tools.push((name, description));
}
}
if tools.is_empty() {
println!("No tools found. Create one with: f tools new <name>");
return Ok(());
}
tools.sort_by(|a, b| a.0.cmp(&b.0));
println!("Tools in .ai/tools/:\n");
for (name, desc) in tools {
if let Some(d) = desc {
println!(" {} - {}", name, d);
} else {
println!(" {}", name);
}
}
println!("\nRun with: f tools run <name>");
Ok(())
}
/// Parse description from first comment line in a .ts file.
fn parse_tool_description(path: &PathBuf) -> Option<String> {
let content = fs::read_to_string(path).ok()?;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with("// ") {
return Some(trimmed.trim_start_matches("// ").to_string());
}
if trimmed.starts_with("///") {
return Some(trimmed.trim_start_matches("///").trim().to_string());
}
// Skip empty lines at the top
if !trimmed.is_empty() && !trimmed.starts_with("//") {
break;
}
}
None
}
/// Run a tool via bun.
fn run_tool(name: &str, args: Vec<String>) -> Result<()> {
let tools_dir = get_tools_dir()?;
let tool_file = tools_dir.join(format!("{}.ts", name));
if !tool_file.exists() {
bail!(
"Tool '{}' not found. Create it with: f tools new {}",
name,
name
);
}
let status = Command::new("bun")
.arg("run")
.arg(&tool_file)
.args(&args)
.status()
.context("failed to run bun")?;
if !status.success() {
bail!("Tool '{}' exited with status: {}", name, status);
}
Ok(())
}
/// Create a new tool.
fn new_tool(name: &str, description: Option<&str>, use_ai: bool) -> Result<()> {
let tools_dir = get_tools_dir()?;
fs::create_dir_all(&tools_dir).context("failed to create tools directory")?;
let tool_file = tools_dir.join(format!("{}.ts", name));
if tool_file.exists() {
bail!("Tool '{}' already exists", name);
}
if use_ai {
// Use localcode to generate the tool
let localcode = find_localcode();
if localcode.is_none() {
bail!(
"localcode not found. Install it with:\n \
cd <opencode-repo> && flow link"
);
}
let desc = description.unwrap_or(name);
let prompt = format!(
"Create a TypeScript tool for Bun called '{}' that: {}\n\n\
Requirements:\n\
- Use Bun APIs (Bun.$, Bun.file, etc.)\n\
- Add a description comment at the top\n\
- Handle CLI args via Bun.argv\n\
- Save to: {}",
name,
desc,
tool_file.display()
);
println!("Generating tool '{}' with AI...\n", name);
let status = Command::new(localcode.unwrap())
.arg("--print")
.arg(&prompt)
.status()
.context("failed to run localcode")?;
if !status.success() {
bail!("AI generation failed with status: {}", status);
}
if tool_file.exists() {
println!("\nCreated tool: {}", tool_file.display());
println!("Run it with: f tools run {}", name);
}
} else {
// Create template
let desc = description.unwrap_or("TODO: Add description");
let content = format!(
r#"// {desc}
import {{ $ }} from "bun"
const args = Bun.argv.slice(2)
// TODO: Implement tool logic
console.log("{name} tool running with args:", args)
"#,
desc = desc,
name = name
);
fs::write(&tool_file, content).context("failed to write tool file")?;
println!("Created tool: {}", tool_file.display());
println!("\nEdit it with: f tools edit {}", name);
println!("Run it with: f tools run {}", name);
}
Ok(())
}
/// Edit a tool in the user's editor.
fn edit_tool(name: &str) -> Result<()> {
let tools_dir = get_tools_dir()?;
let tool_file = tools_dir.join(format!("{}.ts", name));
if !tool_file.exists() {
bail!(
"Tool '{}' not found. Create it with: f tools new {}",
name,
name
);
}
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
Command::new(&editor)
.arg(&tool_file)
.status()
.with_context(|| format!("failed to open editor: {}", editor))?;
Ok(())
}
/// Remove a tool.
fn remove_tool(name: &str) -> Result<()> {
let tools_dir = get_tools_dir()?;
let tool_file = tools_dir.join(format!("{}.ts", name));
if !tool_file.exists() {
bail!("Tool '{}' not found", name);
}
fs::remove_file(&tool_file).context("failed to remove tool file")?;
println!("Removed tool: {}", name);
Ok(())
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/docs.rs | src/docs.rs | //! Auto-generated documentation management.
//!
//! Maintains documentation in `.ai/docs/` that stays in sync with the codebase.
use std::fs;
use std::path::Path;
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::cli::{DocsCommand, DocsAction};
/// Docs directory relative to project root.
const DOCS_DIR: &str = ".ai/docs";
/// Run the docs command.
pub fn run(cmd: DocsCommand) -> Result<()> {
let project_root = std::env::current_dir()?;
let docs_dir = project_root.join(DOCS_DIR);
match cmd.action {
Some(DocsAction::List) | None => list_docs(&docs_dir),
Some(DocsAction::Status) => show_status(&project_root, &docs_dir),
Some(DocsAction::Sync { commits, dry }) => sync_docs(&project_root, &docs_dir, commits, dry),
Some(DocsAction::Edit { name }) => edit_doc(&docs_dir, &name),
}
}
/// List all documentation files.
fn list_docs(docs_dir: &Path) -> Result<()> {
if !docs_dir.exists() {
println!("No docs directory. Run `f start` to create .ai/docs/");
return Ok(());
}
let entries: Vec<_> = fs::read_dir(docs_dir)?
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|ext| ext == "md").unwrap_or(false))
.collect();
if entries.is_empty() {
println!("No documentation files in .ai/docs/");
return Ok(());
}
println!("Documentation files in .ai/docs/:\n");
for entry in entries {
let path = entry.path();
let name = path.file_stem().unwrap_or_default().to_string_lossy();
// Read first line as title
let title = fs::read_to_string(&path)
.ok()
.and_then(|content| {
content.lines()
.find(|l| l.starts_with("# "))
.map(|l| l.trim_start_matches("# ").to_string())
})
.unwrap_or_default();
let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
let size_str = if size > 1024 {
format!("{:.1}KB", size as f64 / 1024.0)
} else {
format!("{}B", size)
};
println!(" {:<15} {:>8} {}", name, size_str, title);
}
Ok(())
}
/// Show documentation status.
fn show_status(project_root: &Path, docs_dir: &Path) -> Result<()> {
if !docs_dir.exists() {
println!("No docs directory. Run `f start` to create .ai/docs/");
return Ok(());
}
// Get recent commits
let output = Command::new("git")
.args(["log", "--oneline", "-10"])
.current_dir(project_root)
.output()
.context("failed to run git log")?;
let commits = String::from_utf8_lossy(&output.stdout);
println!("Recent commits (may need documentation):\n");
for line in commits.lines() {
println!(" {}", line);
}
// Check last sync marker
let marker_path = docs_dir.join(".last_sync");
if marker_path.exists() {
let last_sync = fs::read_to_string(&marker_path)?;
println!("\nLast sync: {}", last_sync.trim());
} else {
println!("\nNo sync marker found. Run `f docs sync` to update.");
}
// List doc files with modification times
println!("\nDoc files:");
let entries: Vec<_> = fs::read_dir(docs_dir)?
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|ext| ext == "md").unwrap_or(false))
.collect();
for entry in entries {
let path = entry.path();
let name = path.file_name().unwrap_or_default().to_string_lossy();
let modified = entry.metadata()
.and_then(|m| m.modified())
.map(|t| {
let duration = t.elapsed().unwrap_or_default();
format_duration(duration)
})
.unwrap_or_else(|_| "unknown".to_string());
println!(" {:<20} modified {}", name, modified);
}
Ok(())
}
/// Sync documentation with recent commits.
fn sync_docs(project_root: &Path, docs_dir: &Path, commits: usize, dry: bool) -> Result<()> {
if !docs_dir.exists() {
bail!("No docs directory. Run `f start` to create .ai/docs/");
}
// Get recent commit messages and diffs
let output = Command::new("git")
.args(["log", "--oneline", &format!("-{}", commits)])
.current_dir(project_root)
.output()
.context("failed to run git log")?;
let commit_list = String::from_utf8_lossy(&output.stdout);
println!("Analyzing {} recent commits...\n", commits);
for line in commit_list.lines() {
println!(" {}", line);
}
if dry {
println!("\n[Dry run] Would analyze commits and update:");
println!(" - commands.md (if new commands added)");
println!(" - changelog.md (add entries for new features)");
println!(" - architecture.md (if structure changed)");
return Ok(());
}
// Update sync marker
let marker_path = docs_dir.join(".last_sync");
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
// Get current HEAD
let head = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.current_dir(project_root)
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default();
fs::write(&marker_path, format!("{} ({})\n", now, head))?;
println!("\nβ Sync marker updated");
println!("\nTo fully sync docs, use an AI assistant to:");
println!(" 1. Review recent commits");
println!(" 2. Update changelog.md with new features");
println!(" 3. Update commands.md if CLI changed");
println!(" 4. Update architecture.md if structure changed");
Ok(())
}
/// Open a doc file in the editor.
fn edit_doc(docs_dir: &Path, name: &str) -> Result<()> {
let doc_path = docs_dir.join(format!("{}.md", name));
if !doc_path.exists() {
bail!("Doc file not found: {}.md", name);
}
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
Command::new(&editor)
.arg(&doc_path)
.status()
.with_context(|| format!("failed to open {} with {}", doc_path.display(), editor))?;
Ok(())
}
/// Format a duration as a human-readable string.
fn format_duration(duration: std::time::Duration) -> String {
let secs = duration.as_secs();
if secs < 60 {
format!("{}s ago", secs)
} else if secs < 3600 {
format!("{}m ago", secs / 60)
} else if secs < 86400 {
format!("{}h ago", secs / 3600)
} else {
format!("{}d ago", secs / 86400)
}
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/lin_runtime.rs | src/lin_runtime.rs | use std::{
fs,
path::{Path, PathBuf},
process::Command,
};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
/// Location and metadata for the lin binary that flow should launch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinRuntime {
pub binary: PathBuf,
pub version: Option<String>,
}
/// Path where the runtime metadata is stored.
pub fn runtime_path() -> PathBuf {
if let Some(home) = std::env::var_os("HOME") {
PathBuf::from(home).join(".config/flow/hub-runtime.json")
} else {
PathBuf::from(".config/flow/hub-runtime.json")
}
}
/// Persist the runtime selection so flow can reuse it.
pub fn persist_runtime(runtime: &LinRuntime) -> Result<()> {
let path = runtime_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
let payload =
serde_json::to_string_pretty(runtime).context("failed to serialize lin runtime info")?;
fs::write(&path, payload).with_context(|| format!("failed to write {}", path.display()))?;
Ok(())
}
/// Load previously registered runtime details, if present.
pub fn load_runtime() -> Result<Option<LinRuntime>> {
let path = runtime_path();
if !path.exists() {
return Ok(None);
}
let contents =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
let runtime: LinRuntime = serde_json::from_str(&contents)
.with_context(|| format!("failed to parse lin runtime at {}", path.display()))?;
Ok(Some(runtime))
}
/// Best-effort version detection from the supplied binary.
pub fn detect_binary_version(path: &Path) -> Option<String> {
Command::new(path)
.arg("--version")
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|s| s.trim().to_string())
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/skills.rs | src/skills.rs | //! Codex skills management.
//!
//! Skills are stored in .ai/skills/<name>/skill.md
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::cli::{SkillsAction, SkillsCommand};
use crate::config;
/// Run the skills subcommand.
pub fn run(cmd: SkillsCommand) -> Result<()> {
let action = cmd.action.unwrap_or(SkillsAction::List);
match action {
SkillsAction::List => list_skills()?,
SkillsAction::New { name, description } => new_skill(&name, description.as_deref())?,
SkillsAction::Show { name } => show_skill(&name)?,
SkillsAction::Edit { name } => edit_skill(&name)?,
SkillsAction::Remove { name } => remove_skill(&name)?,
SkillsAction::Install { name } => install_skill(&name)?,
SkillsAction::Search { query } => list_remote_skills(query.as_deref())?,
SkillsAction::Sync => sync_skills()?,
}
Ok(())
}
/// Get the skills directory for the current project.
fn get_skills_dir() -> Result<PathBuf> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
Ok(cwd.join(".ai").join("skills"))
}
/// Ensure symlinks exist from .claude/skills and .codex/skills to .ai/skills
fn ensure_symlinks() -> Result<()> {
let cwd = std::env::current_dir()?;
let ai_skills = cwd.join(".ai").join("skills");
if !ai_skills.exists() {
return Ok(());
}
// Create .claude/skills -> .ai/skills
let claude_dir = cwd.join(".claude");
let claude_skills = claude_dir.join("skills");
create_symlink_if_needed(&ai_skills, &claude_dir, &claude_skills)?;
// Create .codex/skills -> .ai/skills
let codex_dir = cwd.join(".codex");
let codex_skills = codex_dir.join("skills");
create_symlink_if_needed(&ai_skills, &codex_dir, &codex_skills)?;
Ok(())
}
/// Create a symlink if it doesn't exist or points elsewhere.
fn create_symlink_if_needed(
target: &PathBuf,
parent_dir: &PathBuf,
link_path: &PathBuf,
) -> Result<()> {
// Create parent directory if needed
if !parent_dir.exists() {
fs::create_dir_all(parent_dir)?;
}
// Check if symlink already exists and points to correct target
if link_path.is_symlink() {
if let Ok(existing_target) = fs::read_link(link_path) {
if existing_target == *target || existing_target == PathBuf::from("../.ai/skills") {
return Ok(()); // Already correct
}
}
// Wrong target, remove it
fs::remove_file(link_path)?;
} else if link_path.exists() {
// It's a real directory, skip (don't overwrite user's files)
return Ok(());
}
// Create relative symlink: .claude/skills -> ../.ai/skills
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink("../.ai/skills", link_path)?;
}
#[cfg(windows)]
{
use std::os::windows::fs::symlink_dir;
symlink_dir(target, link_path)?;
}
Ok(())
}
/// List all skills in the project.
fn list_skills() -> Result<()> {
let skills_dir = get_skills_dir()?;
if !skills_dir.exists() {
println!("No skills found. Create one with: f skills new <name>");
return Ok(());
}
let entries = fs::read_dir(&skills_dir).context("failed to read skills directory")?;
let mut skills: Vec<(String, Option<String>)> = Vec::new();
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("")
.to_string();
let skill_file = path.join("skill.md");
let description = if skill_file.exists() {
parse_skill_description(&skill_file)
} else {
None
};
skills.push((name, description));
}
}
if skills.is_empty() {
println!("No skills found. Create one with: f skills new <name>");
return Ok(());
}
skills.sort_by(|a, b| a.0.cmp(&b.0));
println!("Skills in .ai/skills/:\n");
for (name, desc) in skills {
if let Some(d) = desc {
println!(" {} - {}", name, d);
} else {
println!(" {}", name);
}
}
Ok(())
}
/// Parse the description from a skill.md file.
fn parse_skill_description(path: &PathBuf) -> Option<String> {
let content = fs::read_to_string(path).ok()?;
// Look for description in YAML frontmatter
if content.starts_with("---") {
let parts: Vec<&str> = content.splitn(3, "---").collect();
if parts.len() >= 2 {
for line in parts[1].lines() {
let line = line.trim();
if line.starts_with("description:") {
return Some(line.trim_start_matches("description:").trim().to_string());
}
}
}
}
None
}
/// Create a new skill.
fn new_skill(name: &str, description: Option<&str>) -> Result<()> {
let skills_dir = get_skills_dir()?;
let skill_dir = skills_dir.join(name);
if skill_dir.exists() {
bail!("Skill '{}' already exists", name);
}
// Create skill directory
fs::create_dir_all(&skill_dir).context("failed to create skill directory")?;
// Create skill.md
let desc = description.unwrap_or("TODO: Add description");
let content = format!(
r#"---
name: {}
description: {}
---
# {}
## Instructions
TODO: Add instructions for this skill.
## Examples
```bash
# Example usage
```
"#,
name, desc, name
);
let skill_file = skill_dir.join("skill.md");
fs::write(&skill_file, content).context("failed to write skill.md")?;
// Ensure symlinks exist for Claude Code and Codex
ensure_symlinks()?;
println!("Created skill: {}", skill_dir.display());
println!("\nEdit it with: f skills edit {}", name);
Ok(())
}
/// Show skill details.
fn show_skill(name: &str) -> Result<()> {
let skills_dir = get_skills_dir()?;
let skill_file = skills_dir.join(name).join("skill.md");
if !skill_file.exists() {
bail!("Skill '{}' not found", name);
}
let content = fs::read_to_string(&skill_file).context("failed to read skill.md")?;
println!("{}", content);
Ok(())
}
/// Edit a skill in the user's editor.
fn edit_skill(name: &str) -> Result<()> {
let skills_dir = get_skills_dir()?;
let skill_file = skills_dir.join(name).join("skill.md");
if !skill_file.exists() {
bail!(
"Skill '{}' not found. Create it with: f skills new {}",
name,
name
);
}
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
Command::new(&editor)
.arg(&skill_file)
.status()
.with_context(|| format!("failed to open editor: {}", editor))?;
Ok(())
}
/// Remove a skill.
fn remove_skill(name: &str) -> Result<()> {
let skills_dir = get_skills_dir()?;
let skill_dir = skills_dir.join(name);
if !skill_dir.exists() {
bail!("Skill '{}' not found", name);
}
fs::remove_dir_all(&skill_dir).context("failed to remove skill directory")?;
println!("Removed skill: {}", name);
Ok(())
}
const SKILLS_API_URL: &str = "https://1focus-io.nikiv.workers.dev/api/skills";
/// Install a skill from the global skills registry.
fn install_skill(name: &str) -> Result<()> {
println!("Fetching skill '{}' from registry...", name);
// Fetch skill from API
let url = format!("{}?name={}", SKILLS_API_URL, name);
let response = reqwest::blocking::get(&url).context("failed to fetch skill from registry")?;
if response.status() == 404 {
bail!("Skill '{}' not found in registry", name);
}
if !response.status().is_success() {
bail!("Failed to fetch skill: HTTP {}", response.status());
}
let skill: SkillResponse = response.json().context("failed to parse skill response")?;
// Create skill directory
let skills_dir = get_skills_dir()?;
let skill_dir = skills_dir.join(name);
if skill_dir.exists() {
bail!(
"Skill '{}' already exists locally. Remove it first with: f skills remove {}",
name,
name
);
}
fs::create_dir_all(&skill_dir)?;
// Write skill.md
let skill_file = skill_dir.join("skill.md");
fs::write(&skill_file, &skill.content)?;
// Ensure symlinks
ensure_symlinks()?;
println!("Installed skill: {}", name);
println!(
" Source: {}",
skill.source.unwrap_or_else(|| "unknown".to_string())
);
if let Some(author) = skill.author {
println!(" Author: {}", author);
}
Ok(())
}
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct SkillResponse {
name: String,
description: String,
content: String,
source: Option<String>,
author: Option<String>,
}
/// List available skills from the registry.
fn list_remote_skills(search: Option<&str>) -> Result<()> {
let url = if let Some(q) = search {
format!("{}?search={}", SKILLS_API_URL, q)
} else {
SKILLS_API_URL.to_string()
};
let response = reqwest::blocking::get(&url).context("failed to fetch skills from registry")?;
if !response.status().is_success() {
bail!("Failed to fetch skills: HTTP {}", response.status());
}
let skills: Vec<SkillListItem> = response.json().context("failed to parse skills response")?;
if skills.is_empty() {
println!("No skills found in registry.");
return Ok(());
}
println!("Available skills from registry:\n");
for skill in skills {
let source = skill.source.unwrap_or_else(|| "unknown".to_string());
println!(" {} [{}]", skill.name, source);
println!(" {}", skill.description);
println!();
}
println!("Install with: f skills install <name>");
Ok(())
}
#[derive(Debug, serde::Deserialize)]
struct SkillListItem {
name: String,
description: String,
source: Option<String>,
}
/// Sync flow.toml tasks as skills.
fn sync_skills() -> Result<()> {
let cwd = std::env::current_dir()?;
let flow_toml = cwd.join("flow.toml");
if !flow_toml.exists() {
bail!("No flow.toml found in current directory");
}
// Load flow.toml
let cfg = config::load(&flow_toml)?;
let skills_dir = get_skills_dir()?;
fs::create_dir_all(&skills_dir)?;
let mut created = 0;
let mut updated = 0;
for task in &cfg.tasks {
let skill_dir = skills_dir.join(&task.name);
let skill_file = skill_dir.join("skill.md");
let existed = skill_file.exists();
fs::create_dir_all(&skill_dir)?;
let desc = task.description.as_deref().unwrap_or("Flow task");
let content = format!(
r#"---
name: {}
description: {}
source: flow.toml
---
# {}
{}
## Usage
Run this task with:
```bash
f {}
```
## Command
```bash
{}
```
"#,
task.name,
desc,
task.name,
desc,
task.name,
task.command.lines().collect::<Vec<_>>().join("\n")
);
fs::write(&skill_file, content)?;
if existed {
updated += 1;
} else {
created += 1;
}
}
// Ensure symlinks exist for Claude Code and Codex
ensure_symlinks()?;
println!("Synced {} tasks from flow.toml", cfg.tasks.len());
if created > 0 {
println!(" Created: {}", created);
}
if updated > 0 {
println!(" Updated: {}", updated);
}
println!("\nSymlinked to .claude/skills/ and .codex/skills/");
Ok(())
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/indexer.rs | src/indexer.rs | use std::{
env, fs,
path::{Path, PathBuf},
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::{Context, Result, bail};
use rusqlite::Connection;
use crate::cli::IndexOpts;
pub fn run(opts: IndexOpts) -> Result<()> {
let codanna_path = which::which(&opts.binary).with_context(|| {
format!(
"failed to locate '{}' on PATH β install Codanna or pass --binary",
opts.binary
)
})?;
let project_root = resolve_project_root(opts.project_root)?;
ensure_codanna_initialized(&codanna_path, &project_root)?;
run_codanna_index(&codanna_path, &project_root)?;
let payload = capture_index_stats(&codanna_path, &project_root)?;
let db_path = persist_snapshot(&project_root, &codanna_path, &payload, opts.database)?;
println!("Codanna index snapshot stored at {}", db_path.display());
Ok(())
}
fn resolve_project_root(path: Option<PathBuf>) -> Result<PathBuf> {
let raw_path = match path {
Some(p) if p.is_absolute() => p,
Some(p) => env::current_dir()?.join(p),
None => env::current_dir()?,
};
raw_path
.canonicalize()
.with_context(|| format!("failed to resolve project root at {}", raw_path.display()))
}
fn ensure_codanna_initialized(binary: &Path, project_root: &Path) -> Result<()> {
let settings = project_root.join(".codanna/settings.toml");
if settings.exists() {
return Ok(());
}
println!(
"No Codanna settings found at {} β running 'codanna init'.",
settings.display()
);
let status = Command::new(binary)
.arg("init")
.current_dir(project_root)
.status()
.with_context(|| "failed to spawn 'codanna init'")?;
if status.success() {
Ok(())
} else {
bail!(
"'codanna init' exited with status {}",
status.code().unwrap_or(-1)
);
}
}
fn run_codanna_index(binary: &Path, project_root: &Path) -> Result<()> {
println!("Indexing project {} via Codanna...", project_root.display());
let status = Command::new(binary)
.arg("index")
.arg("--progress")
.arg(".")
.current_dir(project_root)
.status()
.with_context(|| "failed to spawn 'codanna index'")?;
if status.success() {
Ok(())
} else {
bail!(
"'codanna index' exited with status {}",
status.code().unwrap_or(-1)
);
}
}
fn capture_index_stats(binary: &Path, project_root: &Path) -> Result<String> {
println!("Fetching Codanna index metadata...");
let output = Command::new(binary)
.arg("mcp")
.arg("get_index_info")
.arg("--json")
.current_dir(project_root)
.output()
.with_context(|| "failed to run 'codanna mcp get_index_info --json'")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("'codanna mcp get_index_info' failed: {}", stderr.trim());
}
let json: serde_json::Value = serde_json::from_slice(&output.stdout)
.with_context(|| "failed to parse JSON from 'codanna mcp get_index_info --json'")?;
serde_json::to_string_pretty(&json).with_context(|| "failed to serialize Codanna stats payload")
}
fn persist_snapshot(
project_root: &Path,
binary: &Path,
payload: &str,
override_path: Option<PathBuf>,
) -> Result<PathBuf> {
let db_path = override_path.unwrap_or_else(default_db_path);
if let Some(parent) = db_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create directory {}", parent.display()))?;
}
let conn = Connection::open(&db_path)
.with_context(|| format!("failed to open sqlite database at {}", db_path.display()))?;
conn.execute(
"CREATE TABLE IF NOT EXISTS index_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_path TEXT NOT NULL,
codanna_binary TEXT NOT NULL,
indexed_at INTEGER NOT NULL,
payload TEXT NOT NULL
)",
[],
)
.with_context(|| "failed to create index_runs table")?;
let repo_str = project_root.display().to_string();
let binary_str = binary.display().to_string();
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.with_context(|| "system clock before UNIX_EPOCH")?
.as_secs() as i64;
conn.execute(
"INSERT INTO index_runs (repo_path, codanna_binary, indexed_at, payload)
VALUES (?1, ?2, ?3, ?4)",
(&repo_str, &binary_str, timestamp, payload),
)
.with_context(|| "failed to insert index snapshot")?;
Ok(db_path)
}
fn default_db_path() -> PathBuf {
if let Some(home) = env::var_os("HOME") {
PathBuf::from(home).join(".db/flow/flow.sqlite")
} else {
PathBuf::from(".db/flow/flow.sqlite")
}
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/start.rs | src/start.rs | //! Project bootstrap and initialization.
//!
//! Creates `.ai/` folder structure with public (tracked) and internal (gitignored) sections.
//!
//! Structure:
//! .ai/
//! βββ actions/ # TRACKED - fixer/action scripts
//! βββ skills/ # TRACKED - shared skills
//! βββ tools/ # TRACKED - shared tools
//! βββ review.md # TRACKED - review instructions
//! βββ internal/ # GITIGNORED - private data
//! βββ sessions/ # AI session data
//! βββ checkpoints/
//! βββ db/
//! βββ *.json # Various state files
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
/// Checkpoint names for tracking completed actions.
pub mod checkpoints {
pub const AI_FOLDER_CREATED: &str = "ai_folder_created";
pub const GITIGNORE_UPDATED: &str = "gitignore_updated";
pub const DB_SCHEMA_CREATED: &str = "db_schema_created";
}
/// Run the start command to bootstrap the project.
pub fn run() -> Result<()> {
let project_root = std::env::current_dir()?;
// Create .ai/ folder structure
if !has_checkpoint(&project_root, checkpoints::AI_FOLDER_CREATED) {
create_ai_folder(&project_root)?;
set_checkpoint(&project_root, checkpoints::AI_FOLDER_CREATED)?;
println!("β Created .ai/ folder structure");
}
// Add .ai/internal/ to .gitignore
if !has_checkpoint(&project_root, checkpoints::GITIGNORE_UPDATED) {
update_gitignore(&project_root)?;
set_checkpoint(&project_root, checkpoints::GITIGNORE_UPDATED)?;
println!("β Updated .gitignore");
}
// Create database schema
if !has_checkpoint(&project_root, checkpoints::DB_SCHEMA_CREATED) {
create_db_schema(&project_root)?;
set_checkpoint(&project_root, checkpoints::DB_SCHEMA_CREATED)?;
println!("β Created .ai/internal/db/ with schema");
}
// Materialize .claude/ and .codex/ from .ai/
materialize_tool_folders(&project_root)?;
println!("\nβ Project ready");
println!("\nStructure:");
println!(" .ai/");
println!(" βββ actions/ # Tracked - fixer scripts");
println!(" βββ skills/ # Tracked - shared skills");
println!(" βββ tools/ # Tracked - shared tools");
println!(" βββ flox/ # Tracked - flox manifest");
println!(" βββ docs/ # Tracked - auto-generated docs");
println!(" βββ agents.md # Tracked - agent instructions");
println!(" βββ internal/ # Gitignored - private data");
println!(" .claude/ # Gitignored - symlinks to .ai/");
println!(" .codex/ # Gitignored - symlinks to .ai/");
println!(" .flox/ # Gitignored - symlinks to .ai/flox/");
Ok(())
}
/// Check if a checkpoint exists.
pub fn has_checkpoint(project_root: &Path, name: &str) -> bool {
checkpoint_path(project_root, name).exists()
}
/// Set a checkpoint (creates an empty file).
pub fn set_checkpoint(project_root: &Path, name: &str) -> Result<()> {
let path = checkpoint_path(project_root, name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, "")?;
Ok(())
}
/// Clear a checkpoint.
#[allow(dead_code)]
pub fn clear_checkpoint(project_root: &Path, name: &str) -> Result<()> {
let path = checkpoint_path(project_root, name);
if path.exists() {
fs::remove_file(&path)?;
}
Ok(())
}
/// Get the path to a checkpoint file.
fn checkpoint_path(project_root: &Path, name: &str) -> PathBuf {
project_root
.join(".ai")
.join("internal")
.join("checkpoints")
.join(name)
}
/// Create the .ai/ folder structure.
fn create_ai_folder(project_root: &Path) -> Result<()> {
let ai_dir = project_root.join(".ai");
let internal_dir = ai_dir.join("internal");
// Public folders (tracked in git)
let public_dirs = [
ai_dir.clone(),
ai_dir.join("actions"),
ai_dir.join("skills"),
ai_dir.join("tools"),
ai_dir.join("flox"),
ai_dir.join("docs"),
];
// Private folders (gitignored)
let internal_dirs = [
internal_dir.clone(),
internal_dir.join("checkpoints"),
internal_dir.join("sessions"),
internal_dir.join("db"),
];
for dir in public_dirs.iter().chain(internal_dirs.iter()) {
fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
}
Ok(())
}
/// Materialize .claude/, .codex/, and .flox/ folders with symlinks to .ai/
fn materialize_tool_folders(project_root: &Path) -> Result<()> {
use std::os::unix::fs::symlink;
let ai_dir = project_root.join(".ai");
let agents_source = ai_dir.join("agents.md");
let skills_source = ai_dir.join("skills");
// Materialize .claude/ and .codex/
for tool_dir in [".claude", ".codex"] {
let tool_path = project_root.join(tool_dir);
fs::create_dir_all(&tool_path)?;
// Symlink skills -> ../.ai/skills
let skills_link = tool_path.join("skills");
if !skills_link.exists() && skills_source.exists() {
let _ = symlink("../.ai/skills", &skills_link);
}
// Symlink agents.md -> ../.ai/agents.md
let agents_link = tool_path.join("agents.md");
if !agents_link.exists() && agents_source.exists() {
let _ = symlink("../.ai/agents.md", &agents_link);
}
}
// Materialize .flox/ from .ai/flox/
let flox_source = ai_dir.join("flox");
let manifest_source = flox_source.join("manifest.toml");
if manifest_source.exists() {
let flox_dir = project_root.join(".flox");
let flox_env_dir = flox_dir.join("env");
fs::create_dir_all(&flox_env_dir)?;
// Symlink manifest.toml -> ../../.ai/flox/manifest.toml
let manifest_link = flox_env_dir.join("manifest.toml");
if !manifest_link.exists() {
let _ = symlink("../../.ai/flox/manifest.toml", &manifest_link);
}
// Create env.json files that flox expects
let env_json = flox_dir.join("env.json");
if !env_json.exists() {
fs::write(&env_json, r#"{
"version": 1,
"manifest": "env/manifest.toml",
"lockfile": "env/manifest.lock"
}"#)?;
}
let env_env_json = flox_env_dir.join("env.json");
if !env_env_json.exists() {
let manifest_path = flox_env_dir.join("manifest.toml");
let lockfile_path = flox_env_dir.join("manifest.lock");
fs::write(&env_env_json, format!(r#"{{
"version": 1,
"manifest": "{}",
"lockfile": "{}"
}}"#, manifest_path.display(), lockfile_path.display()))?;
}
}
Ok(())
}
/// Create the database schema files.
fn create_db_schema(project_root: &Path) -> Result<()> {
let db_dir = project_root.join(".ai/internal/db");
fs::create_dir_all(&db_dir)?;
// Create schema.ts with drizzle-orm schema
let schema_path = db_dir.join("schema.ts");
if !schema_path.exists() {
fs::write(&schema_path, SCHEMA_TEMPLATE)?;
}
// Create index.ts for database connection
let index_path = db_dir.join("index.ts");
if !index_path.exists() {
fs::write(&index_path, DB_INDEX_TEMPLATE)?;
}
// Create package.json for dependencies
let package_path = db_dir.join("package.json");
if !package_path.exists() {
fs::write(&package_path, DB_PACKAGE_TEMPLATE)?;
}
Ok(())
}
const SCHEMA_TEMPLATE: &str = r#"// .ai/internal/db/schema.ts
// Database schema for AI project data using drizzle-orm
import { sqliteTable, text, integer, blob } from "drizzle-orm/sqlite-core"
// Research notes and findings
export const research = sqliteTable("research", {
id: text("id").primaryKey(),
title: text("title").notNull(),
content: text("content").notNull(),
source: text("source"), // URL, file path, or reference
tags: text("tags"), // JSON array of tags
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }),
})
// Tasks and todos tracked by agents
export const tasks = sqliteTable("tasks", {
id: text("id").primaryKey(),
title: text("title").notNull(),
description: text("description"),
status: text("status").notNull().default("pending"), // pending, in_progress, completed, blocked
priority: integer("priority").default(0),
parentId: text("parent_id"), // for subtasks
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
completedAt: integer("completed_at", { mode: "timestamp" }),
})
// Files being tracked or generated
export const files = sqliteTable("files", {
id: text("id").primaryKey(),
path: text("path").notNull().unique(),
contentHash: text("content_hash"),
description: text("description"),
generatedBy: text("generated_by"), // agent/tool that created it
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }),
})
// Key-value store for agent memory/state
export const memory = sqliteTable("memory", {
key: text("key").primaryKey(),
value: text("value").notNull(), // JSON serialized
expiresAt: integer("expires_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
})
// External service connections and context
export const connections = sqliteTable("connections", {
id: text("id").primaryKey(),
service: text("service").notNull(), // github, x, linear, etc.
accountId: text("account_id"),
metadata: text("metadata"), // JSON with service-specific data
syncedAt: integer("synced_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
})
"#;
const DB_INDEX_TEMPLATE: &str = r#"// .ai/internal/db/index.ts
// Database connection and utilities
import { drizzle } from "drizzle-orm/bun-sqlite"
import { Database } from "bun:sqlite"
import * as schema from "./schema"
const sqlite = new Database(".ai/internal/db/db.sqlite")
export const db = drizzle(sqlite, { schema })
// Re-export schema for convenience
export * from "./schema"
// Helper to generate IDs
export const genId = () => crypto.randomUUID()
// Helper to get current timestamp
export const now = () => new Date()
"#;
const DB_PACKAGE_TEMPLATE: &str = r#"{
"name": "@ai/db",
"type": "module",
"dependencies": {
"drizzle-orm": "^0.38.0"
},
"devDependencies": {
"drizzle-kit": "^0.30.0"
},
"scripts": {
"generate": "drizzle-kit generate",
"migrate": "drizzle-kit migrate",
"studio": "drizzle-kit studio"
}
}
"#;
/// Flow gitignore patterns.
const FLOW_GITIGNORE_SECTION: &str = "\
# flow
.ai/internal/
.claude/
.codex/
.flox/
";
/// Add flow section to .gitignore if not already present.
fn update_gitignore(project_root: &Path) -> Result<()> {
let gitignore_path = project_root.join(".gitignore");
let content = if gitignore_path.exists() {
fs::read_to_string(&gitignore_path)?
} else {
String::new()
};
// Check if flow section already exists
if content.contains("# flow") {
return Ok(());
}
// Also check if all patterns are already present (legacy)
let has_ai_internal = content.lines().any(|l| l.trim() == ".ai/internal/");
let has_claude = content.lines().any(|l| l.trim() == ".claude/");
let has_codex = content.lines().any(|l| l.trim() == ".codex/");
let has_flox = content.lines().any(|l| l.trim() == ".flox/");
if has_ai_internal && has_claude && has_codex && has_flox {
return Ok(());
}
// Add flow section
let mut new_content = content;
if !new_content.is_empty() && !new_content.ends_with('\n') {
new_content.push('\n');
}
if !new_content.is_empty() && !new_content.ends_with("\n\n") {
new_content.push('\n');
}
new_content.push_str(FLOW_GITIGNORE_SECTION);
fs::write(&gitignore_path, new_content)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_checkpoint_lifecycle() {
let dir = tempdir().unwrap();
let root = dir.path();
assert!(!has_checkpoint(root, "test_checkpoint"));
set_checkpoint(root, "test_checkpoint").unwrap();
assert!(has_checkpoint(root, "test_checkpoint"));
clear_checkpoint(root, "test_checkpoint").unwrap();
assert!(!has_checkpoint(root, "test_checkpoint"));
}
#[test]
fn test_create_ai_folder() {
let dir = tempdir().unwrap();
let root = dir.path();
create_ai_folder(root).unwrap();
// Public folders
assert!(root.join(".ai").exists());
assert!(root.join(".ai/actions").exists());
assert!(root.join(".ai/skills").exists());
assert!(root.join(".ai/tools").exists());
// Internal folders
assert!(root.join(".ai/internal").exists());
assert!(root.join(".ai/internal/checkpoints").exists());
assert!(root.join(".ai/internal/sessions").exists());
assert!(root.join(".ai/internal/db").exists());
}
#[test]
fn test_update_gitignore_new_file() {
let dir = tempdir().unwrap();
let root = dir.path();
update_gitignore(root).unwrap();
let content = fs::read_to_string(root.join(".gitignore")).unwrap();
assert!(content.contains("# flow"));
assert!(content.contains(".ai/internal/"));
assert!(content.contains(".claude/"));
assert!(content.contains(".codex/"));
}
#[test]
fn test_update_gitignore_existing() {
let dir = tempdir().unwrap();
let root = dir.path();
fs::write(root.join(".gitignore"), "node_modules/\n").unwrap();
update_gitignore(root).unwrap();
let content = fs::read_to_string(root.join(".gitignore")).unwrap();
assert!(content.contains("node_modules/"));
assert!(content.contains("# flow"));
assert!(content.contains(".ai/internal/"));
assert!(content.contains(".claude/"));
assert!(content.contains(".codex/"));
}
#[test]
fn test_update_gitignore_already_present() {
let dir = tempdir().unwrap();
let root = dir.path();
fs::write(root.join(".gitignore"), "# flow\n.ai/internal/\n.claude/\n.codex/\n").unwrap();
update_gitignore(root).unwrap();
let content = fs::read_to_string(root.join(".gitignore")).unwrap();
// Should not duplicate
assert_eq!(content.matches("# flow").count(), 1);
assert_eq!(content.matches(".ai/internal/").count(), 1);
}
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/servers_tui.rs | src/servers_tui.rs | use std::{
io,
time::{Duration, Instant},
};
use anyhow::{Context, Result};
use crossterm::{
event::{self, Event as CEvent, KeyCode, KeyEvent},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap},
};
use crate::{
cli::ServersOpts,
servers::{LogLine, LogStream, ServerSnapshot},
};
const LOG_LIMIT: usize = 512;
pub fn run(opts: ServersOpts) -> Result<()> {
let base_url = format!("http://{}:{}", opts.host, opts.port);
let client = reqwest::blocking::Client::new();
// Set up terminal
enable_raw_mode().context("failed to enable raw mode")?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen).context("failed to enter alternate screen")?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend).context("failed to create terminal backend")?;
let app_result = run_app(&mut terminal, client, base_url);
// Restore terminal state on exit
disable_raw_mode().ok();
let _ = terminal.show_cursor();
drop(terminal);
let mut stdout = io::stdout();
execute!(stdout, LeaveAlternateScreen).ok();
app_result
}
struct App {
client: reqwest::blocking::Client,
base_url: String,
servers: Vec<ServerSnapshot>,
selected: usize,
logs: Vec<LogLine>,
log_scroll: u16,
focus_server: bool,
last_servers_refresh: Instant,
last_logs_refresh: Instant,
}
impl App {
fn new(client: reqwest::blocking::Client, base_url: String) -> Result<Self> {
let mut app = Self {
client,
base_url,
servers: Vec::new(),
selected: 0,
logs: Vec::new(),
log_scroll: 0,
focus_server: true,
last_servers_refresh: Instant::now(),
last_logs_refresh: Instant::now(),
};
app.refresh_servers()?;
app.refresh_logs()?;
Ok(app)
}
fn selected_server_name(&self) -> Option<&str> {
self.servers.get(self.selected).map(|s| s.name.as_str())
}
fn refresh_servers(&mut self) -> Result<()> {
let url = format!("{}/servers", self.base_url);
let resp = self
.client
.get(&url)
.send()
.with_context(|| format!("failed to GET {url}"))?;
if !resp.status().is_success() {
anyhow::bail!(
"daemon responded with {} when fetching servers",
resp.status()
);
}
let servers = resp
.json::<Vec<ServerSnapshot>>()
.context("failed to decode /servers response")?;
self.servers = servers;
if self.selected >= self.servers.len() {
self.selected = self.servers.len().saturating_sub(1);
}
self.last_servers_refresh = Instant::now();
Ok(())
}
fn refresh_logs(&mut self) -> Result<()> {
let request = if self.focus_server {
let name = match self.selected_server_name() {
Some(name) => name,
None => {
self.logs.clear();
self.focus_server = false;
self.last_logs_refresh = Instant::now();
return Ok(());
}
};
format!("{}/servers/{}/logs", self.base_url, name)
} else {
format!("{}/logs", self.base_url)
};
let resp = self
.client
.get(&request)
.query(&[("limit", LOG_LIMIT)])
.send()
.with_context(|| format!("failed to GET {request}"))?;
if resp.status().is_success() {
let logs = resp
.json::<Vec<LogLine>>()
.context("failed to decode logs response")?;
self.logs = logs;
} else {
self.logs.clear();
}
self.last_logs_refresh = Instant::now();
Ok(())
}
fn maybe_refresh(&mut self) -> Result<()> {
let now = Instant::now();
if now.duration_since(self.last_servers_refresh) > Duration::from_secs(5) {
let _ = self.refresh_servers();
}
if now.duration_since(self.last_logs_refresh) > Duration::from_secs(1) {
let _ = self.refresh_logs();
}
Ok(())
}
fn select_next(&mut self) -> Result<()> {
if !self.servers.is_empty() && self.selected + 1 < self.servers.len() {
self.selected += 1;
self.log_scroll = 0;
self.refresh_logs()?;
}
Ok(())
}
fn select_prev(&mut self) -> Result<()> {
if !self.servers.is_empty() && self.selected > 0 {
self.selected -= 1;
self.log_scroll = 0;
self.refresh_logs()?;
}
Ok(())
}
fn scroll_down(&mut self) {
self.log_scroll = self.log_scroll.saturating_add(1);
}
fn scroll_up(&mut self) {
self.log_scroll = self.log_scroll.saturating_sub(1);
}
fn toggle_focus(&mut self) -> Result<()> {
if self.servers.is_empty() {
return Ok(());
}
self.focus_server = !self.focus_server;
self.log_scroll = 0;
self.refresh_logs()
}
fn show_all_logs(&mut self) -> Result<()> {
if self.focus_server {
self.focus_server = false;
self.log_scroll = 0;
self.refresh_logs()
} else {
Ok(())
}
}
fn log_scope_label(&self) -> String {
if self.focus_server {
match self.selected_server_name() {
Some(name) => format!("Focused: {}", name),
None => "Focused: (none)".to_string(),
}
} else {
"All servers".to_string()
}
}
}
fn run_app<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
client: reqwest::blocking::Client,
base_url: String,
) -> Result<()> {
let mut app = App::new(client, base_url)?;
let tick_rate = Duration::from_millis(250);
loop {
terminal
.draw(|f| draw_ui(f, &app))
.context("failed to draw TUI frame")?;
if crossterm::event::poll(tick_rate)? {
if let CEvent::Key(key) = event::read()? {
if handle_key(&mut app, key)? {
break;
}
}
}
app.maybe_refresh()?;
}
Ok(())
}
fn handle_key(app: &mut App, key: KeyEvent) -> Result<bool> {
match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Esc => return Ok(true),
KeyCode::Down | KeyCode::Char('j') => {
app.select_next()?;
}
KeyCode::Up | KeyCode::Char('k') => {
app.select_prev()?;
}
KeyCode::PageDown | KeyCode::Char('J') => {
app.scroll_down();
}
KeyCode::PageUp | KeyCode::Char('K') => {
app.scroll_up();
}
KeyCode::Char('r') => {
app.refresh_servers()?;
app.refresh_logs()?;
}
KeyCode::Char('f') => {
app.toggle_focus()?;
}
KeyCode::Char('a') => {
app.show_all_logs()?;
}
_ => {}
}
Ok(false)
}
fn draw_ui(f: &mut ratatui::Frame<'_>, app: &App) {
let size = f.size();
let layout = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(0), Constraint::Length(3)])
.split(size);
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
.split(layout[0]);
// Servers list
let servers_items: Vec<ListItem> = if app.servers.is_empty() {
vec![ListItem::new("No servers (check config or daemon)")]
} else {
app.servers
.iter()
.map(|s| {
let label = match s.port {
Some(port) => format!("{}:{} [{}]", s.name, port, s.status),
None => format!("{} [{}]", s.name, s.status),
};
ListItem::new(label)
})
.collect()
};
let mut list_state = ListState::default();
if !app.servers.is_empty() {
list_state.select(Some(app.selected));
}
let servers_list = List::new(servers_items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Servers (β/β, r = reload, q = quit)"),
)
.highlight_style(Style::default().add_modifier(Modifier::REVERSED))
.highlight_symbol("βΆ ");
f.render_stateful_widget(servers_list, chunks[0], &mut list_state);
// Logs pane
let log_lines: Vec<Line> = if app.logs.is_empty() {
vec![Line::from(Span::raw("No logs yet"))]
} else {
app.logs
.iter()
.map(|line| {
let ts = format_ts(line.timestamp_ms);
let stream = match line.stream {
LogStream::Stdout => ("OUT", Style::default().fg(Color::Green)),
LogStream::Stderr => ("ERR", Style::default().fg(Color::Red)),
};
let server_label = Span::styled(
format!("{:<12}", line.server),
Style::default()
.fg(Color::LightCyan)
.add_modifier(Modifier::BOLD),
);
Line::from(vec![
Span::styled(
format!("[{ts}]"),
Style::default().add_modifier(Modifier::DIM),
),
Span::raw(" "),
server_label,
Span::raw(" "),
Span::styled(stream.0, stream.1.add_modifier(Modifier::BOLD)),
Span::raw(" "),
Span::raw(line.line.trim_end()),
])
})
.collect()
};
let scope = app.log_scope_label();
let title = format!("Logs ({scope}) β PgUp/PgDn scroll β’ f focus toggle β’ a all logs");
let logs_widget = Paragraph::new(log_lines)
.block(Block::default().borders(Borders::ALL).title(title))
.scroll((app.log_scroll, 0));
f.render_widget(logs_widget, chunks[1]);
let help = Paragraph::new(Line::from(vec![
Span::styled("Hub: ", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(&app.base_url),
Span::raw(" | q quit β’ r refresh β’ j/k select β’ f focus β’ a all logs"),
]))
.block(Block::default().borders(Borders::ALL).title("Help"))
.wrap(Wrap { trim: true });
f.render_widget(help, layout[1]);
}
fn format_ts(ms: u128) -> String {
let secs = ms / 1000;
let millis = ms % 1000;
format!("{secs}.{millis:03}")
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
nikivdev/flow | https://github.com/nikivdev/flow/blob/85db313c274056cf0dbb36cc0aee35e037a66cfd/src/screen.rs | src/screen.rs | use anyhow::{Context, Result};
use serde::Serialize;
use std::{
fmt,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{
sync::{RwLock, broadcast},
time,
};
use crate::cli::ScreenOpts;
#[derive(Clone)]
pub struct ScreenBroadcaster {
sender: broadcast::Sender<ScreenFrame>,
latest: Arc<RwLock<Option<ScreenFrame>>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ScreenFrame {
pub frame_number: u64,
pub captured_at_ms: u128,
pub encoding: String,
pub payload: String,
}
impl fmt::Display for ScreenFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"#{frame:<5} @ {ts}ms | {}",
self.payload,
frame = self.frame_number,
ts = self.captured_at_ms
)
}
}
impl ScreenBroadcaster {
pub fn with_mock_stream(buffer: usize, fps: u8) -> Self {
let broadcaster = Self::new(buffer);
broadcaster.spawn_mock_stream(fps);
broadcaster
}
pub fn new(buffer: usize) -> Self {
let (sender, _) = broadcast::channel(buffer);
Self {
sender,
latest: Arc::new(RwLock::new(None)),
}
}
pub fn subscribe(&self) -> broadcast::Receiver<ScreenFrame> {
self.sender.subscribe()
}
pub async fn latest(&self) -> Option<ScreenFrame> {
self.latest.read().await.clone()
}
fn spawn_mock_stream(&self, fps: u8) {
let fps = fps.max(1);
let period = Duration::from_millis((1000 / fps as u64).max(1));
let mut frame_number = 0_u64;
let handle = self.clone();
tokio::spawn(async move {
let mut ticker = time::interval(period);
loop {
ticker.tick().await;
frame_number += 1;
let payload = build_ascii_frame(frame_number);
let frame = ScreenFrame {
frame_number,
captured_at_ms: current_epoch_ms(),
encoding: "text/mock".to_string(),
payload,
};
handle.publish(frame).await;
}
});
}
async fn publish(&self, frame: ScreenFrame) {
{
let mut guard = self.latest.write().await;
*guard = Some(frame.clone());
}
// Ignore lagging consumers; they'll resubscribe and catch up.
let _ = self.sender.send(frame);
}
}
pub async fn preview(opts: ScreenOpts) -> Result<()> {
let generator = ScreenBroadcaster::with_mock_stream(opts.frame_buffer, opts.fps);
let mut rx = generator.subscribe();
for _ in 0..opts.frames {
let frame = rx
.recv()
.await
.context("screen preview channel closed unexpectedly")?;
println!("{frame}");
}
Ok(())
}
fn current_epoch_ms() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|dur| dur.as_millis())
.unwrap_or(0)
}
fn build_ascii_frame(frame: u64) -> String {
const WIDTH: usize = 32;
const FILL: char = '#';
const EMPTY: char = '.';
let position = (frame as usize) % WIDTH;
let mut line = String::with_capacity(WIDTH);
for idx in 0..WIDTH {
if idx == position {
line.push(FILL);
} else {
line.push(EMPTY);
}
}
line
}
| rust | MIT | 85db313c274056cf0dbb36cc0aee35e037a66cfd | 2026-01-04T15:40:10.857433Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/test/packages/deptry_reproducer/src/lib.rs | test/packages/deptry_reproducer/src/lib.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-dev/src/generate_sysconfig_mappings.rs | crates/uv-dev/src/generate_sysconfig_mappings.rs | //! Generate sysconfig mappings for supported python-build-standalone *nix platforms.
use anstream::println;
use anyhow::{Result, bail};
use pretty_assertions::StrComparison;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fmt::Write;
use std::path::PathBuf;
use crate::ROOT_DIR;
use crate::generate_all::Mode;
/// Contains current supported targets
const TARGETS_YML_URL: &str = "https://raw.githubusercontent.com/astral-sh/python-build-standalone/refs/tags/20251217/cpython-unix/targets.yml";
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
#[derive(Debug, Deserialize)]
struct TargetConfig {
host_cc: Option<String>,
host_cxx: Option<String>,
target_cc: Option<String>,
target_cxx: Option<String>,
}
pub(crate) async fn main(args: &Args) -> Result<()> {
let reference_string = generate().await?;
let filename = "generated_mappings.rs";
let reference_path = PathBuf::from(ROOT_DIR)
.join("crates")
.join("uv-python")
.join("src")
.join("sysconfig")
.join(filename);
match args.mode {
Mode::DryRun => {
println!("{reference_string}");
}
Mode::Check => match fs_err::read_to_string(reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
let comparison = StrComparison::new(¤t, &reference_string);
bail!(
"{filename} changed, please run `cargo dev generate-sysconfig-metadata`:\n{comparison}"
);
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!("{filename} not found, please run `cargo dev generate-sysconfig-metadata`");
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-sysconfig-metadata`:\n{err}"
);
}
},
Mode::Write => match fs_err::read_to_string(&reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-sysconfig-metadata`:\n{err}"
);
}
},
}
Ok(())
}
async fn generate() -> Result<String> {
println!("Downloading python-build-standalone cpython-unix/targets.yml ...");
let body = reqwest::get(TARGETS_YML_URL).await?.text().await?;
let parsed: BTreeMap<String, TargetConfig> = serde_yaml::from_str(&body)?;
let mut replacements: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
for targets_config in parsed.values() {
for sysconfig_cc_entry in ["CC", "LDSHARED", "BLDSHARED", "LINKCC"] {
if let Some(ref from_cc) = targets_config.host_cc {
replacements
.entry(sysconfig_cc_entry)
.or_default()
.insert(from_cc.to_owned(), "cc".to_string());
}
if let Some(ref from_cc) = targets_config.target_cc {
replacements
.entry(sysconfig_cc_entry)
.or_default()
.insert(from_cc.to_owned(), "cc".to_string());
}
}
for sysconfig_cxx_entry in ["CXX", "LDCXXSHARED"] {
if let Some(ref from_cxx) = targets_config.host_cxx {
replacements
.entry(sysconfig_cxx_entry)
.or_default()
.insert(from_cxx.to_owned(), "c++".to_string());
}
if let Some(ref from_cxx) = targets_config.target_cxx {
replacements
.entry(sysconfig_cxx_entry)
.or_default()
.insert(from_cxx.to_owned(), "c++".to_string());
}
}
}
let mut output = String::new();
// Opening statements
output.push_str("//! DO NOT EDIT\n");
output.push_str("//!\n");
output.push_str("//! Generated with `cargo run dev generate-sysconfig-metadata`\n");
output.push_str("//! Targets from <https://github.com/astral-sh/python-build-standalone/blob/20251217/cpython-unix/targets.yml>\n");
output.push_str("//!\n");
// Disable clippy/fmt
output.push_str("#![allow(clippy::all)]\n");
output.push_str("#![cfg_attr(any(), rustfmt::skip)]\n\n");
// Begin main code
output.push_str("use std::collections::BTreeMap;\n");
output.push_str("use std::sync::LazyLock;\n\n");
output.push_str("use crate::sysconfig::replacements::{ReplacementEntry, ReplacementMode};\n\n");
output.push_str(
"/// Mapping for sysconfig keys to lookup and replace with the appropriate entry.\n",
);
output.push_str("pub(crate) static DEFAULT_VARIABLE_UPDATES: LazyLock<BTreeMap<String, Vec<ReplacementEntry>>> = LazyLock::new(|| {\n");
output.push_str(" BTreeMap::from_iter([\n");
// Add Replacement Entries for CC, CXX, etc.
for (key, entries) in &replacements {
writeln!(output, " (\"{key}\".to_string(), vec![")?;
for (from, to) in entries {
writeln!(
output,
" ReplacementEntry {{ mode: ReplacementMode::Partial {{ from: \"{from}\".to_string() }}, to: \"{to}\".to_string() }},"
)?;
}
writeln!(output, " ]),")?;
}
// Add AR case last
output.push_str(" (\"AR\".to_string(), vec![\n");
output.push_str(" ReplacementEntry {\n");
output.push_str(" mode: ReplacementMode::Full,\n");
output.push_str(" to: \"ar\".to_string(),\n");
output.push_str(" },\n");
output.push_str(" ]),\n");
// Closing
output.push_str(" ])\n});\n");
Ok(output)
}
#[cfg(test)]
mod tests {
use std::env;
use anyhow::Result;
use uv_static::EnvVars;
use crate::generate_all::Mode;
use super::{Args, main};
#[tokio::test]
async fn test_generate_sysconfig_mappings() -> Result<()> {
// Skip this test in CI to avoid redundancy with the dedicated CI job
if env::var_os(EnvVars::CI).is_some() {
return Ok(());
}
let mode = if env::var(EnvVars::UV_UPDATE_SCHEMA).as_deref() == Ok("1") {
Mode::Write
} else {
Mode::Check
};
main(&Args { mode }).await
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-dev/src/generate_options_reference.rs | crates/uv-dev/src/generate_options_reference.rs | //! Generate a Markdown-compatible listing of configuration options for `pyproject.toml`.
//!
//! Based on: <https://github.com/astral-sh/ruff/blob/dc8db1afb08704ad6a788c497068b01edf8b460d/crates/ruff_dev/src/generate_options.rs>
use std::fmt::Write;
use std::path::PathBuf;
use anstream::println;
use anyhow::{Result, bail};
use itertools::Itertools;
use pretty_assertions::StrComparison;
use schemars::JsonSchema;
use serde::Deserialize;
use uv_macros::OptionsMetadata;
use uv_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit};
use uv_settings::Options as SettingsOptions;
use uv_workspace::pyproject::ToolUv as WorkspaceOptions;
use crate::ROOT_DIR;
use crate::generate_all::Mode;
#[derive(Deserialize, JsonSchema, OptionsMetadata)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
// The names and docstrings of this struct and the types it contains are used as `title` and
// `description` in uv.schema.json, see https://github.com/SchemaStore/schemastore/blob/master/editor-features.md#title-as-an-expected-object-type
/// Metadata and configuration for uv.
struct CombinedOptions {
#[serde(flatten)]
options: SettingsOptions,
#[serde(flatten)]
workspace: WorkspaceOptions,
}
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
pub(crate) fn main(args: &Args) -> Result<()> {
let reference_string = generate();
let filename = "settings.md";
let reference_path = PathBuf::from(ROOT_DIR)
.join("docs")
.join("reference")
.join(filename);
match args.mode {
Mode::DryRun => {
println!("{reference_string}");
}
Mode::Check => match fs_err::read_to_string(reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
let comparison = StrComparison::new(¤t, &reference_string);
bail!(
"{filename} changed, please run `cargo dev generate-options-reference`:\n{comparison}"
);
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!("{filename} not found, please run `cargo dev generate-options-reference`");
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-options-reference`:\n{err}"
);
}
},
Mode::Write => match fs_err::read_to_string(&reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-options-reference`:\n{err}"
);
}
},
}
Ok(())
}
enum OptionType {
Configuration,
ProjectMetadata,
}
fn generate() -> String {
let mut output = String::new();
generate_set(
&mut output,
Set::Global {
set: WorkspaceOptions::metadata(),
option_type: OptionType::ProjectMetadata,
},
&mut Vec::new(),
);
generate_set(
&mut output,
Set::Global {
set: SettingsOptions::metadata(),
option_type: OptionType::Configuration,
},
&mut Vec::new(),
);
output
}
fn generate_set(output: &mut String, set: Set, parents: &mut Vec<Set>) {
match &set {
Set::Global { option_type, .. } => {
let header = match option_type {
OptionType::Configuration => "## Configuration\n",
OptionType::ProjectMetadata => "## Project metadata\n",
};
output.push_str(header);
}
Set::Named { name, .. } => {
let title = parents
.iter()
.filter_map(|set| set.name())
.chain(std::iter::once(name.as_str()))
.join(".");
writeln!(output, "### `{title}`\n").unwrap();
if let Some(documentation) = set.metadata().documentation() {
output.push_str(documentation);
output.push('\n');
output.push('\n');
}
}
}
let mut visitor = CollectOptionsVisitor::default();
set.metadata().record(&mut visitor);
let (mut fields, mut sets) = (visitor.fields, visitor.groups);
fields.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2));
sets.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2));
parents.push(set);
// Generate the fields.
for (name, field) in &fields {
emit_field(output, name, field, parents.as_slice());
output.push_str("---\n\n");
}
// Generate all the sub-sets.
for (set_name, sub_set) in &sets {
generate_set(
output,
Set::Named {
name: set_name.to_owned(),
set: *sub_set,
},
parents,
);
}
parents.pop();
}
enum Set {
Global {
option_type: OptionType,
set: OptionSet,
},
Named {
name: String,
set: OptionSet,
},
}
impl Set {
fn name(&self) -> Option<&str> {
match self {
Self::Global { .. } => None,
Self::Named { name, .. } => Some(name),
}
}
fn metadata(&self) -> &OptionSet {
match self {
Self::Global { set, .. } => set,
Self::Named { set, .. } => set,
}
}
}
#[allow(clippy::format_push_string)]
fn emit_field(output: &mut String, name: &str, field: &OptionField, parents: &[Set]) {
let header_level = if parents.len() > 1 { "####" } else { "###" };
let parents_anchor = parents.iter().filter_map(|parent| parent.name()).join("_");
if parents_anchor.is_empty() {
output.push_str(&format!(
"{header_level} [`{name}`](#{name}) {{: #{name} }}\n"
));
} else {
output.push_str(&format!(
"{header_level} [`{name}`](#{parents_anchor}_{name}) {{: #{parents_anchor}_{name} }}\n"
));
// the anchor used to just be the name, but now it's the group name
// for backwards compatibility, we need to keep the old anchor
output.push_str(&format!("<span id=\"{name}\"></span>\n"));
}
output.push('\n');
if let Some(deprecated) = &field.deprecated {
output.push_str("!!! warning \"Deprecated\"\n");
output.push_str(" This option has been deprecated");
if let Some(since) = deprecated.since {
write!(output, " in {since}").unwrap();
}
output.push('.');
if let Some(message) = deprecated.message {
writeln!(output, " {message}").unwrap();
}
output.push('\n');
}
output.push_str(field.doc);
output.push_str("\n\n");
output.push_str(&format!("**Default value**: `{}`\n", field.default));
output.push('\n');
if let Some(possible_values) = field
.possible_values
.as_ref()
.filter(|values| !values.is_empty())
{
output.push_str("**Possible values**:\n\n");
for value in possible_values {
output.push_str(format!("- {value}\n").as_str());
}
} else {
output.push_str(&format!("**Type**: `{}`\n", field.value_type));
}
output.push('\n');
output.push_str("**Example usage**:\n\n");
match parents[0] {
Set::Global {
option_type: OptionType::ProjectMetadata,
..
} => {
output.push_str(&format_code(
"pyproject.toml",
&format_header(
field.scope,
field.example,
parents,
ConfigurationFile::PyprojectToml,
),
field.example,
));
}
Set::Global {
option_type: OptionType::Configuration,
..
} => {
output.push_str(&format_tab(
"pyproject.toml",
&format_header(
field.scope,
field.example,
parents,
ConfigurationFile::PyprojectToml,
),
field.example,
));
output.push_str(&format_tab(
"uv.toml",
&format_header(
field.scope,
field.example,
parents,
ConfigurationFile::UvToml,
),
field.example,
));
}
_ => {}
}
output.push('\n');
}
fn format_tab(tab_name: &str, header: &str, content: &str) -> String {
if header.is_empty() {
format!(
"=== \"{}\"\n\n ```toml\n{}\n ```\n",
tab_name,
textwrap::indent(content, " ")
)
} else {
format!(
"=== \"{}\"\n\n ```toml\n {}\n{}\n ```\n",
tab_name,
header,
textwrap::indent(content, " ")
)
}
}
fn format_code(file_name: &str, header: &str, content: &str) -> String {
format!("```toml title=\"{file_name}\"\n{header}\n{content}\n```\n")
}
/// Format the TOML header for the example usage for a given option.
///
/// For example: `[tool.uv.pip]`.
fn format_header(
scope: Option<&str>,
example: &str,
parents: &[Set],
configuration: ConfigurationFile,
) -> String {
let tool_parent = match configuration {
ConfigurationFile::PyprojectToml => Some("tool.uv"),
ConfigurationFile::UvToml => None,
};
let header = tool_parent
.into_iter()
.chain(parents.iter().filter_map(|parent| parent.name()))
.chain(scope)
.join(".");
// Ex) `[[tool.uv.index]]`
if example.starts_with(&format!("[[{header}")) {
return String::new();
}
// Ex) `[tool.uv.sources]`
if example.starts_with(&format!("[{header}")) {
return String::new();
}
if header.is_empty() {
String::new()
} else {
format!("[{header}]")
}
}
#[derive(Debug, Copy, Clone)]
enum ConfigurationFile {
PyprojectToml,
UvToml,
}
#[derive(Default)]
struct CollectOptionsVisitor {
groups: Vec<(String, OptionSet)>,
fields: Vec<(String, OptionField)>,
}
impl Visit for CollectOptionsVisitor {
fn record_set(&mut self, name: &str, group: OptionSet) {
self.groups.push((name.to_owned(), group));
}
fn record_field(&mut self, name: &str, field: OptionField) {
self.fields.push((name.to_owned(), field));
}
}
| 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-dev/src/clear_compile.rs | crates/uv-dev/src/clear_compile.rs | use std::path::PathBuf;
use clap::Parser;
use tracing::info;
use walkdir::WalkDir;
#[derive(Parser)]
pub(crate) struct ClearCompileArgs {
/// Compile all `.py` in this or any subdirectory to bytecode
root: PathBuf,
}
pub(crate) fn clear_compile(args: &ClearCompileArgs) -> anyhow::Result<()> {
let mut removed_files = 0;
let mut removed_directories = 0;
for entry in WalkDir::new(&args.root).contents_first(true) {
let entry = entry?;
let metadata = entry.metadata()?;
if metadata.is_file() {
if entry.path().extension().is_some_and(|ext| ext == "pyc") {
fs_err::remove_file(entry.path())?;
removed_files += 1;
}
} else if metadata.is_dir() {
if entry.file_name() == "__pycache__" {
fs_err::remove_dir(entry.path())?;
removed_directories += 1;
}
}
}
info!("Removed {removed_files} files and {removed_directories} directories");
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-dev/src/lib.rs | crates/uv-dev/src/lib.rs | use std::env;
use anyhow::Result;
use clap::Parser;
use tracing::instrument;
use uv_settings::EnvironmentOptions;
use crate::clear_compile::ClearCompileArgs;
use crate::compile::CompileArgs;
use crate::generate_all::Args as GenerateAllArgs;
use crate::generate_cli_reference::Args as GenerateCliReferenceArgs;
use crate::generate_env_vars_reference::Args as GenerateEnvVarsReferenceArgs;
use crate::generate_json_schema::Args as GenerateJsonSchemaArgs;
use crate::generate_options_reference::Args as GenerateOptionsReferenceArgs;
use crate::generate_sysconfig_mappings::Args as GenerateSysconfigMetadataArgs;
use crate::list_packages::ListPackagesArgs;
#[cfg(feature = "render")]
use crate::render_benchmarks::RenderBenchmarksArgs;
use crate::validate_zip::ValidateZipArgs;
use crate::wheel_metadata::WheelMetadataArgs;
mod clear_compile;
mod compile;
mod generate_all;
mod generate_cli_reference;
mod generate_env_vars_reference;
mod generate_json_schema;
mod generate_options_reference;
mod generate_sysconfig_mappings;
mod list_packages;
mod render_benchmarks;
mod validate_zip;
mod wheel_metadata;
const ROOT_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../");
#[derive(Parser)]
enum Cli {
/// Display the metadata for a `.whl` at a given URL.
WheelMetadata(WheelMetadataArgs),
/// Validate that a `.whl` or `.zip` file at a given URL is a valid ZIP file.
ValidateZip(ValidateZipArgs),
/// Compile all `.py` to `.pyc` files in the tree.
Compile(CompileArgs),
/// Remove all `.pyc` in the tree.
ClearCompile(ClearCompileArgs),
/// List all packages from a Simple API index.
ListPackages(ListPackagesArgs),
/// Run all code and documentation generation steps.
GenerateAll(GenerateAllArgs),
/// Generate JSON schema for the TOML configuration file.
GenerateJSONSchema(GenerateJsonSchemaArgs),
/// Generate the options reference for the documentation.
GenerateOptionsReference(GenerateOptionsReferenceArgs),
/// Generate the CLI reference for the documentation.
GenerateCliReference(GenerateCliReferenceArgs),
/// Generate the environment variables reference for the documentation.
GenerateEnvVarsReference(GenerateEnvVarsReferenceArgs),
/// Generate the sysconfig metadata from derived targets.
GenerateSysconfigMetadata(GenerateSysconfigMetadataArgs),
#[cfg(feature = "render")]
/// Render the benchmarks.
RenderBenchmarks(RenderBenchmarksArgs),
}
#[instrument] // Anchor span to check for overhead
pub async fn run() -> Result<()> {
let cli = Cli::parse();
let environment = EnvironmentOptions::new()?;
match cli {
Cli::WheelMetadata(args) => wheel_metadata::wheel_metadata(args, environment).await?,
Cli::ValidateZip(args) => validate_zip::validate_zip(args, environment).await?,
Cli::Compile(args) => compile::compile(args).await?,
Cli::ClearCompile(args) => clear_compile::clear_compile(&args)?,
Cli::ListPackages(args) => list_packages::list_packages(args, environment).await?,
Cli::GenerateAll(args) => generate_all::main(&args).await?,
Cli::GenerateJSONSchema(args) => generate_json_schema::main(&args)?,
Cli::GenerateOptionsReference(args) => generate_options_reference::main(&args)?,
Cli::GenerateCliReference(args) => generate_cli_reference::main(&args)?,
Cli::GenerateEnvVarsReference(args) => generate_env_vars_reference::main(&args)?,
Cli::GenerateSysconfigMetadata(args) => generate_sysconfig_mappings::main(&args).await?,
#[cfg(feature = "render")]
Cli::RenderBenchmarks(args) => render_benchmarks::render_benchmarks(&args)?,
}
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-dev/src/generate_all.rs | crates/uv-dev/src/generate_all.rs | //! Run all code and documentation generation steps.
use anyhow::Result;
use crate::{
generate_cli_reference, generate_env_vars_reference, generate_json_schema,
generate_options_reference, generate_sysconfig_mappings,
};
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
mode: Mode,
}
#[derive(Copy, Clone, PartialEq, Eq, clap::ValueEnum, Default)]
pub(crate) enum Mode {
/// Update the content in the `configuration.md`.
#[default]
Write,
/// Don't write to the file, check if the file is up-to-date and error if not.
Check,
/// Write the generated help to stdout.
DryRun,
}
pub(crate) async fn main(args: &Args) -> Result<()> {
generate_json_schema::main(&generate_json_schema::Args { mode: args.mode })?;
generate_options_reference::main(&generate_options_reference::Args { mode: args.mode })?;
generate_cli_reference::main(&generate_cli_reference::Args { mode: args.mode })?;
generate_env_vars_reference::main(&generate_env_vars_reference::Args { mode: args.mode })?;
generate_sysconfig_mappings::main(&generate_sysconfig_mappings::Args { mode: args.mode })
.await?;
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-dev/src/compile.rs | crates/uv-dev/src/compile.rs | use std::path::PathBuf;
use clap::Parser;
use tracing::info;
use uv_cache::{Cache, CacheArgs};
use uv_configuration::Concurrency;
use uv_preview::Preview;
use uv_python::{EnvironmentPreference, PythonEnvironment, PythonPreference, PythonRequest};
#[derive(Parser)]
pub(crate) struct CompileArgs {
/// Compile all `.py` in this or any subdirectory to bytecode
root: PathBuf,
python: Option<PathBuf>,
#[command(flatten)]
cache_args: CacheArgs,
}
pub(crate) async fn compile(args: CompileArgs) -> anyhow::Result<()> {
let cache = Cache::try_from(args.cache_args)?.init().await?;
let interpreter = if let Some(python) = args.python {
python
} else {
let interpreter = PythonEnvironment::find(
&PythonRequest::default(),
EnvironmentPreference::OnlyVirtual,
PythonPreference::default(),
&cache,
Preview::default(),
)?
.into_interpreter();
interpreter.sys_executable().to_path_buf()
};
let files = uv_installer::compile_tree(
&fs_err::canonicalize(args.root)?,
&interpreter,
&Concurrency::default(),
cache.root(),
)
.await?;
info!("Compiled {files} files");
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-dev/src/list_packages.rs | crates/uv-dev/src/list_packages.rs | use anstream::println;
use anyhow::Result;
use clap::Parser;
use uv_cache::{Cache, CacheArgs};
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
use uv_distribution_types::IndexUrl;
use uv_settings::EnvironmentOptions;
#[derive(Parser)]
pub(crate) struct ListPackagesArgs {
/// The Simple API index URL (e.g., <https://pypi.org/simple>/)
url: String,
#[command(flatten)]
cache_args: CacheArgs,
}
pub(crate) async fn list_packages(
args: ListPackagesArgs,
environment: EnvironmentOptions,
) -> Result<()> {
let cache = Cache::try_from(args.cache_args)?.init().await?;
let client = RegistryClientBuilder::new(
BaseClientBuilder::default().timeout(environment.http_timeout),
cache,
)
.build();
let index_url = IndexUrl::parse(&args.url, None)?;
let index = client.fetch_simple_index(&index_url).await?;
for package_name in index.iter() {
println!("{}", package_name);
}
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-dev/src/render_benchmarks.rs | crates/uv-dev/src/render_benchmarks.rs | #![cfg(feature = "render")]
use std::path::{Path, PathBuf};
use anyhow::{Result, anyhow};
use clap::Parser;
use poloto::build;
use resvg::usvg_text_layout::{TreeTextToPath, fontdb};
use serde::Deserialize;
use tagu::prelude::*;
#[derive(Parser)]
pub(crate) struct RenderBenchmarksArgs {
/// Path to a JSON output from a `hyperfine` benchmark.
path: PathBuf,
/// Title of the plot.
#[clap(long, short)]
title: Option<String>,
}
pub(crate) fn render_benchmarks(args: &RenderBenchmarksArgs) -> Result<()> {
let mut results: BenchmarkResults = serde_json::from_slice(&fs_err::read(&args.path)?)?;
// Replace the command with a shorter name. (The command typically includes the benchmark name,
// but we assume we're running over a single benchmark here.)
for result in &mut results.results {
if result.command.starts_with("uv") {
result.command = "uv".into();
} else if result.command.starts_with("pip-compile") {
result.command = "pip-compile".into();
} else if result.command.starts_with("pip-sync") {
result.command = "pip-sync".into();
} else if result.command.starts_with("poetry") {
result.command = "Poetry".into();
} else if result.command.starts_with("pdm") {
result.command = "PDM".into();
} else {
return Err(anyhow!("unknown command: {}", result.command));
}
}
let fontdb = load_fonts();
render_to_png(
&plot_benchmark(args.title.as_deref().unwrap_or("Benchmark"), &results)?,
&args.path.with_extension("png"),
&fontdb,
)?;
Ok(())
}
/// Render a benchmark to an SVG (as a string).
fn plot_benchmark(heading: &str, results: &BenchmarkResults) -> Result<String> {
let mut data = Vec::new();
for result in &results.results {
data.push((result.mean, &result.command));
}
let theme = poloto::render::Theme::light();
let theme = theme.append(tagu::build::raw(
".poloto0.poloto_fill{fill: #6340AC !important;}",
));
let theme = theme.append(tagu::build::raw(
".poloto_background{fill: white !important;}",
));
Ok(build::bar::gen_simple("", data, [0.0])
.label((heading, "Time (s)", ""))
.append_to(poloto::header().append(theme))
.render_string()?)
}
/// Render an SVG to a PNG file.
fn render_to_png(data: &str, path: &Path, fontdb: &fontdb::Database) -> Result<()> {
let mut tree = resvg::usvg::Tree::from_str(data, &resvg::usvg::Options::default())?;
tree.convert_text(fontdb);
let fit_to = resvg::usvg::FitTo::Width(1600);
let size = fit_to
.fit_to(tree.size.to_screen_size())
.ok_or_else(|| anyhow!("failed to fit to screen size"))?;
let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height()).unwrap();
resvg::render(
&tree,
fit_to,
resvg::tiny_skia::Transform::default(),
pixmap.as_mut(),
)
.ok_or_else(|| anyhow!("failed to render"))?;
fs_err::create_dir_all(path.parent().unwrap())?;
pixmap.save_png(path)?;
Ok(())
}
/// Load the system fonts and set the default font families.
fn load_fonts() -> fontdb::Database {
let mut fontdb = fontdb::Database::new();
fontdb.load_system_fonts();
fontdb.set_serif_family("Times New Roman");
fontdb.set_sans_serif_family("Arial");
fontdb.set_cursive_family("Comic Sans MS");
fontdb.set_fantasy_family("Impact");
fontdb.set_monospace_family("Courier New");
fontdb
}
#[derive(Debug, Deserialize)]
struct BenchmarkResults {
results: Vec<BenchmarkResult>,
}
#[derive(Debug, Deserialize)]
struct BenchmarkResult {
command: String,
mean: f64,
}
| 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-dev/src/generate_json_schema.rs | crates/uv-dev/src/generate_json_schema.rs | use std::path::PathBuf;
use anstream::println;
use anyhow::{Result, bail};
use pretty_assertions::StrComparison;
use schemars::JsonSchema;
use serde::Deserialize;
use uv_settings::Options as SettingsOptions;
use uv_workspace::pyproject::ToolUv as WorkspaceOptions;
use crate::ROOT_DIR;
use crate::generate_all::Mode;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
// The names and docstrings of this struct and the types it contains are used as `title` and
// `description` in uv.schema.json, see https://github.com/SchemaStore/schemastore/blob/master/editor-features.md#title-as-an-expected-object-type
/// Metadata and configuration for uv.
struct CombinedOptions {
#[serde(flatten)]
options: SettingsOptions,
#[serde(flatten)]
workspace: WorkspaceOptions,
}
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
pub(crate) fn main(args: &Args) -> Result<()> {
// Generate the schema.
let schema_string = generate();
let filename = "uv.schema.json";
let schema_path = PathBuf::from(ROOT_DIR).join(filename);
match args.mode {
Mode::DryRun => {
println!("{schema_string}");
}
Mode::Check => match fs_err::read_to_string(schema_path) {
Ok(current) => {
if current == schema_string {
println!("Up-to-date: {filename}");
} else {
let comparison = StrComparison::new(¤t, &schema_string);
bail!(
"{filename} changed, please run `cargo dev generate-json-schema`:\n{comparison}"
);
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!("{filename} not found, please run `cargo dev generate-json-schema`");
}
Err(err) => {
bail!("{filename} changed, please run `cargo dev generate-json-schema`:\n{err}");
}
},
Mode::Write => match fs_err::read_to_string(&schema_path) {
Ok(current) => {
if current == schema_string {
println!("Up-to-date: {filename}");
} else {
println!("Updating: {filename}");
fs_err::write(schema_path, schema_string.as_bytes())?;
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!("Updating: {filename}");
fs_err::write(schema_path, schema_string.as_bytes())?;
}
Err(err) => {
bail!("{filename} changed, please run `cargo dev generate-json-schema`:\n{err}");
}
},
}
Ok(())
}
const REPLACEMENTS: &[(&str, &str)] = &[
// Use the fully-resolved URL rather than the relative Markdown path.
(
"(../concepts/projects/dependencies.md)",
"(https://docs.astral.sh/uv/concepts/projects/dependencies/)",
),
];
/// Generate the JSON schema for the combined options as a string.
fn generate() -> String {
let settings = schemars::generate::SchemaSettings::draft07();
let generator = schemars::SchemaGenerator::new(settings);
let schema = generator.into_root_schema_for::<CombinedOptions>();
let mut output = serde_json::to_string_pretty(&schema).unwrap();
for (value, replacement) in REPLACEMENTS {
assert_ne!(
value, replacement,
"`value` and `replacement` must be different, but both are `{value}`"
);
let before = &output;
let after = output.replace(value, replacement);
assert_ne!(*before, after, "Could not find `{value}` in the output");
output = after;
}
output
}
#[cfg(test)]
mod tests {
use std::env;
use anyhow::Result;
use uv_static::EnvVars;
use crate::generate_all::Mode;
use super::{Args, main};
#[test]
fn test_generate_json_schema() -> Result<()> {
// Skip this test in CI to avoid redundancy with the dedicated CI job
if env::var_os(EnvVars::CI).is_some() {
return Ok(());
}
let mode = if env::var(EnvVars::UV_UPDATE_SCHEMA).as_deref() == Ok("1") {
Mode::Write
} else {
Mode::Check
};
main(&Args { mode })
}
}
| 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-dev/src/validate_zip.rs | crates/uv-dev/src/validate_zip.rs | use std::ops::Deref;
use anyhow::{Result, bail};
use clap::Parser;
use futures::TryStreamExt;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use uv_cache::{Cache, CacheArgs};
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
use uv_pep508::VerbatimUrl;
use uv_pypi_types::ParsedUrl;
use uv_settings::EnvironmentOptions;
#[derive(Parser)]
pub(crate) struct ValidateZipArgs {
url: VerbatimUrl,
#[command(flatten)]
cache_args: CacheArgs,
}
pub(crate) async fn validate_zip(
args: ValidateZipArgs,
environment: EnvironmentOptions,
) -> Result<()> {
let cache = Cache::try_from(args.cache_args)?.init().await?;
let client = RegistryClientBuilder::new(
BaseClientBuilder::default().timeout(environment.http_timeout),
cache,
)
.build();
let ParsedUrl::Archive(archive) = ParsedUrl::try_from(args.url.to_url())? else {
bail!("Only archive URLs are supported");
};
let response = client
.uncached_client(&archive.url)
.get(archive.url.deref().clone())
.send()
.await?;
let reader = response
.bytes_stream()
.map_err(std::io::Error::other)
.into_async_read();
let target = tempfile::TempDir::new()?;
uv_extract::stream::unzip(reader.compat(), target.path()).await?;
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-dev/src/main.rs | crates/uv-dev/src/main.rs | use std::env;
use std::path::PathBuf;
use std::process::ExitCode;
use std::str::FromStr;
use std::time::Instant;
use anstream::eprintln;
use owo_colors::OwoColorize;
use tracing::{debug, trace};
use tracing_durations_export::DurationsLayerBuilder;
use tracing_durations_export::plot::PlotConfig;
use tracing_subscriber::filter::Directive;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
use uv_dev::run;
use uv_static::EnvVars;
#[tokio::main(flavor = "current_thread")]
async fn main() -> ExitCode {
let (duration_layer, _guard) = if let Ok(location) = env::var(EnvVars::TRACING_DURATIONS_FILE) {
let location = PathBuf::from(location);
if let Some(parent) = location.parent() {
fs_err::tokio::create_dir_all(&parent)
.await
.expect("Failed to create parent of TRACING_DURATIONS_FILE");
}
let plot_config = PlotConfig {
multi_lane: true,
min_length: None,
remove: Some(
["get_cached_with_callback".to_string()]
.into_iter()
.collect(),
),
..PlotConfig::default()
};
let (layer, guard) = DurationsLayerBuilder::default()
.durations_file(&location)
.plot_file(location.with_extension("svg"))
.plot_config(plot_config)
.build()
.expect("Couldn't create TRACING_DURATIONS_FILE files");
(Some(layer), Some(guard))
} else {
(None, None)
};
// Show `INFO` messages from the uv crate, but allow `RUST_LOG` to override.
let default_directive = Directive::from_str("uv=info").unwrap();
let filter = EnvFilter::builder()
.with_default_directive(default_directive)
.from_env()
.expect("Valid RUST_LOG directives");
tracing_subscriber::registry()
.with(duration_layer)
.with(
tracing_subscriber::fmt::layer()
.with_writer(std::io::stderr)
.with_filter(filter),
)
.init();
let start = Instant::now();
let result = run().await;
debug!("Took {}ms", start.elapsed().as_millis());
if let Err(err) = result {
trace!("Error trace: {err:?}");
eprintln!("{}", "uv-dev failed".red().bold());
for err in err.chain() {
eprintln!(" {}: {}", "Caused by".red().bold(), err.to_string().trim());
}
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
| 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-dev/src/generate_cli_reference.rs | crates/uv-dev/src/generate_cli_reference.rs | //! Generate a Markdown-compatible reference for the uv command-line interface.
use std::cmp::max;
use std::path::PathBuf;
use anstream::println;
use anyhow::{Result, bail};
use clap::{Command, CommandFactory};
use itertools::Itertools;
use pretty_assertions::StrComparison;
use crate::ROOT_DIR;
use crate::generate_all::Mode;
use uv_cli::Cli;
const REPLACEMENTS: &[(&str, &str)] = &[
// Replace suggestions to use `uv help python` with a link to the
// `uv python` section
(
"<code>uv help python</code>",
"<a href=\"#uv-python\">uv python</a>",
),
// Drop the manually included `env` section for `--no-python-downloads`
// TODO(zanieb): In general, we should show all of the environment variables in the reference
// but this one is non-standard so it's the only one included right now. When we tackle the rest
// we can fix the formatting.
(" [env: "UV_PYTHON_DOWNLOADS=never"]", ""),
];
const SHOW_HIDDEN_COMMANDS: &[&str] = &["generate-shell-completion"];
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
pub(crate) fn main(args: &Args) -> Result<()> {
let reference_string = generate();
let filename = "cli.md";
let reference_path = PathBuf::from(ROOT_DIR)
.join("docs")
.join("reference")
.join(filename);
match args.mode {
Mode::DryRun => {
println!("{reference_string}");
}
Mode::Check => match fs_err::read_to_string(reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
let comparison = StrComparison::new(¤t, &reference_string);
bail!(
"{filename} changed, please run `cargo dev generate-cli-reference`:\n{comparison}"
);
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!("{filename} not found, please run `cargo dev generate-cli-reference`");
}
Err(err) => {
bail!("{filename} changed, please run `cargo dev generate-cli-reference`:\n{err}");
}
},
Mode::Write => match fs_err::read_to_string(&reference_path) {
Ok(current) => {
if current == reference_string {
println!("Up-to-date: {filename}");
} else {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
Err(err) => {
bail!("{filename} changed, please run `cargo dev generate-cli-reference`:\n{err}");
}
},
}
Ok(())
}
fn generate() -> String {
let mut output = String::new();
let mut uv = Cli::command();
// It is very important to build the command before beginning inspection or subcommands
// will be missing all of the propagated options.
uv.build();
let mut parents = Vec::new();
output.push_str("# CLI Reference\n\n");
generate_command(&mut output, &uv, &mut parents);
for (value, replacement) in REPLACEMENTS {
assert_ne!(
value, replacement,
"`value` and `replacement` must be different, but both are `{value}`"
);
let before = &output;
let after = output.replace(value, replacement);
assert_ne!(*before, after, "Could not find `{value}` in the output");
output = after;
}
output
}
#[allow(clippy::format_push_string)]
fn generate_command<'a>(output: &mut String, command: &'a Command, parents: &mut Vec<&'a Command>) {
if command.is_hide_set() && !SHOW_HIDDEN_COMMANDS.contains(&command.get_name()) {
return;
}
// Generate the command header.
let name = if parents.is_empty() {
command.get_name().to_string()
} else {
format!(
"{} {}",
parents.iter().map(|cmd| cmd.get_name()).join(" "),
command.get_name()
)
};
// Display the top-level `uv` command at the same level as its children
let level = max(2, parents.len() + 1);
output.push_str(&format!("{} {name}\n\n", "#".repeat(level)));
// Display the command description.
if let Some(about) = command.get_long_about().or_else(|| command.get_about()) {
output.push_str(&about.to_string());
output.push_str("\n\n");
}
// Display the usage
{
// This appears to be the simplest way to get rendered usage from Clap,
// it is complicated to render it manually. It's annoying that it
// requires a mutable reference but it doesn't really matter.
let mut command = command.clone();
output.push_str("<h3 class=\"cli-reference\">Usage</h3>\n\n");
output.push_str(&format!(
"```\n{}\n```",
command
.render_usage()
.to_string()
.trim_start_matches("Usage: "),
));
output.push_str("\n\n");
}
// Display a list of child commands
let mut subcommands = command.get_subcommands().peekable();
let has_subcommands = subcommands.peek().is_some();
if has_subcommands {
output.push_str("<h3 class=\"cli-reference\">Commands</h3>\n\n");
output.push_str("<dl class=\"cli-reference\">");
for subcommand in subcommands {
if subcommand.is_hide_set() {
continue;
}
let subcommand_name = format!("{name} {}", subcommand.get_name());
output.push_str(&format!(
"<dt><a href=\"#{}\"><code>{subcommand_name}</code></a></dt>",
subcommand_name.replace(' ', "-")
));
if let Some(about) = subcommand.get_about() {
output.push_str(&format!(
"<dd>{}</dd>\n",
markdown::to_html(&about.to_string())
));
}
}
output.push_str("</dl>\n\n");
}
// Do not display options for commands with children
if !has_subcommands {
let name_key = name.replace(' ', "-");
// Display positional arguments
let mut arguments = command
.get_positionals()
.filter(|arg| !arg.is_hide_set())
.peekable();
if arguments.peek().is_some() {
output.push_str("<h3 class=\"cli-reference\">Arguments</h3>\n\n");
output.push_str("<dl class=\"cli-reference\">");
for arg in arguments {
let id = format!("{name_key}--{}", arg.get_id());
output.push_str(&format!("<dt id=\"{id}\">"));
output.push_str(&format!(
"<a href=\"#{id}\"<code>{}</code></a>",
arg.get_id().to_string().to_uppercase(),
));
output.push_str("</dt>");
if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) {
output.push_str("<dd>");
output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
output.push_str("</dd>");
}
}
output.push_str("</dl>\n\n");
}
// Display options and flags
let mut options = command
.get_arguments()
.filter(|arg| !arg.is_positional())
.filter(|arg| !arg.is_hide_set())
.sorted_by_key(|arg| arg.get_id())
.peekable();
if options.peek().is_some() {
output.push_str("<h3 class=\"cli-reference\">Options</h3>\n\n");
output.push_str("<dl class=\"cli-reference\">");
for opt in options {
let Some(long) = opt.get_long() else { continue };
let id = format!("{name_key}--{long}");
output.push_str(&format!("<dt id=\"{id}\">"));
output.push_str(&format!("<a href=\"#{id}\"><code>--{long}</code></a>"));
for long_alias in opt.get_all_aliases().into_iter().flatten() {
output.push_str(&format!(", <code>--{long_alias}</code>"));
}
if let Some(short) = opt.get_short() {
output.push_str(&format!(", <code>-{short}</code>"));
}
for short_alias in opt.get_all_short_aliases().into_iter().flatten() {
output.push_str(&format!(", <code>-{short_alias}</code>"));
}
// Re-implements private `Arg::is_takes_value_set` used in `Command::get_opts`
if opt
.get_num_args()
.unwrap_or_else(|| 1.into())
.takes_values()
{
if let Some(values) = opt.get_value_names() {
for value in values {
output.push_str(&format!(
" <i>{}</i>",
value.to_lowercase().replace('_', "-")
));
}
}
}
output.push_str("</dt>");
if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) {
output.push_str("<dd>");
output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
emit_env_option(opt, output);
emit_default_option(opt, output);
emit_possible_options(opt, output);
output.push_str("</dd>");
}
}
output.push_str("</dl>");
}
output.push_str("\n\n");
}
parents.push(command);
// Recurse to all of the subcommands.
for subcommand in command.get_subcommands() {
generate_command(output, subcommand, parents);
}
parents.pop();
}
fn emit_env_option(opt: &clap::Arg, output: &mut String) {
if opt.is_hide_env_set() {
return;
}
if let Some(env) = opt.get_env() {
output.push_str(&markdown::to_html(&format!(
"May also be set with the `{}` environment variable.",
env.to_string_lossy()
)));
}
}
fn emit_default_option(opt: &clap::Arg, output: &mut String) {
if opt.is_hide_default_value_set() || !opt.get_num_args().expect("built").takes_values() {
return;
}
let values = opt.get_default_values();
if !values.is_empty() {
let value = format!(
"\n[default: {}]",
opt.get_default_values()
.iter()
.map(|s| s.to_string_lossy())
.join(",")
);
output.push_str(&markdown::to_html(&value));
}
}
fn emit_possible_options(opt: &clap::Arg, output: &mut String) {
if opt.is_hide_possible_values_set() {
return;
}
let values = opt.get_possible_values();
if !values.is_empty() {
let value = format!(
"\nPossible values:\n{}",
values
.into_iter()
.filter(|value| !value.is_hide_set())
.map(|value| {
let name = value.get_name();
value.get_help().map_or_else(
|| format!(" - `{name}`"),
|help| format!(" - `{name}`: {help}"),
)
})
.collect_vec()
.join("\n"),
);
output.push_str(&markdown::to_html(&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-dev/src/wheel_metadata.rs | crates/uv-dev/src/wheel_metadata.rs | use std::str::FromStr;
use anstream::println;
use anyhow::{Result, bail};
use clap::Parser;
use uv_cache::{Cache, CacheArgs};
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{BuiltDist, DirectUrlBuiltDist, IndexCapabilities, RemoteSource};
use uv_pep508::VerbatimUrl;
use uv_pypi_types::ParsedUrl;
use uv_settings::EnvironmentOptions;
#[derive(Parser)]
pub(crate) struct WheelMetadataArgs {
url: VerbatimUrl,
#[command(flatten)]
cache_args: CacheArgs,
}
pub(crate) async fn wheel_metadata(
args: WheelMetadataArgs,
environment: EnvironmentOptions,
) -> Result<()> {
let cache = Cache::try_from(args.cache_args)?.init().await?;
let client = RegistryClientBuilder::new(
BaseClientBuilder::default().timeout(environment.http_timeout),
cache,
)
.build();
let capabilities = IndexCapabilities::default();
let filename = WheelFilename::from_str(&args.url.filename()?)?;
let ParsedUrl::Archive(archive) = ParsedUrl::try_from(args.url.to_url())? else {
bail!("Only HTTPS is supported");
};
let metadata = client
.wheel_metadata(
&BuiltDist::DirectUrl(DirectUrlBuiltDist {
filename,
location: Box::new(archive.url),
url: args.url,
}),
&capabilities,
)
.await?;
println!("{metadata:?}");
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-dev/src/generate_env_vars_reference.rs | crates/uv-dev/src/generate_env_vars_reference.rs | //! Generate the environment variables reference from `uv_static::EnvVars`.
use anyhow::bail;
use pretty_assertions::StrComparison;
use std::collections::BTreeSet;
use std::path::PathBuf;
use uv_static::EnvVars;
use crate::ROOT_DIR;
use crate::generate_all::Mode;
#[derive(clap::Args)]
pub(crate) struct Args {
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
pub(crate) fn main(args: &Args) -> anyhow::Result<()> {
let reference_string = generate();
let filename = "environment.md";
let reference_path = PathBuf::from(ROOT_DIR)
.join("docs")
.join("reference")
.join(filename);
match args.mode {
Mode::DryRun => {
anstream::println!("{reference_string}");
}
Mode::Check => match fs_err::read_to_string(reference_path) {
Ok(current) => {
if current == reference_string {
anstream::println!("Up-to-date: {filename}");
} else {
let comparison = StrComparison::new(¤t, &reference_string);
bail!(
"{filename} changed, please run `cargo dev generate-env-vars-reference`:\n{comparison}"
);
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!("{filename} not found, please run `cargo dev generate-env-vars-reference`");
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-env-vars-reference`:\n{err}"
);
}
},
Mode::Write => match fs_err::read_to_string(&reference_path) {
Ok(current) => {
if current == reference_string {
anstream::println!("Up-to-date: {filename}");
} else {
anstream::println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
anstream::println!("Updating: {filename}");
fs_err::write(reference_path, reference_string.as_bytes())?;
}
Err(err) => {
bail!(
"{filename} changed, please run `cargo dev generate-env-vars-reference`:\n{err}"
);
}
},
}
Ok(())
}
fn generate() -> String {
let mut output = String::new();
output.push_str("# Environment variables\n\n");
// Partition and sort environment variables into UV_ and external variables.
let (uv_vars, external_vars): (BTreeSet<_>, BTreeSet<_>) = EnvVars::metadata()
.iter()
.partition(|(var, _, _)| var.starts_with("UV_"));
output.push_str("uv defines and respects the following environment variables:\n\n");
for (var, doc, added_in) in uv_vars {
output.push_str(&render(var, doc, added_in));
}
output.push_str("\n\n## Externally defined variables\n\n");
output.push_str("uv also reads the following externally defined environment variables:\n\n");
for (var, doc, added_in) in external_vars {
output.push_str(&render(var, doc, added_in));
}
output
}
/// Render an environment variable and its documentation.
fn render(var: &str, doc: &str, added_in: Option<&str>) -> String {
if let Some(added_in) = added_in {
format!("### `{var}`\n<small class=\"added-in\">added in `{added_in}`</small>\n\n{doc}\n\n")
} else {
format!("### `{var}`\n\n{doc}\n\n")
}
}
| 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-normalize/src/lib.rs | crates/uv-normalize/src/lib.rs | use std::error::Error;
use std::fmt::{Display, Formatter};
pub use dist_info_name::DistInfoName;
pub use extra_name::{DefaultExtras, ExtraName};
pub use group_name::{DEV_DEPENDENCIES, DefaultGroups, GroupName, PipGroupName};
pub use package_name::PackageName;
use uv_small_str::SmallString;
mod dist_info_name;
mod extra_name;
mod group_name;
mod package_name;
/// Validate and normalize an unowned package or extra name.
pub(crate) fn validate_and_normalize_ref(
name: impl AsRef<str>,
) -> Result<SmallString, InvalidNameError> {
let name = name.as_ref();
if is_normalized(name)? {
Ok(SmallString::from(name))
} else {
Ok(SmallString::from(normalize(name)?))
}
}
/// Normalize an unowned package or extra name.
fn normalize(name: &str) -> Result<String, InvalidNameError> {
let mut normalized = String::with_capacity(name.len());
let mut last = None;
for char in name.bytes() {
match char {
b'A'..=b'Z' => {
normalized.push(char.to_ascii_lowercase() as char);
}
b'a'..=b'z' | b'0'..=b'9' => {
normalized.push(char as char);
}
b'-' | b'_' | b'.' => {
match last {
// Names can't start with punctuation.
None => return Err(InvalidNameError(name.to_string())),
Some(b'-' | b'_' | b'.') => {}
Some(_) => normalized.push('-'),
}
}
_ => return Err(InvalidNameError(name.to_string())),
}
last = Some(char);
}
// Names can't end with punctuation.
if matches!(last, Some(b'-' | b'_' | b'.')) {
return Err(InvalidNameError(name.to_string()));
}
Ok(normalized)
}
/// Returns `true` if the name is already normalized.
fn is_normalized(name: impl AsRef<str>) -> Result<bool, InvalidNameError> {
let mut last = None;
for char in name.as_ref().bytes() {
match char {
b'A'..=b'Z' => {
// Uppercase characters need to be converted to lowercase.
return Ok(false);
}
b'a'..=b'z' | b'0'..=b'9' => {}
b'_' | b'.' => {
// `_` and `.` are normalized to `-`.
return Ok(false);
}
b'-' => {
match last {
// Names can't start with punctuation.
None => return Err(InvalidNameError(name.as_ref().to_string())),
Some(b'-') => {
// Runs of `-` are normalized to a single `-`.
return Ok(false);
}
Some(_) => {}
}
}
_ => return Err(InvalidNameError(name.as_ref().to_string())),
}
last = Some(char);
}
// Names can't end with punctuation.
if matches!(last, Some(b'-' | b'_' | b'.')) {
return Err(InvalidNameError(name.as_ref().to_string()));
}
Ok(true)
}
/// Invalid [`PackageName`] or [`ExtraName`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvalidNameError(String);
impl InvalidNameError {
/// Returns the invalid name.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for InvalidNameError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Not a valid package or extra name: \"{}\". Names must start and end with a letter or \
digit and may only contain -, _, ., and alphanumeric characters.",
self.0
)
}
}
impl Error for InvalidNameError {}
/// Path didn't end with `pyproject.toml`
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvalidPipGroupPathError(String);
impl InvalidPipGroupPathError {
/// Returns the invalid path.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for InvalidPipGroupPathError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"The `--group` path is required to end in 'pyproject.toml' for compatibility with pip; got: {}",
self.0,
)
}
}
impl Error for InvalidPipGroupPathError {}
/// Possible errors from reading a [`PipGroupName`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InvalidPipGroupError {
Name(InvalidNameError),
Path(InvalidPipGroupPathError),
}
impl Display for InvalidPipGroupError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Name(e) => e.fmt(f),
Self::Path(e) => e.fmt(f),
}
}
}
impl Error for InvalidPipGroupError {}
impl From<InvalidNameError> for InvalidPipGroupError {
fn from(value: InvalidNameError) -> Self {
Self::Name(value)
}
}
impl From<InvalidPipGroupPathError> for InvalidPipGroupError {
fn from(value: InvalidPipGroupPathError) -> Self {
Self::Path(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize() {
let inputs = [
"friendly-bard",
"Friendly-Bard",
"FRIENDLY-BARD",
"friendly.bard",
"friendly_bard",
"friendly--bard",
"friendly-.bard",
"FrIeNdLy-._.-bArD",
];
for input in inputs {
assert_eq!(
validate_and_normalize_ref(input).unwrap().as_ref(),
"friendly-bard"
);
}
}
#[test]
fn check() {
let inputs = ["friendly-bard", "friendlybard"];
for input in inputs {
assert!(is_normalized(input).unwrap(), "{input:?}");
}
let inputs = [
"friendly.bard",
"friendly.BARD",
"friendly_bard",
"friendly--bard",
"friendly-.bard",
"FrIeNdLy-._.-bArD",
];
for input in inputs {
assert!(!is_normalized(input).unwrap(), "{input:?}");
}
}
#[test]
fn unchanged() {
// Unchanged
let unchanged = ["friendly-bard", "1okay", "okay2"];
for input in unchanged {
assert_eq!(validate_and_normalize_ref(input).unwrap().as_ref(), input);
assert!(is_normalized(input).unwrap());
}
}
#[test]
fn failures() {
let failures = [
" starts-with-space",
"-starts-with-dash",
"ends-with-dash-",
"ends-with-space ",
"includes!invalid-char",
"space in middle",
"alpha-Ξ±",
];
for input in failures {
assert!(validate_and_normalize_ref(input).is_err());
assert!(is_normalized(input).is_err());
}
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-normalize/src/extra_name.rs | crates/uv-normalize/src/extra_name.rs | use std::fmt;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Deserializer, Serialize};
use uv_small_str::SmallString;
use crate::{InvalidNameError, validate_and_normalize_ref};
/// Either the literal "all" or a list of extras
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum DefaultExtras {
/// All extras are defaulted
All,
/// A list of extras
List(Vec<ExtraName>),
}
/// Serialize a [`DefaultExtras`] struct into a list of marker strings.
impl serde::Serialize for DefaultExtras {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::All => serializer.serialize_str("all"),
Self::List(extras) => {
let mut seq = serializer.serialize_seq(Some(extras.len()))?;
for extra in extras {
seq.serialize_element(&extra)?;
}
seq.end()
}
}
}
}
/// Deserialize a "all" or list of [`ExtraName`] into a [`DefaultExtras`] enum.
impl<'de> serde::Deserialize<'de> for DefaultExtras {
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 = DefaultExtras;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str(r#"the string "all" or a list of strings"#)
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if value != "all" {
return Err(serde::de::Error::custom(
r#"default-extras must be "all" or a ["list", "of", "extras"]"#,
));
}
Ok(DefaultExtras::All)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut extras = Vec::new();
while let Some(elem) = seq.next_element::<ExtraName>()? {
extras.push(elem);
}
Ok(DefaultExtras::List(extras))
}
}
deserializer.deserialize_any(StringOrVecVisitor)
}
}
impl Default for DefaultExtras {
fn default() -> Self {
Self::List(Vec::new())
}
}
/// The normalized name of an extra dependency.
///
/// Converts the name to lowercase and collapses runs of `-`, `_`, and `.` down to a single `-`.
/// For example, `---`, `.`, and `__` are all converted to a single `-`.
///
/// See:
/// - <https://peps.python.org/pep-0685/#specification/>
/// - <https://packaging.python.org/en/latest/specifications/name-normalization/>
#[derive(
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Serialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[rkyv(derive(Debug))]
pub struct ExtraName(SmallString);
impl ExtraName {
/// Create a validated, normalized extra name.
///
/// At present, this is no more efficient than calling [`ExtraName::from_str`].
#[allow(clippy::needless_pass_by_value)]
pub fn from_owned(name: String) -> Result<Self, InvalidNameError> {
validate_and_normalize_ref(&name).map(Self)
}
/// Return the underlying extra name as a string.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for ExtraName {
type Err = InvalidNameError;
fn from_str(name: &str) -> Result<Self, Self::Err> {
validate_and_normalize_ref(name).map(Self)
}
}
impl<'de> Deserialize<'de> for ExtraName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = ExtraName;
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("a string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
ExtraName::from_str(v).map_err(serde::de::Error::custom)
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
ExtraName::from_owned(v).map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Display for ExtraName {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl AsRef<str> for ExtraName {
fn as_ref(&self) -> &str {
self.as_str()
}
}
| 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-normalize/src/group_name.rs | crates/uv-normalize/src/group_name.rs | #[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::LazyLock;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use uv_small_str::SmallString;
use crate::{
InvalidNameError, InvalidPipGroupError, InvalidPipGroupPathError, validate_and_normalize_ref,
};
/// The normalized name of a dependency group.
///
/// See:
/// - <https://peps.python.org/pep-0735/>
/// - <https://packaging.python.org/en/latest/specifications/name-normalization/>
#[derive(
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[rkyv(derive(Debug))]
pub struct GroupName(SmallString);
impl GroupName {
/// Create a validated, normalized group name.
///
/// At present, this is no more efficient than calling [`GroupName::from_str`].
#[allow(clippy::needless_pass_by_value)]
pub fn from_owned(name: String) -> Result<Self, InvalidNameError> {
validate_and_normalize_ref(&name).map(Self)
}
/// Return the underlying group name as a string.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for GroupName {
type Err = InvalidNameError;
fn from_str(name: &str) -> Result<Self, Self::Err> {
validate_and_normalize_ref(name).map(Self)
}
}
impl<'de> Deserialize<'de> for GroupName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = GroupName;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
GroupName::from_str(v).map_err(serde::de::Error::custom)
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
GroupName::from_owned(v).map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Serialize for GroupName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
impl std::fmt::Display for GroupName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl AsRef<str> for GroupName {
fn as_ref(&self) -> &str {
&self.0
}
}
/// The pip-compatible variant of a [`GroupName`].
///
/// Either <groupname> or <path>:<groupname>.
/// If <path> is omitted it defaults to "pyproject.toml".
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct PipGroupName {
pub path: Option<PathBuf>,
pub name: GroupName,
}
impl FromStr for PipGroupName {
type Err = InvalidPipGroupError;
fn from_str(path_and_name: &str) -> Result<Self, Self::Err> {
// The syntax is `<path>:<name>`.
//
// `:` isn't valid as part of a dependency-group name, but it can appear in a path.
// Therefore we look for the first `:` starting from the end to find the delimiter.
// If there is no `:` then there's no path and we use the default one.
if let Some((path, name)) = path_and_name.rsplit_once(':') {
// pip hard errors if the path does not end with pyproject.toml
if !path.ends_with("pyproject.toml") {
Err(InvalidPipGroupPathError(path.to_owned()))?;
}
let name = GroupName::from_str(name)?;
let path = Some(PathBuf::from(path));
Ok(Self { path, name })
} else {
let name = GroupName::from_str(path_and_name)?;
let path = None;
Ok(Self { path, name })
}
}
}
impl<'de> Deserialize<'de> for PipGroupName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl Serialize for PipGroupName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let string = self.to_string();
string.serialize(serializer)
}
}
impl Display for PipGroupName {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(path) = &self.path {
write!(f, "{}:{}", path.display(), self.name)
} else {
self.name.fmt(f)
}
}
}
/// Either the literal "all" or a list of groups
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DefaultGroups {
/// All groups are defaulted
All,
/// A list of groups
List(Vec<GroupName>),
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for DefaultGroups {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("DefaultGroups")
}
fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "Either the literal \"all\" or a list of groups",
"oneOf": [
{
"description": "All groups are defaulted",
"type": "string",
"const": "all"
},
{
"description": "A list of groups",
"type": "array",
"items": generator.subschema_for::<GroupName>()
}
]
})
}
}
/// Serialize a [`DefaultGroups`] struct into a list of marker strings.
impl serde::Serialize for DefaultGroups {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::All => serializer.serialize_str("all"),
Self::List(groups) => {
let mut seq = serializer.serialize_seq(Some(groups.len()))?;
for group in groups {
seq.serialize_element(&group)?;
}
seq.end()
}
}
}
}
/// Deserialize a "all" or list of [`GroupName`] into a [`DefaultGroups`] enum.
impl<'de> serde::Deserialize<'de> for DefaultGroups {
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 = DefaultGroups;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str(r#"the string "all" or a list of strings"#)
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if value != "all" {
return Err(serde::de::Error::custom(
r#"default-groups must be "all" or a ["list", "of", "groups"]"#,
));
}
Ok(DefaultGroups::All)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut groups = Vec::new();
while let Some(elem) = seq.next_element::<GroupName>()? {
groups.push(elem);
}
Ok(DefaultGroups::List(groups))
}
}
deserializer.deserialize_any(StringOrVecVisitor)
}
}
impl Default for DefaultGroups {
/// Note this is an "empty" default unlike other contexts where `["dev"]` is the default
fn default() -> Self {
Self::List(Vec::new())
}
}
/// The name of the global `dev-dependencies` group.
///
/// Internally, we model dependency groups as a generic concept; but externally, we only expose the
/// `dev-dependencies` group.
pub static DEV_DEPENDENCIES: LazyLock<GroupName> =
LazyLock::new(|| GroupName::from_str("dev").unwrap());
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-normalize/src/package_name.rs | crates/uv-normalize/src/package_name.rs | use std::borrow::Cow;
use std::cmp::PartialEq;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize};
use uv_small_str::SmallString;
use crate::{InvalidNameError, validate_and_normalize_ref};
/// The normalized name of a package.
///
/// Converts the name to lowercase and collapses runs of `-`, `_`, and `.` down to a single `-`.
/// For example, `---`, `.`, and `__` are all converted to a single `-`.
///
/// See: <https://packaging.python.org/en/latest/specifications/name-normalization/>
#[derive(
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Serialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[rkyv(derive(Debug))]
pub struct PackageName(SmallString);
impl PackageName {
/// Create a validated, normalized package name.
///
/// At present, this is no more efficient than calling [`PackageName::from_str`].
#[allow(clippy::needless_pass_by_value)]
pub fn from_owned(name: String) -> Result<Self, InvalidNameError> {
validate_and_normalize_ref(&name).map(Self)
}
/// Escape this name with underscores (`_`) instead of dashes (`-`)
///
/// See: <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#recording-installed-packages>
pub fn as_dist_info_name(&self) -> Cow<'_, str> {
if let Some(dash_position) = self.0.find('-') {
// Initialize `replaced` with the start of the string up to the current character.
let mut owned_string = String::with_capacity(self.0.len());
owned_string.push_str(&self.0[..dash_position]);
owned_string.push('_');
// Iterate over the rest of the string.
owned_string.extend(
self.0[dash_position + 1..]
.chars()
.map(|character| if character == '-' { '_' } else { character }),
);
Cow::Owned(owned_string)
} else {
Cow::Borrowed(self.0.as_ref())
}
}
/// Returns the underlying package name.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&Self> for PackageName {
/// Required for `WaitMap::wait`.
fn from(package_name: &Self) -> Self {
package_name.clone()
}
}
impl FromStr for PackageName {
type Err = InvalidNameError;
fn from_str(name: &str) -> Result<Self, Self::Err> {
validate_and_normalize_ref(name).map(Self)
}
}
impl<'de> Deserialize<'de> for PackageName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = PackageName;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
PackageName::from_str(v).map_err(serde::de::Error::custom)
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
PackageName::from_owned(v).map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl std::fmt::Display for PackageName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl AsRef<str> for PackageName {
fn as_ref(&self) -> &str {
&self.0
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-normalize/src/dist_info_name.rs | crates/uv-normalize/src/dist_info_name.rs | use std::borrow::Cow;
use std::fmt;
use std::fmt::{Display, Formatter};
/// The normalized name of a `.dist-info` directory.
///
/// Like [`PackageName`](crate::PackageName), but without restrictions on the set of allowed
/// characters, etc.
///
/// See: <https://github.com/pypa/pip/blob/111eed14b6e9fba7c78a5ec2b7594812d17b5d2b/src/pip/_vendor/packaging/utils.py#L45>
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DistInfoName<'a>(Cow<'a, str>);
impl<'a> DistInfoName<'a> {
/// Create a validated, normalized `.dist-info` directory name.
pub fn new(name: &'a str) -> Self {
if Self::is_normalized(name) {
Self(Cow::Borrowed(name))
} else {
Self(Cow::Owned(Self::normalize(name)))
}
}
/// Normalize a `.dist-info` name, converting it to lowercase and collapsing runs
/// of `-`, `_`, and `.` down to a single `-`.
fn normalize(name: impl AsRef<str>) -> String {
let mut normalized = String::with_capacity(name.as_ref().len());
let mut last = None;
for char in name.as_ref().bytes() {
match char {
b'A'..=b'Z' => {
normalized.push(char.to_ascii_lowercase() as char);
}
b'-' | b'_' | b'.' => {
if matches!(last, Some(b'-' | b'_' | b'.')) {
continue;
}
normalized.push('-');
}
_ => {
normalized.push(char as char);
}
}
last = Some(char);
}
normalized
}
/// Returns `true` if the name is already normalized.
fn is_normalized(name: impl AsRef<str>) -> bool {
let mut last = None;
for char in name.as_ref().bytes() {
match char {
b'A'..=b'Z' => {
// Uppercase characters need to be converted to lowercase.
return false;
}
b'_' | b'.' => {
// `_` and `.` are normalized to `-`.
return false;
}
b'-' => {
if matches!(last, Some(b'-')) {
// Runs of `-` are normalized to a single `-`.
return false;
}
}
_ => {}
}
last = Some(char);
}
true
}
}
impl Display for DistInfoName<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl AsRef<str> for DistInfoName<'_> {
fn as_ref(&self) -> &str {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize() {
let inputs = [
"friendly-bard",
"Friendly-Bard",
"FRIENDLY-BARD",
"friendly.bard",
"friendly_bard",
"friendly--bard",
"friendly-.bard",
"FrIeNdLy-._.-bArD",
];
for input in inputs {
assert_eq!(DistInfoName::normalize(input), "friendly-bard");
}
}
}
| 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-performance-memory-allocator/src/lib.rs | crates/uv-performance-memory-allocator/src/lib.rs | //! The only purpose of this crate is to pull in `mimalloc` on windows and
//! `tikv-jemallocator` on most other platforms.
#[cfg(target_os = "windows")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[cfg(all(
not(target_os = "windows"),
not(target_os = "openbsd"),
not(target_os = "freebsd"),
any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "powerpc64"
)
))]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
| 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-client/src/tls.rs | crates/uv-client/src/tls.rs | use reqwest::Identity;
use std::ffi::OsStr;
use std::io::Read;
#[derive(thiserror::Error, Debug)]
pub(crate) enum CertificateError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Reqwest(reqwest::Error),
}
/// Return the `Identity` from the provided file.
pub(crate) fn read_identity(ssl_client_cert: &OsStr) -> Result<Identity, CertificateError> {
let mut buf = Vec::new();
fs_err::File::open(ssl_client_cert)?.read_to_end(&mut buf)?;
Identity::from_pem(&buf).map_err(|tls_err| {
debug_assert!(tls_err.is_builder(), "must be a rustls::Error internally");
CertificateError::Reqwest(tls_err)
})
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-client/src/registry_client.rs | crates/uv-client/src/registry_client.rs | use std::collections::BTreeMap;
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use async_http_range_reader::AsyncHttpRangeReader;
use futures::{FutureExt, StreamExt, TryStreamExt};
use http::{HeaderMap, StatusCode};
use itertools::Either;
use reqwest::{Proxy, Response};
use rustc_hash::FxHashMap;
use tokio::sync::{Mutex, Semaphore};
use tracing::{Instrument, debug, info_span, instrument, trace, warn};
use url::Url;
use uv_auth::{CredentialsCache, Indexes, PyxTokenStore};
use uv_cache::{Cache, CacheBucket, CacheEntry, WheelCache};
use uv_configuration::IndexStrategy;
use uv_configuration::KeyringProviderType;
use uv_distribution_filename::{DistFilename, SourceDistFilename, WheelFilename};
use uv_distribution_types::{
BuiltDist, File, IndexCapabilities, IndexFormat, IndexLocations, IndexMetadataRef,
IndexStatusCodeDecision, IndexStatusCodeStrategy, IndexUrl, IndexUrls, Name,
};
use uv_metadata::{read_metadata_async_seek, read_metadata_async_stream};
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_pep508::MarkerEnvironment;
use uv_platform_tags::Platform;
use uv_pypi_types::{
PypiSimpleDetail, PypiSimpleIndex, PyxSimpleDetail, PyxSimpleIndex, ResolutionMetadata,
};
use uv_redacted::DisplaySafeUrl;
use uv_small_str::SmallString;
use uv_torch::TorchStrategy;
use crate::base_client::{BaseClientBuilder, ExtraMiddleware, RedirectPolicy};
use crate::cached_client::CacheControl;
use crate::flat_index::FlatIndexEntry;
use crate::html::SimpleDetailHTML;
use crate::remote_metadata::wheel_metadata_from_remote_zip;
use crate::rkyvutil::OwnedArchive;
use crate::{
BaseClient, CachedClient, Error, ErrorKind, FlatIndexClient, FlatIndexEntries,
RedirectClientWithMiddleware,
};
/// A builder for an [`RegistryClient`].
#[derive(Debug, Clone)]
pub struct RegistryClientBuilder<'a> {
index_locations: IndexLocations,
index_strategy: IndexStrategy,
torch_backend: Option<TorchStrategy>,
cache: Cache,
base_client_builder: BaseClientBuilder<'a>,
}
impl<'a> RegistryClientBuilder<'a> {
pub fn new(base_client_builder: BaseClientBuilder<'a>, cache: Cache) -> Self {
Self {
index_locations: IndexLocations::default(),
index_strategy: IndexStrategy::default(),
torch_backend: None,
cache,
base_client_builder,
}
}
#[must_use]
pub fn with_reqwest_client(mut self, client: reqwest::Client) -> Self {
self.base_client_builder = self.base_client_builder.custom_client(client);
self
}
#[must_use]
pub fn index_locations(mut self, index_locations: IndexLocations) -> Self {
self.index_locations = index_locations;
self
}
#[must_use]
pub fn index_strategy(mut self, index_strategy: IndexStrategy) -> Self {
self.index_strategy = index_strategy;
self
}
#[must_use]
pub fn torch_backend(mut self, torch_backend: Option<TorchStrategy>) -> Self {
self.torch_backend = torch_backend;
self
}
#[must_use]
pub fn keyring(mut self, keyring_type: KeyringProviderType) -> Self {
self.base_client_builder = self.base_client_builder.keyring(keyring_type);
self
}
#[must_use]
pub fn built_in_root_certs(mut self, built_in_root_certs: bool) -> Self {
self.base_client_builder = self
.base_client_builder
.built_in_root_certs(built_in_root_certs);
self
}
#[must_use]
pub fn cache(mut self, cache: Cache) -> Self {
self.cache = cache;
self
}
#[must_use]
pub fn extra_middleware(mut self, middleware: ExtraMiddleware) -> Self {
self.base_client_builder = self.base_client_builder.extra_middleware(middleware);
self
}
#[must_use]
pub fn markers(mut self, markers: &'a MarkerEnvironment) -> Self {
self.base_client_builder = self.base_client_builder.markers(markers);
self
}
#[must_use]
pub fn platform(mut self, platform: &'a Platform) -> Self {
self.base_client_builder = self.base_client_builder.platform(platform);
self
}
#[must_use]
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.base_client_builder = self.base_client_builder.proxy(proxy);
self
}
/// Allows credentials to be propagated on cross-origin redirects.
///
/// WARNING: This should only be available for tests. In production code, propagating credentials
/// during cross-origin redirects can lead to security vulnerabilities including credential
/// leakage to untrusted domains.
#[cfg(test)]
#[must_use]
pub fn allow_cross_origin_credentials(mut self) -> Self {
self.base_client_builder = self.base_client_builder.allow_cross_origin_credentials();
self
}
/// Add all authenticated sources to the cache.
pub fn cache_index_credentials(&mut self) {
for index in self.index_locations.known_indexes() {
if let Some(credentials) = index.credentials() {
trace!(
"Read credentials for index {}",
index
.name
.as_ref()
.map(ToString::to_string)
.unwrap_or_else(|| index.url.to_string())
);
if let Some(root_url) = index.root_url() {
self.base_client_builder
.store_credentials(&root_url, credentials.clone());
}
self.base_client_builder
.store_credentials(index.raw_url(), credentials);
}
}
}
pub fn build(mut self) -> RegistryClient {
self.cache_index_credentials();
let index_urls = self.index_locations.index_urls();
// Build a base client
let builder = self
.base_client_builder
.indexes(Indexes::from(&self.index_locations))
.redirect(RedirectPolicy::RetriggerMiddleware);
let client = builder.build();
let timeout = client.timeout();
let connectivity = client.connectivity();
// Wrap in the cache middleware.
let client = CachedClient::new(client);
RegistryClient {
index_urls,
index_strategy: self.index_strategy,
torch_backend: self.torch_backend,
cache: self.cache,
connectivity,
client,
timeout,
flat_indexes: Arc::default(),
pyx_token_store: PyxTokenStore::from_settings().ok(),
}
}
/// Share the underlying client between two different middleware configurations.
pub fn wrap_existing(mut self, existing: &BaseClient) -> RegistryClient {
self.cache_index_credentials();
let index_urls = self.index_locations.index_urls();
// Wrap in any relevant middleware and handle connectivity.
let client = self
.base_client_builder
.indexes(Indexes::from(&self.index_locations))
.wrap_existing(existing);
let timeout = client.timeout();
let connectivity = client.connectivity();
// Wrap in the cache middleware.
let client = CachedClient::new(client);
RegistryClient {
index_urls,
index_strategy: self.index_strategy,
torch_backend: self.torch_backend,
cache: self.cache,
connectivity,
client,
timeout,
flat_indexes: Arc::default(),
pyx_token_store: PyxTokenStore::from_settings().ok(),
}
}
}
/// A client for fetching packages from a `PyPI`-compatible index.
#[derive(Debug, Clone)]
pub struct RegistryClient {
/// The index URLs to use for fetching packages.
index_urls: IndexUrls,
/// The strategy to use when fetching across multiple indexes.
index_strategy: IndexStrategy,
/// The strategy to use when selecting a PyTorch backend, if any.
torch_backend: Option<TorchStrategy>,
/// The underlying HTTP client.
client: CachedClient,
/// Used for the remote wheel METADATA cache.
cache: Cache,
/// The connectivity mode to use.
connectivity: Connectivity,
/// Configured client timeout, in seconds.
timeout: Duration,
/// The flat index entries for each `--find-links`-style index URL.
flat_indexes: Arc<Mutex<FlatIndexCache>>,
/// The pyx token store to use for persistent credentials.
// TODO(charlie): The token store is only needed for `is_known_url`; can we avoid storing it here?
pyx_token_store: Option<PyxTokenStore>,
}
/// The format of the package metadata returned by querying an index.
#[derive(Debug)]
pub enum MetadataFormat {
/// The metadata adheres to the Simple Repository API format.
Simple(OwnedArchive<SimpleDetailMetadata>),
/// The metadata consists of a list of distributions from a "flat" index.
Flat(Vec<FlatIndexEntry>),
}
impl RegistryClient {
/// Return the [`CachedClient`] used by this client.
pub fn cached_client(&self) -> &CachedClient {
&self.client
}
/// Return the [`BaseClient`] used by this client.
pub fn uncached_client(&self, url: &DisplaySafeUrl) -> &RedirectClientWithMiddleware {
self.client.uncached().for_host(url)
}
/// Returns `true` if SSL verification is disabled for the given URL.
pub fn disable_ssl(&self, url: &DisplaySafeUrl) -> bool {
self.client.uncached().disable_ssl(url)
}
/// Return the [`Connectivity`] mode used by this client.
pub fn connectivity(&self) -> Connectivity {
self.connectivity
}
/// Return the timeout this client is configured with, in seconds.
pub fn timeout(&self) -> Duration {
self.timeout
}
pub fn credentials_cache(&self) -> &CredentialsCache {
self.client.uncached().credentials_cache()
}
/// Return the appropriate index URLs for the given [`PackageName`].
fn index_urls_for(
&self,
package_name: &PackageName,
) -> impl Iterator<Item = IndexMetadataRef<'_>> {
self.torch_backend
.as_ref()
.and_then(|torch_backend| {
torch_backend
.applies_to(package_name)
.then(|| torch_backend.index_urls())
.map(|indexes| indexes.map(IndexMetadataRef::from))
})
.map(Either::Left)
.unwrap_or_else(|| Either::Right(self.index_urls.indexes().map(IndexMetadataRef::from)))
}
/// Return the appropriate [`IndexStrategy`] for the given [`PackageName`].
fn index_strategy_for(&self, package_name: &PackageName) -> IndexStrategy {
self.torch_backend
.as_ref()
.and_then(|torch_backend| {
torch_backend
.applies_to(package_name)
.then_some(IndexStrategy::UnsafeFirstMatch)
})
.unwrap_or(self.index_strategy)
}
/// Fetch package metadata from an index.
///
/// Supports both the "Simple" API and `--find-links`-style flat indexes.
///
/// "Simple" here refers to [PEP 503 β Simple Repository API](https://peps.python.org/pep-0503/)
/// and [PEP 691 β JSON-based Simple API for Python Package Indexes](https://peps.python.org/pep-0691/),
/// which the PyPI JSON API implements.
#[instrument(skip_all, fields(package = % package_name))]
pub async fn simple_detail<'index>(
&'index self,
package_name: &PackageName,
index: Option<IndexMetadataRef<'index>>,
capabilities: &IndexCapabilities,
download_concurrency: &Semaphore,
) -> Result<Vec<(&'index IndexUrl, MetadataFormat)>, Error> {
// If `--no-index` is specified, avoid fetching regardless of whether the index is implicit,
// explicit, etc.
if self.index_urls.no_index() {
return Err(ErrorKind::NoIndex(package_name.to_string()).into());
}
let indexes = if let Some(index) = index {
Either::Left(std::iter::once(index))
} else {
Either::Right(self.index_urls_for(package_name))
};
let mut results = Vec::new();
match self.index_strategy_for(package_name) {
// If we're searching for the first index that contains the package, fetch serially.
IndexStrategy::FirstIndex => {
for index in indexes {
let _permit = download_concurrency.acquire().await;
match index.format {
IndexFormat::Simple => {
let status_code_strategy =
self.index_urls.status_code_strategy_for(index.url);
match self
.simple_detail_single_index(
package_name,
index.url,
capabilities,
&status_code_strategy,
)
.await?
{
SimpleMetadataSearchOutcome::Found(metadata) => {
results.push((index.url, MetadataFormat::Simple(metadata)));
break;
}
// Package not found, so we will continue on to the next index (if there is one)
SimpleMetadataSearchOutcome::NotFound => {}
// The search failed because of an HTTP status code that we don't ignore for
// this index. We end our search here.
SimpleMetadataSearchOutcome::StatusCodeFailure(status_code) => {
debug!(
"Indexes search failed because of status code failure: {status_code}"
);
break;
}
}
}
IndexFormat::Flat => {
let entries = self.flat_single_index(package_name, index.url).await?;
if !entries.is_empty() {
results.push((index.url, MetadataFormat::Flat(entries)));
break;
}
}
}
}
}
// Otherwise, fetch concurrently.
IndexStrategy::UnsafeBestMatch | IndexStrategy::UnsafeFirstMatch => {
results = futures::stream::iter(indexes)
.map(async |index| {
let _permit = download_concurrency.acquire().await;
match index.format {
IndexFormat::Simple => {
// For unsafe matches, ignore authentication failures.
let status_code_strategy =
IndexStatusCodeStrategy::ignore_authentication_error_codes();
let metadata = match self
.simple_detail_single_index(
package_name,
index.url,
capabilities,
&status_code_strategy,
)
.await?
{
SimpleMetadataSearchOutcome::Found(metadata) => Some(metadata),
_ => None,
};
Ok((index.url, metadata.map(MetadataFormat::Simple)))
}
IndexFormat::Flat => {
let entries =
self.flat_single_index(package_name, index.url).await?;
Ok((index.url, Some(MetadataFormat::Flat(entries))))
}
}
})
.buffered(8)
.filter_map(async |result: Result<_, Error>| match result {
Ok((index, Some(metadata))) => Some(Ok((index, metadata))),
Ok((_, None)) => None,
Err(err) => Some(Err(err)),
})
.try_collect::<Vec<_>>()
.await?;
}
}
if results.is_empty() {
return match self.connectivity {
Connectivity::Online => {
Err(ErrorKind::RemotePackageNotFound(package_name.clone()).into())
}
Connectivity::Offline => Err(ErrorKind::Offline(package_name.to_string()).into()),
};
}
Ok(results)
}
/// Fetch the [`FlatIndexEntry`] entries for a given package from a single `--find-links` index.
async fn flat_single_index(
&self,
package_name: &PackageName,
index: &IndexUrl,
) -> Result<Vec<FlatIndexEntry>, Error> {
// Store the flat index entries in a cache, to avoid redundant fetches. A flat index will
// typically contain entries for multiple packages; as such, it's more efficient to cache
// the entire index rather than re-fetching it for each package.
let mut cache = self.flat_indexes.lock().await;
if let Some(entries) = cache.get(index) {
return Ok(entries.get(package_name).cloned().unwrap_or_default());
}
let client = FlatIndexClient::new(self.cached_client(), self.connectivity, &self.cache);
// Fetch the entries for the index.
let FlatIndexEntries { entries, .. } =
client.fetch_index(index).await.map_err(ErrorKind::Flat)?;
// Index by package name.
let mut entries_by_package: FxHashMap<PackageName, Vec<FlatIndexEntry>> =
FxHashMap::default();
for entry in entries {
entries_by_package
.entry(entry.filename.name().clone())
.or_default()
.push(entry);
}
let package_entries = entries_by_package
.get(package_name)
.cloned()
.unwrap_or_default();
// Write to the cache.
cache.insert(index.clone(), entries_by_package);
Ok(package_entries)
}
/// Fetch the [`SimpleDetailMetadata`] from a single index for a given package.
///
/// The index can either be a PEP 503-compatible remote repository, or a local directory laid
/// out in the same format.
async fn simple_detail_single_index(
&self,
package_name: &PackageName,
index: &IndexUrl,
capabilities: &IndexCapabilities,
status_code_strategy: &IndexStatusCodeStrategy,
) -> Result<SimpleMetadataSearchOutcome, Error> {
// Format the URL for PyPI.
let mut url = index.url().clone();
url.path_segments_mut()
.map_err(|()| ErrorKind::CannotBeABase(index.url().clone()))?
.pop_if_empty()
.push(package_name.as_ref())
// The URL *must* end in a trailing slash for proper relative path behavior
// ref https://github.com/servo/rust-url/issues/333
.push("");
trace!("Fetching metadata for {package_name} from {url}");
let cache_entry = self.cache.entry(
CacheBucket::Simple,
WheelCache::Index(index).root(),
format!("{package_name}.rkyv"),
);
let cache_control = match self.connectivity {
Connectivity::Online => {
if let Some(header) = self.index_urls.simple_api_cache_control_for(index) {
CacheControl::Override(header)
} else {
CacheControl::from(
self.cache
.freshness(&cache_entry, Some(package_name), None)
.map_err(ErrorKind::Io)?,
)
}
}
Connectivity::Offline => CacheControl::AllowStale,
};
// Acquire an advisory lock, to guard against concurrent writes.
#[cfg(windows)]
let _lock = {
let lock_entry = cache_entry.with_file(format!("{package_name}.lock"));
lock_entry.lock().await.map_err(ErrorKind::CacheLock)?
};
let result = if matches!(index, IndexUrl::Path(_)) {
self.fetch_local_simple_detail(package_name, &url).await
} else {
self.fetch_remote_simple_detail(package_name, &url, index, &cache_entry, cache_control)
.await
};
match result {
Ok(metadata) => Ok(SimpleMetadataSearchOutcome::Found(metadata)),
Err(err) => match err.kind() {
// The package could not be found in the remote index.
ErrorKind::WrappedReqwestError(.., reqwest_err) => {
let Some(status_code) = reqwest_err.status() else {
return Err(err);
};
let decision =
status_code_strategy.handle_status_code(status_code, index, capabilities);
if let IndexStatusCodeDecision::Fail(status_code) = decision {
if !matches!(
status_code,
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
) {
return Err(err);
}
}
Ok(SimpleMetadataSearchOutcome::from(decision))
}
// The package is unavailable due to a lack of connectivity.
ErrorKind::Offline(_) => Ok(SimpleMetadataSearchOutcome::NotFound),
// The package could not be found in the local index.
ErrorKind::LocalPackageNotFound(_) => Ok(SimpleMetadataSearchOutcome::NotFound),
_ => Err(err),
},
}
}
/// Fetch the [`SimpleDetailMetadata`] from a remote URL, using the PEP 503 Simple Repository API.
async fn fetch_remote_simple_detail(
&self,
package_name: &PackageName,
url: &DisplaySafeUrl,
index: &IndexUrl,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
) -> Result<OwnedArchive<SimpleDetailMetadata>, Error> {
// In theory, we should be able to pass `MediaType::all()` to all registries, and as
// unsupported media types should be ignored by the server. For now, we implement this
// defensively to avoid issues with misconfigured servers.
let accept = if self
.pyx_token_store
.as_ref()
.is_some_and(|token_store| token_store.is_known_url(index.url()))
{
MediaType::all()
} else {
MediaType::pypi()
};
let simple_request = self
.uncached_client(url)
.get(Url::from(url.clone()))
.header("Accept-Encoding", "gzip, deflate, zstd")
.header("Accept", accept)
.build()
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let parse_simple_response = |response: Response| {
async {
// Use the response URL, rather than the request URL, as the base for relative URLs.
// This ensures that we handle redirects and other URL transformations correctly.
let url = DisplaySafeUrl::from_url(response.url().clone());
let content_type = response
.headers()
.get("content-type")
.ok_or_else(|| Error::from(ErrorKind::MissingContentType(url.clone())))?;
let content_type = content_type.to_str().map_err(|err| {
Error::from(ErrorKind::InvalidContentTypeHeader(url.clone(), err))
})?;
let media_type = content_type.split(';').next().unwrap_or(content_type);
let media_type = MediaType::from_str(media_type).ok_or_else(|| {
Error::from(ErrorKind::UnsupportedMediaType(
url.clone(),
media_type.to_string(),
))
})?;
let unarchived = match media_type {
MediaType::PyxV1Msgpack => {
let bytes = response
.bytes()
.await
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let data: PyxSimpleDetail = rmp_serde::from_slice(bytes.as_ref())
.map_err(|err| Error::from_msgpack_err(err, url.clone()))?;
SimpleDetailMetadata::from_pyx_files(
data.files,
data.core_metadata,
package_name,
&url,
)
}
MediaType::PyxV1Json => {
let bytes = response
.bytes()
.await
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let data: PyxSimpleDetail = serde_json::from_slice(bytes.as_ref())
.map_err(|err| Error::from_json_err(err, url.clone()))?;
SimpleDetailMetadata::from_pyx_files(
data.files,
data.core_metadata,
package_name,
&url,
)
}
MediaType::PypiV1Json => {
let bytes = response
.bytes()
.await
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let data: PypiSimpleDetail = serde_json::from_slice(bytes.as_ref())
.map_err(|err| Error::from_json_err(err, url.clone()))?;
SimpleDetailMetadata::from_pypi_files(data.files, package_name, &url)
}
MediaType::PypiV1Html | MediaType::TextHtml => {
let text = response
.text()
.await
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
SimpleDetailMetadata::from_html(&text, package_name, &url)?
}
};
OwnedArchive::from_unarchived(&unarchived)
}
.boxed_local()
.instrument(info_span!("parse_simple_api", package = %package_name))
};
let simple = self
.cached_client()
.get_cacheable_with_retry(
simple_request,
cache_entry,
cache_control,
parse_simple_response,
)
.await?;
Ok(simple)
}
/// Fetch the [`SimpleDetailMetadata`] from a local file, using a PEP 503-compatible directory
/// structure.
async fn fetch_local_simple_detail(
&self,
package_name: &PackageName,
url: &DisplaySafeUrl,
) -> Result<OwnedArchive<SimpleDetailMetadata>, Error> {
let path = url
.to_file_path()
.map_err(|()| ErrorKind::NonFileUrl(url.clone()))?
.join("index.html");
let text = match fs_err::tokio::read_to_string(&path).await {
Ok(text) => text,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Err(Error::from(ErrorKind::LocalPackageNotFound(
package_name.clone(),
)));
}
Err(err) => {
return Err(Error::from(ErrorKind::Io(err)));
}
};
let metadata = SimpleDetailMetadata::from_html(&text, package_name, url)?;
OwnedArchive::from_unarchived(&metadata)
}
/// Fetch the list of projects from a Simple API index at a remote URL.
///
/// This fetches the root of a Simple API index (e.g., `https://pypi.org/simple/`)
/// which returns a list of all available projects.
pub async fn fetch_simple_index(
&self,
index_url: &IndexUrl,
) -> Result<SimpleIndexMetadata, Error> {
// Format the URL for PyPI.
let mut url = index_url.url().clone();
url.path_segments_mut()
.map_err(|()| ErrorKind::CannotBeABase(index_url.url().clone()))?
.pop_if_empty()
// The URL *must* end in a trailing slash for proper relative path behavior
// ref https://github.com/servo/rust-url/issues/333
.push("");
if url.scheme() == "file" {
let archived = self.fetch_local_simple_index(&url).await?;
Ok(OwnedArchive::deserialize(&archived))
} else {
let archived = self.fetch_remote_simple_index(&url, index_url).await?;
Ok(OwnedArchive::deserialize(&archived))
}
}
/// Fetch the list of projects from a remote Simple API index.
async fn fetch_remote_simple_index(
&self,
url: &DisplaySafeUrl,
index: &IndexUrl,
) -> Result<OwnedArchive<SimpleIndexMetadata>, Error> {
// In theory, we should be able to pass `MediaType::all()` to all registries, and as
// unsupported media types should be ignored by the server. For now, we implement this
// defensively to avoid issues with misconfigured servers.
let accept = if self
.pyx_token_store
.as_ref()
.is_some_and(|token_store| token_store.is_known_url(index.url()))
{
MediaType::all()
} else {
MediaType::pypi()
};
let cache_entry = self.cache.entry(
CacheBucket::Simple,
WheelCache::Index(index).root(),
"index.html.rkyv",
);
let cache_control = match self.connectivity {
Connectivity::Online => {
if let Some(header) = self.index_urls.simple_api_cache_control_for(index) {
CacheControl::Override(header)
} else {
CacheControl::from(
self.cache
.freshness(&cache_entry, None, None)
.map_err(ErrorKind::Io)?,
)
}
}
Connectivity::Offline => CacheControl::AllowStale,
};
let parse_simple_response = |response: Response| {
async {
// Use the response URL, rather than the request URL, as the base for relative URLs.
// This ensures that we handle redirects and other URL transformations correctly.
let url = DisplaySafeUrl::from_url(response.url().clone());
let content_type = response
.headers()
.get("content-type")
.ok_or_else(|| Error::from(ErrorKind::MissingContentType(url.clone())))?;
let content_type = content_type.to_str().map_err(|err| {
Error::from(ErrorKind::InvalidContentTypeHeader(url.clone(), err))
})?;
let media_type = content_type.split(';').next().unwrap_or(content_type);
let media_type = MediaType::from_str(media_type).ok_or_else(|| {
Error::from(ErrorKind::UnsupportedMediaType(
url.clone(),
media_type.to_string(),
))
})?;
let metadata = match media_type {
MediaType::PyxV1Msgpack => {
let bytes = response
.bytes()
| 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-client/src/html.rs | crates/uv-client/src/html.rs | use std::str::FromStr;
use jiff::Timestamp;
use tl::HTMLTag;
use tracing::{debug, instrument, warn};
use uv_normalize::PackageName;
use uv_pep440::VersionSpecifiers;
use uv_pypi_types::{BaseUrl, CoreMetadata, Hashes, PypiFile, Yanked};
use uv_pypi_types::{HashError, LenientVersionSpecifiers};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
/// A parsed structure from PyPI "HTML" index format for a single package.
#[derive(Debug, Clone)]
pub(crate) struct SimpleDetailHTML {
/// The [`BaseUrl`] to which all relative URLs should be resolved.
pub(crate) base: BaseUrl,
/// The list of [`PypiFile`]s available for download sorted by filename.
pub(crate) files: Vec<PypiFile>,
}
impl SimpleDetailHTML {
/// Parse the list of [`PypiFile`]s from the simple HTML page returned by the given URL.
#[instrument(skip_all, fields(url = % url))]
pub(crate) fn parse(text: &str, url: &DisplaySafeUrl) -> Result<Self, Error> {
let dom = tl::parse(text, tl::ParserOptions::default())?;
// Parse the first `<base>` tag, if any, to determine the base URL to which all
// relative URLs should be resolved. The HTML spec requires that the `<base>` tag
// appear before other tags with attribute values of URLs.
let base = BaseUrl::from(
dom.nodes()
.iter()
.filter_map(|node| node.as_tag())
.take_while(|tag| !matches!(tag.name().as_bytes(), b"a" | b"link"))
.find(|tag| tag.name().as_bytes() == b"base")
.map(|base| Self::parse_base(base))
.transpose()?
.flatten()
.unwrap_or_else(|| url.clone()),
);
// Parse each `<a>` tag, to extract the filename, hash, and URL.
let mut files: Vec<PypiFile> = dom
.nodes()
.iter()
.filter_map(|node| node.as_tag())
.filter(|link| link.name().as_bytes() == b"a")
.map(|link| Self::parse_anchor(link))
.filter_map(|result| match result {
Ok(None) => None,
Ok(Some(file)) => Some(Ok(file)),
Err(err) => Some(Err(err)),
})
.collect::<Result<Vec<_>, _>>()?;
// 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(Self { base, files })
}
/// Parse the `href` from a `<base>` tag.
fn parse_base(base: &HTMLTag) -> Result<Option<DisplaySafeUrl>, Error> {
let Some(Some(href)) = base.attributes().get("href") else {
return Ok(None);
};
let href = std::str::from_utf8(href.as_bytes())?;
let url =
DisplaySafeUrl::parse(href).map_err(|err| Error::UrlParse(href.to_string(), err))?;
Ok(Some(url))
}
/// Parse a [`PypiFile`] from an `<a>` tag.
///
/// Returns `None` if the `<a>` doesn't have an `href` attribute.
fn parse_anchor(link: &HTMLTag) -> Result<Option<PypiFile>, Error> {
// Extract the href.
let Some(href) = link
.attributes()
.get("href")
.flatten()
.filter(|bytes| !bytes.as_bytes().is_empty())
else {
return Ok(None);
};
let href = std::str::from_utf8(href.as_bytes())?;
// Extract the hash, which should be in the fragment.
let decoded = html_escape::decode_html_entities(href);
let (path, hashes) = if let Some((path, fragment)) = decoded.split_once('#') {
let fragment = percent_encoding::percent_decode_str(fragment).decode_utf8()?;
(
path,
if fragment.trim().is_empty() {
Hashes::default()
} else {
match Hashes::parse_fragment(&fragment) {
Ok(hashes) => hashes,
Err(
err
@ (HashError::InvalidFragment(..) | HashError::InvalidStructure(..)),
) => {
// If the URL includes an irrelevant hash (e.g., `#main`), ignore it.
debug!("{err}");
Hashes::default()
}
Err(HashError::UnsupportedHashAlgorithm(fragment)) => {
if fragment == "egg" {
// If the URL references an egg hash, ignore it.
debug!("{}", HashError::UnsupportedHashAlgorithm(fragment));
Hashes::default()
} else {
// If the URL references a hash, but it's unsupported, error.
return Err(HashError::UnsupportedHashAlgorithm(fragment).into());
}
}
}
},
)
} else {
(decoded.as_ref(), Hashes::default())
};
// Extract the filename from the body text, which MUST match that of
// the final path component of the URL.
let filename = path
.split('/')
.next_back()
.ok_or_else(|| Error::MissingFilename(href.to_string()))?;
// Strip any query string from the filename.
let filename = filename.split('?').next().unwrap_or(filename);
// Unquote the filename.
let filename = percent_encoding::percent_decode_str(filename)
.decode_utf8()
.map_err(|_| Error::UnsupportedFilename(filename.to_string()))?;
// Extract the `requires-python` value, which should be set on the
// `data-requires-python` attribute.
let requires_python = if let Some(requires_python) =
link.attributes().get("data-requires-python").flatten()
{
let requires_python = std::str::from_utf8(requires_python.as_bytes())?;
let requires_python = html_escape::decode_html_entities(requires_python);
Some(LenientVersionSpecifiers::from_str(&requires_python).map(VersionSpecifiers::from))
} else {
None
};
// Extract the `core-metadata` field, which is either set on:
// - `data-core-metadata`, per PEP 714.
// - `data-dist-info-metadata`, per PEP 658.
let core_metadata = if let Some(dist_info_metadata) = link
.attributes()
.get("data-core-metadata")
.flatten()
.or_else(|| link.attributes().get("data-dist-info-metadata").flatten())
{
let dist_info_metadata = std::str::from_utf8(dist_info_metadata.as_bytes())?;
let dist_info_metadata = html_escape::decode_html_entities(dist_info_metadata);
match dist_info_metadata.as_ref() {
"true" => Some(CoreMetadata::Bool(true)),
"false" => Some(CoreMetadata::Bool(false)),
fragment => match Hashes::parse_fragment(fragment) {
Ok(hash) => Some(CoreMetadata::Hashes(hash)),
Err(err) => {
warn!("Failed to parse core metadata value `{fragment}`: {err}");
None
}
},
}
} else {
None
};
// Extract the `yanked` field, which should be set on the `data-yanked`
// attribute.
let yanked = if let Some(yanked) = link.attributes().get("data-yanked").flatten() {
let yanked = std::str::from_utf8(yanked.as_bytes())?;
let yanked = html_escape::decode_html_entities(yanked);
Some(Box::new(Yanked::Reason(yanked.into())))
} else {
None
};
// Extract the `size` field, which should be set on the `data-size` attribute. This isn't
// included in PEP 700, which omits the HTML API, but we respect it anyway. Since this
// field isn't standardized, we discard errors.
let size = link
.attributes()
.get("data-size")
.flatten()
.and_then(|size| std::str::from_utf8(size.as_bytes()).ok())
.map(|size| html_escape::decode_html_entities(size))
.and_then(|size| size.parse().ok());
// Extract the `upload-time` field, which should be set on the `data-upload-time` attribute. This isn't
// included in PEP 700, which omits the HTML API, but we respect it anyway. Since this
// field isn't standardized, we discard errors.
let upload_time = link
.attributes()
.get("data-upload-time")
.flatten()
.and_then(|upload_time| std::str::from_utf8(upload_time.as_bytes()).ok())
.map(|upload_time| html_escape::decode_html_entities(upload_time))
.and_then(|upload_time| Timestamp::from_str(&upload_time).ok());
Ok(Some(PypiFile {
core_metadata,
yanked,
requires_python,
hashes,
filename: filename.into(),
url: path.into(),
size,
upload_time,
}))
}
}
/// A parsed structure from PyPI "HTML" index format listing all available packages.
#[derive(Debug, Clone)]
pub(crate) struct SimpleIndexHtml {
/// The list of project names available in the index.
pub(crate) projects: Vec<PackageName>,
}
impl SimpleIndexHtml {
/// Parse the list of project names from the Simple API index HTML page.
pub(crate) fn parse(text: &str) -> Result<Self, Error> {
let dom = tl::parse(text, tl::ParserOptions::default())?;
// Parse each `<a>` tag to extract the project name.
let parser = dom.parser();
let mut projects = dom
.nodes()
.iter()
.filter_map(|node| node.as_tag())
.filter(|link| link.name().as_bytes() == b"a")
.filter_map(|link| Self::parse_anchor_project_name(link, parser))
.collect::<Vec<_>>();
// Sort for deterministic ordering.
projects.sort_unstable();
Ok(Self { projects })
}
/// Parse a project name from an `<a>` tag.
///
/// Returns `None` if the `<a>` doesn't have an `href` attribute or text content.
fn parse_anchor_project_name(link: &HTMLTag, parser: &tl::Parser) -> Option<PackageName> {
// Extract the href.
link.attributes()
.get("href")
.flatten()
.filter(|bytes| !bytes.as_bytes().is_empty())?;
// Extract the text content, which should be the project name.
let inner_text = link.inner_text(parser);
let project_name = inner_text.trim();
if project_name.is_empty() {
return None;
}
PackageName::from_str(project_name).ok()
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
#[error(transparent)]
FromUtf8(#[from] std::string::FromUtf8Error),
#[error("Failed to parse URL: {0}")]
UrlParse(String, #[source] DisplaySafeUrlError),
#[error(transparent)]
HtmlParse(#[from] tl::ParseError),
#[error("Missing href attribute on anchor link: `{0}`")]
MissingHref(String),
#[error("Expected distribution filename as last path component of URL: {0}")]
MissingFilename(String),
#[error("Expected distribution filename to be UTF-8: {0}")]
UnsupportedFilename(String),
#[error("Missing hash attribute on URL: {0}")]
MissingHash(String),
#[error(transparent)]
FragmentParse(#[from] HashError),
#[error("Invalid `requires-python` specifier: {0}")]
Pep440(#[source] uv_pep440::VersionSpecifiersParseError),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_sha256() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#sha256=6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: Some(
"6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61",
),
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_md5() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#md5=6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: Some(
"6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61",
),
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_base() {
let text = r#"
<!DOCTYPE html>
<html>
<head>
<base href="https://index.python.org/">
</head>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#sha256=6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"index.python.org",
),
),
port: None,
path: "/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: Some(
"6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61",
),
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_escaped_fragment() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2+233fca715f49-py3-none-any.whl#sha256=6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61">Jinja2-3.1.2+233fca715f49-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2+233fca715f49-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: Some(
"6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61",
),
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2+233fca715f49-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_encoded_fragment() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#sha256%3D4095ada29e51070f7d199a0a5bdf5c8d8e238e03f0bf4dcc02571e78c9ae800d">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: Some(
"4095ada29e51070f7d199a0a5bdf5c8d8e238e03f0bf4dcc02571e78c9ae800d",
),
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_quoted_filepath() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="cpu/torchtext-0.17.0%2Bcpu-cp39-cp39-win_amd64.whl">cpu/torchtext-0.17.0%2Bcpu-cp39-cp39-win_amd64.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "torchtext-0.17.0+cpu-cp39-cp39-win_amd64.whl",
hashes: Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "cpu/torchtext-0.17.0%2Bcpu-cp39-cp39-win_amd64.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_missing_hash() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_missing_href() {
let text = r"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a>Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
";
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [],
}
"#);
}
#[test]
fn parse_empty_href() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [],
}
"#);
}
#[test]
fn parse_empty_fragment() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_query_string() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl?project=legacy">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base).unwrap();
insta::assert_debug_snapshot!(result, @r#"
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: None,
sha384: None,
sha512: None,
blake2b: None,
},
requires_python: None,
size: None,
upload_time: None,
url: "/whl/Jinja2-3.1.2-py3-none-any.whl?project=legacy",
yanked: None,
},
],
}
"#);
}
#[test]
fn parse_unknown_fragment() {
let text = r#"
<!DOCTYPE html>
<html>
<body>
<h1>Links for jinja2</h1>
<a href="/whl/Jinja2-3.1.2-py3-none-any.whl#main">Jinja2-3.1.2-py3-none-any.whl</a><br/>
</body>
</html>
<!--TIMESTAMP 1703347410-->
"#;
let base = DisplaySafeUrl::parse("https://download.pytorch.org/whl/jinja2/").unwrap();
let result = SimpleDetailHTML::parse(text, &base);
insta::assert_debug_snapshot!(result, @r#"
Ok(
SimpleDetailHTML {
base: BaseUrl(
DisplaySafeUrl {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(
Domain(
"download.pytorch.org",
),
),
port: None,
path: "/whl/jinja2/",
query: None,
fragment: None,
},
),
files: [
PypiFile {
core_metadata: None,
filename: "Jinja2-3.1.2-py3-none-any.whl",
hashes: Hashes {
md5: None,
sha256: None,
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | true |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-client/src/lib.rs | crates/uv-client/src/lib.rs | pub use base_client::{
AuthIntegration, BaseClient, BaseClientBuilder, DEFAULT_MAX_REDIRECTS, DEFAULT_RETRIES,
ExtraMiddleware, RedirectClientWithMiddleware, RedirectPolicy, RequestBuilder,
RetryParsingError, RetryState, UvRetryableStrategy,
};
pub use cached_client::{CacheControl, CachedClient, CachedClientError, DataWithCachePolicy};
pub use error::{Error, ErrorKind, WrappedReqwestError};
pub use flat_index::{FlatIndexClient, FlatIndexEntries, FlatIndexEntry, FlatIndexError};
pub use linehaul::LineHaul;
pub use registry_client::{
Connectivity, MetadataFormat, RegistryClient, RegistryClientBuilder, SimpleDetailMetadata,
SimpleDetailMetadatum, SimpleIndexMetadata, VersionFiles,
};
pub use rkyvutil::{Deserializer, OwnedArchive, Serializer, Validator};
mod base_client;
mod cached_client;
mod error;
mod flat_index;
mod html;
mod httpcache;
mod linehaul;
mod middleware;
mod registry_client;
mod remote_metadata;
mod rkyvutil;
mod tls;
| 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-client/src/linehaul.rs | crates/uv-client/src/linehaul.rs | use std::env;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use uv_pep508::MarkerEnvironment;
use uv_platform_tags::{Os, Platform};
use uv_static::EnvVars;
use uv_version::version;
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Installer {
pub name: Option<String>,
pub version: Option<String>,
pub subcommand: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Implementation {
pub name: Option<String>,
pub version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Libc {
pub lib: Option<String>,
pub version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Distro {
pub name: Option<String>,
pub version: Option<String>,
pub id: Option<String>,
pub libc: Option<Libc>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct System {
pub name: Option<String>,
pub release: Option<String>,
}
/// Linehaul structs were derived from
/// <https://github.com/pypi/linehaul-cloud-function/blob/1.0.1/linehaul/ua/datastructures.py>.
/// For the sake of parity, the nullability of all the values was kept intact.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct LineHaul {
pub installer: Option<Installer>,
pub python: Option<String>,
pub implementation: Option<Implementation>,
pub distro: Option<Distro>,
pub system: Option<System>,
pub cpu: Option<String>,
pub openssl_version: Option<String>,
pub setuptools_version: Option<String>,
pub rustc_version: Option<String>,
pub ci: Option<bool>,
}
/// Implements Linehaul information format as defined by
/// <https://github.com/pypa/pip/blob/24.0/src/pip/_internal/network/session.py#L109>.
/// This metadata is added to the user agent to enrich PyPI statistics.
impl LineHaul {
/// Initializes Linehaul information based on PEP 508 markers.
#[instrument(name = "linehaul", skip_all)]
pub fn new(
markers: Option<&MarkerEnvironment>,
platform: Option<&Platform>,
subcommand: Option<Vec<String>>,
) -> Self {
// https://github.com/pypa/pip/blob/24.0/src/pip/_internal/network/session.py#L87
let looks_like_ci = [
EnvVars::BUILD_BUILDID,
EnvVars::BUILD_ID,
EnvVars::CI,
EnvVars::PIP_IS_CI,
]
.iter()
.find_map(|&var_name| env::var(var_name).ok().map(|_| true));
let libc = match platform.map(Platform::os) {
Some(Os::Manylinux { major, minor }) => Some(Libc {
lib: Some("glibc".to_string()),
version: Some(format!("{major}.{minor}")),
}),
Some(Os::Musllinux { major, minor }) => Some(Libc {
lib: Some("musl".to_string()),
version: Some(format!("{major}.{minor}")),
}),
_ => None,
};
// Build Distro as Linehaul expects.
let distro: Option<Distro> = if cfg!(target_os = "linux") {
// Gather distribution info from /etc/os-release.
sys_info::linux_os_release().ok().map(|info| Distro {
// e.g., Jammy, Focal, etc.
id: info.version_codename,
// e.g., Ubuntu, Fedora, etc.
name: info.name,
// e.g., 22.04, etc.
version: info.version_id,
// e.g., glibc 2.38, musl 1.2
libc,
})
} else if cfg!(target_os = "macos") {
let version = match platform.map(Platform::os) {
Some(Os::Macos { major, minor }) => Some(format!("{major}.{minor}")),
_ => None,
};
Some(Distro {
// N/A
id: None,
// pip hardcodes distro name to macOS.
name: Some("macOS".to_string()),
// Same as python's platform.mac_ver()[0].
version,
// N/A
libc: None,
})
} else {
// Always empty on Windows.
None
};
Self {
installer: Option::from(Installer {
name: Some("uv".to_string()),
version: Some(version().to_string()),
subcommand,
}),
python: markers.map(|markers| markers.python_full_version().version.to_string()),
implementation: Option::from(Implementation {
name: markers.map(|markers| markers.platform_python_implementation().to_string()),
version: markers.map(|markers| markers.python_full_version().version.to_string()),
}),
distro,
system: Option::from(System {
name: markers.map(|markers| markers.platform_system().to_string()),
release: markers.map(|markers| markers.platform_release().to_string()),
}),
cpu: markers.map(|markers| markers.platform_machine().to_string()),
// Should probably always be None in uv.
openssl_version: None,
// Should probably always be None in uv.
setuptools_version: None,
// Calling rustc --version is likely too slow.
rustc_version: None,
ci: looks_like_ci,
}
}
}
| 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-client/src/rkyvutil.rs | crates/uv-client/src/rkyvutil.rs | /*!
Defines some helpers for use with `rkyv`.
# Owned archived type
Typical usage patterns with rkyv involve using an `&Archived<T>`, where values
of that type are cast from a `&[u8]`. The owned archive type in this module
effectively provides a way to use `Archive<T>` without needing to worry about
the lifetime of the buffer it's attached to. This works by making the owned
archive type own the buffer itself. It then provides convenient routines for
serializing and deserializing.
*/
use rkyv::{
Archive, Deserialize, Portable, Serialize,
api::high::{HighDeserializer, HighSerializer, HighValidator},
bytecheck::CheckBytes,
rancor,
ser::allocator::ArenaHandle,
util::AlignedVec,
};
use crate::{Error, ErrorKind};
/// A convenient alias for the rkyv serializer used by `uv-client`.
///
/// This utilizes rkyv's `HighSerializer` but fixes its type parameters where
/// possible since we don't need the full flexibility of a generic serializer.
pub type Serializer<'a> = HighSerializer<AlignedVec, ArenaHandle<'a>, rancor::Error>;
/// A convenient alias for the rkyv deserializer used by `uv-client`.
///
/// This utilizes rkyv's `HighDeserializer` but fixes its type parameters
/// where possible since we don't need the full flexibility of a generic
/// deserializer.
pub type Deserializer = HighDeserializer<rancor::Error>;
/// A convenient alias for the rkyv validator used by `uv-client`.
///
/// This utilizes rkyv's `HighValidator` but fixes its type parameters where
/// possible since we don't need the full flexibility of a generic validator.
pub type Validator<'a> = HighValidator<'a, rancor::Error>;
/// An owned archived type.
///
/// This type is effectively an owned version of `Archived<A>`. Normally, when
/// one gets an archived type from a buffer, the archive type is bound to the
/// lifetime of the buffer. This effectively provides a home for that buffer so
/// that one can pass around an archived type as if it were owned.
///
/// Constructing the type requires validating the bytes are a valid
/// representation of an `Archived<A>`, but subsequent accesses (via deref) are
/// free.
///
/// Note that this type makes a number of assumptions about the specific
/// serializer, deserializer and validator used. This type could be made
/// more generic, but it's not clear we need that in uv. By making our
/// choices concrete here, we make use of this type much simpler to understand.
/// Unfortunately, AG couldn't find a way of making the trait bounds simpler,
/// so if `OwnedVec` is being used in trait implementations, the traits bounds
/// will likely need to be copied from here.
#[derive(Debug)]
pub struct OwnedArchive<A> {
raw: AlignedVec,
archive: std::marker::PhantomData<A>,
}
impl<A> OwnedArchive<A>
where
A: Archive + for<'a> Serialize<Serializer<'a>>,
A::Archived: Portable + Deserialize<A, Deserializer> + for<'a> CheckBytes<Validator<'a>>,
{
/// Create a new owned archived value from the raw aligned bytes of the
/// serialized representation of an `A`.
///
/// # Errors
///
/// If the bytes fail validation (e.g., contains unaligned pointers or
/// strings aren't valid UTF-8), then this returns an error.
pub fn new(raw: AlignedVec) -> Result<Self, Error> {
// We convert the error to a simple string because... the error type
// does not implement Send. And I don't think we really need to keep
// the error type around anyway.
let _ = rkyv::access::<A::Archived, rancor::Error>(&raw)
.map_err(|e| ErrorKind::ArchiveRead(e.to_string()))?;
Ok(Self {
raw,
archive: std::marker::PhantomData,
})
}
/// Like `OwnedArchive::new`, but reads the value from the given reader.
///
/// Note that this consumes the entirety of the given reader.
///
/// # Errors
///
/// If the bytes fail validation (e.g., contains unaligned pointers or
/// strings aren't valid UTF-8), then this returns an error.
pub fn from_reader<R: std::io::Read>(mut rdr: R) -> Result<Self, Error> {
let mut buf = AlignedVec::with_capacity(1024);
buf.extend_from_reader(&mut rdr).map_err(ErrorKind::Io)?;
Self::new(buf)
}
/// Creates an owned archive value from the unarchived value.
///
/// # Errors
///
/// This can fail if creating an archive for the given type fails.
/// Currently, this, at minimum, includes cases where an `A` contains a
/// `PathBuf` that is not valid UTF-8.
pub fn from_unarchived(unarchived: &A) -> Result<Self, Error> {
let raw = rkyv::to_bytes::<rancor::Error>(unarchived)
.map_err(|e| ErrorKind::ArchiveWrite(e.to_string()))?;
Ok(Self {
raw,
archive: std::marker::PhantomData,
})
}
/// Write the underlying bytes of this archived value to the given writer.
///
/// Note that because this type has a `Deref` impl, this method requires
/// fully-qualified syntax. So, if `o` is an `OwnedValue`, then use
/// `OwnedValue::write(&o, wtr)`.
///
/// # Errors
///
/// Any failures from writing are returned to the caller.
pub fn write<W: std::io::Write>(this: &Self, mut wtr: W) -> Result<(), Error> {
Ok(wtr.write_all(&this.raw).map_err(ErrorKind::Io)?)
}
/// Returns the raw underlying bytes of this owned archive value.
///
/// They are guaranteed to be a valid serialization of `Archived<A>`.
///
/// Note that because this type has a `Deref` impl, this method requires
/// fully-qualified syntax. So, if `o` is an `OwnedValue`, then use
/// `OwnedValue::as_bytes(&o)`.
pub fn as_bytes(this: &Self) -> &[u8] {
&this.raw
}
/// Deserialize this owned archived value into the original
/// `SimpleMetadata`.
///
/// Note that because this type has a `Deref` impl, this method requires
/// fully-qualified syntax. So, if `o` is an `OwnedValue`, then use
/// `OwnedValue::deserialize(&o)`.
pub fn deserialize(this: &Self) -> A {
rkyv::deserialize(&**this).expect("valid archive must deserialize correctly")
}
}
impl<A> std::ops::Deref for OwnedArchive<A>
where
A: Archive + for<'a> Serialize<Serializer<'a>>,
A::Archived: Portable + Deserialize<A, Deserializer> + for<'a> CheckBytes<Validator<'a>>,
{
type Target = A::Archived;
fn deref(&self) -> &A::Archived {
// SAFETY: We've validated that our underlying buffer is a valid
// archive for SimpleMetadata in the constructor, so we can skip
// validation here. Since we don't mutate the buffer, this conversion
// is guaranteed to be correct.
#[allow(unsafe_code)]
unsafe {
rkyv::access_unchecked::<A::Archived>(&self.raw)
}
}
}
| 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-client/src/base_client.rs | crates/uv-client/src/base_client.rs | use std::error::Error;
use std::fmt::Debug;
use std::fmt::Write;
use std::num::ParseIntError;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use std::{env, io, iter};
use anyhow::anyhow;
use http::{
HeaderMap, HeaderName, HeaderValue, Method, StatusCode,
header::{
AUTHORIZATION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, LOCATION,
PROXY_AUTHORIZATION, REFERER, TRANSFER_ENCODING, WWW_AUTHENTICATE,
},
};
use itertools::Itertools;
use reqwest::{Client, ClientBuilder, IntoUrl, Proxy, Request, Response, multipart};
use reqwest_middleware::{ClientWithMiddleware, Middleware};
use reqwest_retry::policies::ExponentialBackoff;
use reqwest_retry::{
RetryPolicy, RetryTransientMiddleware, Retryable, RetryableStrategy, default_on_request_error,
default_on_request_success,
};
use thiserror::Error;
use tracing::{debug, trace};
use url::ParseError;
use url::Url;
use uv_auth::{AuthMiddleware, Credentials, CredentialsCache, Indexes, PyxTokenStore};
use uv_configuration::{KeyringProviderType, TrustedHost};
use uv_fs::Simplified;
use uv_pep508::MarkerEnvironment;
use uv_platform_tags::Platform;
use uv_preview::Preview;
use uv_redacted::DisplaySafeUrl;
use uv_redacted::DisplaySafeUrlError;
use uv_static::EnvVars;
use uv_version::version;
use uv_warnings::warn_user_once;
use crate::linehaul::LineHaul;
use crate::middleware::OfflineMiddleware;
use crate::tls::read_identity;
use crate::{Connectivity, WrappedReqwestError};
pub const DEFAULT_RETRIES: u32 = 3;
/// Maximum number of redirects to follow before giving up.
///
/// This is the default used by [`reqwest`].
pub const DEFAULT_MAX_REDIRECTS: u32 = 10;
/// Selectively skip parts or the entire auth middleware.
#[derive(Debug, Clone, Copy, Default)]
pub enum AuthIntegration {
/// Run the full auth middleware, including sending an unauthenticated request first.
#[default]
Default,
/// Send only an authenticated request without cloning and sending an unauthenticated request
/// first. Errors if no credentials were found.
OnlyAuthenticated,
/// Skip the auth middleware entirely. The caller is responsible for managing authentication.
NoAuthMiddleware,
}
/// A builder for an [`BaseClient`].
#[derive(Debug, Clone)]
pub struct BaseClientBuilder<'a> {
keyring: KeyringProviderType,
preview: Preview,
allow_insecure_host: Vec<TrustedHost>,
native_tls: bool,
built_in_root_certs: bool,
retries: u32,
pub connectivity: Connectivity,
markers: Option<&'a MarkerEnvironment>,
platform: Option<&'a Platform>,
auth_integration: AuthIntegration,
/// Global authentication cache for a uv invocation to share credentials across uv clients.
credentials_cache: Arc<CredentialsCache>,
indexes: Indexes,
timeout: Duration,
extra_middleware: Option<ExtraMiddleware>,
proxies: Vec<Proxy>,
redirect_policy: RedirectPolicy,
/// Whether credentials should be propagated during cross-origin redirects.
///
/// A policy allowing propagation is insecure and should only be available for test code.
cross_origin_credential_policy: CrossOriginCredentialsPolicy,
/// Optional custom reqwest client to use instead of creating a new one.
custom_client: Option<Client>,
/// uv subcommand in which this client is being used
subcommand: Option<Vec<String>>,
}
/// The policy for handling HTTP redirects.
#[derive(Debug, Default, Clone, Copy)]
pub enum RedirectPolicy {
/// Use reqwest's built-in redirect handling. This bypasses our custom middleware
/// on redirect.
#[default]
BypassMiddleware,
/// Handle redirects manually, re-triggering our custom middleware for each request.
RetriggerMiddleware,
/// No redirect for non-cloneable (e.g., streaming) requests with custom redirect logic.
NoRedirect,
}
impl RedirectPolicy {
pub fn reqwest_policy(self) -> reqwest::redirect::Policy {
match self {
Self::BypassMiddleware => reqwest::redirect::Policy::default(),
Self::RetriggerMiddleware => reqwest::redirect::Policy::none(),
Self::NoRedirect => reqwest::redirect::Policy::none(),
}
}
}
/// A list of user-defined middlewares to be applied to the client.
#[derive(Clone)]
pub struct ExtraMiddleware(pub Vec<Arc<dyn Middleware>>);
impl Debug for ExtraMiddleware {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExtraMiddleware")
.field("0", &format!("{} middlewares", self.0.len()))
.finish()
}
}
impl Default for BaseClientBuilder<'_> {
fn default() -> Self {
Self {
keyring: KeyringProviderType::default(),
preview: Preview::default(),
allow_insecure_host: vec![],
native_tls: false,
built_in_root_certs: false,
connectivity: Connectivity::Online,
retries: DEFAULT_RETRIES,
markers: None,
platform: None,
auth_integration: AuthIntegration::default(),
credentials_cache: Arc::new(CredentialsCache::default()),
indexes: Indexes::new(),
timeout: Duration::from_secs(30),
extra_middleware: None,
proxies: vec![],
redirect_policy: RedirectPolicy::default(),
cross_origin_credential_policy: CrossOriginCredentialsPolicy::Secure,
custom_client: None,
subcommand: None,
}
}
}
impl<'a> BaseClientBuilder<'a> {
pub fn new(
connectivity: Connectivity,
native_tls: bool,
allow_insecure_host: Vec<TrustedHost>,
preview: Preview,
timeout: Duration,
retries: u32,
) -> Self {
Self {
preview,
allow_insecure_host,
native_tls,
retries,
connectivity,
timeout,
..Self::default()
}
}
/// Use a custom reqwest client instead of creating a new one.
///
/// This allows you to provide your own reqwest client with custom configuration.
/// Note that some configuration options from this builder will still be applied
/// to the client via middleware.
#[must_use]
pub fn custom_client(mut self, client: Client) -> Self {
self.custom_client = Some(client);
self
}
#[must_use]
pub fn keyring(mut self, keyring_type: KeyringProviderType) -> Self {
self.keyring = keyring_type;
self
}
#[must_use]
pub fn allow_insecure_host(mut self, allow_insecure_host: Vec<TrustedHost>) -> Self {
self.allow_insecure_host = allow_insecure_host;
self
}
#[must_use]
pub fn connectivity(mut self, connectivity: Connectivity) -> Self {
self.connectivity = connectivity;
self
}
#[must_use]
pub fn retries(mut self, retries: u32) -> Self {
self.retries = retries;
self
}
#[must_use]
pub fn native_tls(mut self, native_tls: bool) -> Self {
self.native_tls = native_tls;
self
}
#[must_use]
pub fn built_in_root_certs(mut self, built_in_root_certs: bool) -> Self {
self.built_in_root_certs = built_in_root_certs;
self
}
#[must_use]
pub fn markers(mut self, markers: &'a MarkerEnvironment) -> Self {
self.markers = Some(markers);
self
}
#[must_use]
pub fn platform(mut self, platform: &'a Platform) -> Self {
self.platform = Some(platform);
self
}
#[must_use]
pub fn auth_integration(mut self, auth_integration: AuthIntegration) -> Self {
self.auth_integration = auth_integration;
self
}
#[must_use]
pub fn indexes(mut self, indexes: Indexes) -> Self {
self.indexes = indexes;
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn extra_middleware(mut self, middleware: ExtraMiddleware) -> Self {
self.extra_middleware = Some(middleware);
self
}
#[must_use]
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.proxies.push(proxy);
self
}
#[must_use]
pub fn redirect(mut self, policy: RedirectPolicy) -> Self {
self.redirect_policy = policy;
self
}
/// Allows credentials to be propagated on cross-origin redirects.
///
/// WARNING: This should only be available for tests. In production code, propagating credentials
/// during cross-origin redirects can lead to security vulnerabilities including credential
/// leakage to untrusted domains.
#[cfg(test)]
#[must_use]
pub fn allow_cross_origin_credentials(mut self) -> Self {
self.cross_origin_credential_policy = CrossOriginCredentialsPolicy::Insecure;
self
}
#[must_use]
pub fn subcommand(mut self, subcommand: Vec<String>) -> Self {
self.subcommand = Some(subcommand);
self
}
pub fn credentials_cache(&self) -> &CredentialsCache {
&self.credentials_cache
}
/// See [`CredentialsCache::store_credentials_from_url`].
pub fn store_credentials_from_url(&self, url: &DisplaySafeUrl) -> bool {
self.credentials_cache.store_credentials_from_url(url)
}
/// See [`CredentialsCache::store_credentials`].
pub fn store_credentials(&self, url: &DisplaySafeUrl, credentials: Credentials) {
self.credentials_cache.store_credentials(url, credentials);
}
pub fn is_native_tls(&self) -> bool {
self.native_tls
}
pub fn is_offline(&self) -> bool {
matches!(self.connectivity, Connectivity::Offline)
}
/// Create a [`RetryPolicy`] for the client.
pub fn retry_policy(&self) -> ExponentialBackoff {
let mut builder = ExponentialBackoff::builder();
if env::var_os(EnvVars::UV_TEST_NO_HTTP_RETRY_DELAY).is_some() {
builder = builder.retry_bounds(Duration::from_millis(0), Duration::from_millis(0));
}
builder.build_with_max_retries(self.retries)
}
pub fn build(&self) -> BaseClient {
let timeout = self.timeout;
debug!("Using request timeout of {}s", timeout.as_secs());
// Use the custom client if provided, otherwise create a new one
let (raw_client, raw_dangerous_client) = match &self.custom_client {
Some(client) => (client.clone(), client.clone()),
None => self.create_secure_and_insecure_clients(timeout),
};
// Wrap in any relevant middleware and handle connectivity.
let client = RedirectClientWithMiddleware {
client: self.apply_middleware(raw_client.clone()),
redirect_policy: self.redirect_policy,
cross_origin_credentials_policy: self.cross_origin_credential_policy,
};
let dangerous_client = RedirectClientWithMiddleware {
client: self.apply_middleware(raw_dangerous_client.clone()),
redirect_policy: self.redirect_policy,
cross_origin_credentials_policy: self.cross_origin_credential_policy,
};
BaseClient {
connectivity: self.connectivity,
allow_insecure_host: self.allow_insecure_host.clone(),
retries: self.retries,
client,
raw_client,
dangerous_client,
raw_dangerous_client,
timeout,
credentials_cache: self.credentials_cache.clone(),
}
}
/// Share the underlying client between two different middleware configurations.
pub fn wrap_existing(&self, existing: &BaseClient) -> BaseClient {
// Wrap in any relevant middleware and handle connectivity.
let client = RedirectClientWithMiddleware {
client: self.apply_middleware(existing.raw_client.clone()),
redirect_policy: self.redirect_policy,
cross_origin_credentials_policy: self.cross_origin_credential_policy,
};
let dangerous_client = RedirectClientWithMiddleware {
client: self.apply_middleware(existing.raw_dangerous_client.clone()),
redirect_policy: self.redirect_policy,
cross_origin_credentials_policy: self.cross_origin_credential_policy,
};
BaseClient {
connectivity: self.connectivity,
allow_insecure_host: self.allow_insecure_host.clone(),
retries: self.retries,
client,
dangerous_client,
raw_client: existing.raw_client.clone(),
raw_dangerous_client: existing.raw_dangerous_client.clone(),
timeout: existing.timeout,
credentials_cache: existing.credentials_cache.clone(),
}
}
fn create_secure_and_insecure_clients(&self, timeout: Duration) -> (Client, Client) {
// Create user agent.
let mut user_agent_string = format!("uv/{}", version());
// Add linehaul metadata.
let linehaul = LineHaul::new(self.markers, self.platform, self.subcommand.clone());
if let Ok(output) = serde_json::to_string(&linehaul) {
let _ = write!(user_agent_string, " {output}");
}
// Checks for the presence of `SSL_CERT_FILE`.
// Certificate loading support is delegated to `rustls-native-certs`.
// See https://github.com/rustls/rustls-native-certs/blob/813790a297ad4399efe70a8e5264ca1b420acbec/src/lib.rs#L118-L125
let ssl_cert_file_exists = env::var_os(EnvVars::SSL_CERT_FILE).is_some_and(|path| {
let path_exists = Path::new(&path).exists();
if !path_exists {
warn_user_once!(
"Ignoring invalid `SSL_CERT_FILE`. File does not exist: {}.",
path.simplified_display().cyan()
);
}
path_exists
});
// Checks for the presence of `SSL_CERT_DIR`.
// Certificate loading support is delegated to `rustls-native-certs`.
// See https://github.com/rustls/rustls-native-certs/blob/813790a297ad4399efe70a8e5264ca1b420acbec/src/lib.rs#L118-L125
let ssl_cert_dir_exists = env::var_os(EnvVars::SSL_CERT_DIR)
.filter(|v| !v.is_empty())
.is_some_and(|dirs| {
// Parse `SSL_CERT_DIR`, with support for multiple entries using
// a platform-specific delimiter (`:` on Unix, `;` on Windows)
let (existing, missing): (Vec<_>, Vec<_>) =
env::split_paths(&dirs).partition(|p| p.exists());
if existing.is_empty() {
let end_note = if missing.len() == 1 {
"The directory does not exist."
} else {
"The entries do not exist."
};
warn_user_once!(
"Ignoring invalid `SSL_CERT_DIR`. {end_note}: {}.",
missing
.iter()
.map(Simplified::simplified_display)
.join(", ")
.cyan()
);
return false;
}
// Warn on any missing entries
if !missing.is_empty() {
let end_note = if missing.len() == 1 {
"The following directory does not exist:"
} else {
"The following entries do not exist:"
};
warn_user_once!(
"Invalid entries in `SSL_CERT_DIR`. {end_note}: {}.",
missing
.iter()
.map(Simplified::simplified_display)
.join(", ")
.cyan()
);
}
// Proceed while ignoring missing entries
true
});
// Create a secure client that validates certificates.
let raw_client = self.create_client(
&user_agent_string,
timeout,
ssl_cert_file_exists,
ssl_cert_dir_exists,
Security::Secure,
self.redirect_policy,
);
// Create an insecure client that accepts invalid certificates.
let raw_dangerous_client = self.create_client(
&user_agent_string,
timeout,
ssl_cert_file_exists,
ssl_cert_dir_exists,
Security::Insecure,
self.redirect_policy,
);
(raw_client, raw_dangerous_client)
}
fn create_client(
&self,
user_agent: &str,
timeout: Duration,
ssl_cert_file_exists: bool,
ssl_cert_dir_exists: bool,
security: Security,
redirect_policy: RedirectPolicy,
) -> Client {
// Configure the builder.
let client_builder = ClientBuilder::new()
.http1_title_case_headers()
.user_agent(user_agent)
.pool_max_idle_per_host(20)
.read_timeout(timeout)
.tls_built_in_root_certs(self.built_in_root_certs)
.redirect(redirect_policy.reqwest_policy());
// If necessary, accept invalid certificates.
let client_builder = match security {
Security::Secure => client_builder,
Security::Insecure => client_builder.danger_accept_invalid_certs(true),
};
let client_builder = if self.native_tls || ssl_cert_file_exists || ssl_cert_dir_exists {
client_builder.tls_built_in_native_certs(true)
} else {
client_builder.tls_built_in_webpki_certs(true)
};
// Configure mTLS.
let client_builder = if let Some(ssl_client_cert) = env::var_os(EnvVars::SSL_CLIENT_CERT) {
match read_identity(&ssl_client_cert) {
Ok(identity) => client_builder.identity(identity),
Err(err) => {
warn_user_once!("Ignoring invalid `SSL_CLIENT_CERT`: {err}");
client_builder
}
}
} else {
client_builder
};
// apply proxies
let mut client_builder = client_builder;
for p in &self.proxies {
client_builder = client_builder.proxy(p.clone());
}
let client_builder = client_builder;
client_builder
.build()
.expect("Failed to build HTTP client.")
}
fn apply_middleware(&self, client: Client) -> ClientWithMiddleware {
match self.connectivity {
Connectivity::Online => {
// Create a base client to using in the authentication middleware.
let base_client = {
let mut client = reqwest_middleware::ClientBuilder::new(client.clone());
// Avoid uncloneable errors with a streaming body during publish.
if self.retries > 0 {
// Initialize the retry strategy.
let retry_strategy = RetryTransientMiddleware::new_with_policy_and_strategy(
self.retry_policy(),
UvRetryableStrategy,
);
client = client.with(retry_strategy);
}
// When supplied, add the extra middleware.
if let Some(extra_middleware) = &self.extra_middleware {
for middleware in &extra_middleware.0 {
client = client.with_arc(middleware.clone());
}
}
client.build()
};
let mut client = reqwest_middleware::ClientBuilder::new(client);
// Avoid uncloneable errors with a streaming body during publish.
if self.retries > 0 {
// Initialize the retry strategy.
let retry_strategy = RetryTransientMiddleware::new_with_policy_and_strategy(
self.retry_policy(),
UvRetryableStrategy,
);
client = client.with(retry_strategy);
}
// When supplied, add the extra middleware.
if let Some(extra_middleware) = &self.extra_middleware {
for middleware in &extra_middleware.0 {
client = client.with_arc(middleware.clone());
}
}
// Initialize the authentication middleware to set headers.
match self.auth_integration {
AuthIntegration::Default => {
let mut auth_middleware = AuthMiddleware::new()
.with_cache_arc(self.credentials_cache.clone())
.with_base_client(base_client)
.with_indexes(self.indexes.clone())
.with_keyring(self.keyring.to_provider())
.with_preview(self.preview);
if let Ok(token_store) = PyxTokenStore::from_settings() {
auth_middleware = auth_middleware.with_pyx_token_store(token_store);
}
client = client.with(auth_middleware);
}
AuthIntegration::OnlyAuthenticated => {
let mut auth_middleware = AuthMiddleware::new()
.with_cache_arc(self.credentials_cache.clone())
.with_base_client(base_client)
.with_indexes(self.indexes.clone())
.with_keyring(self.keyring.to_provider())
.with_preview(self.preview)
.with_only_authenticated(true);
if let Ok(token_store) = PyxTokenStore::from_settings() {
auth_middleware = auth_middleware.with_pyx_token_store(token_store);
}
client = client.with(auth_middleware);
}
AuthIntegration::NoAuthMiddleware => {
// The downstream code uses custom auth logic.
}
}
client.build()
}
Connectivity::Offline => reqwest_middleware::ClientBuilder::new(client)
.with(OfflineMiddleware)
.build(),
}
}
}
/// A base client for HTTP requests
#[derive(Debug, Clone)]
pub struct BaseClient {
/// The underlying HTTP client that enforces valid certificates.
client: RedirectClientWithMiddleware,
/// The underlying HTTP client that accepts invalid certificates.
dangerous_client: RedirectClientWithMiddleware,
/// The HTTP client without middleware.
raw_client: Client,
/// The HTTP client that accepts invalid certificates without middleware.
raw_dangerous_client: Client,
/// The connectivity mode to use.
connectivity: Connectivity,
/// Configured client timeout, in seconds.
timeout: Duration,
/// Hosts that are trusted to use the insecure client.
allow_insecure_host: Vec<TrustedHost>,
/// The number of retries to attempt on transient errors.
retries: u32,
/// Global authentication cache for a uv invocation to share credentials across uv clients.
credentials_cache: Arc<CredentialsCache>,
}
#[derive(Debug, Clone, Copy)]
enum Security {
/// The client should use secure settings, i.e., valid certificates.
Secure,
/// The client should use insecure settings, i.e., skip certificate validation.
Insecure,
}
impl BaseClient {
/// Selects the appropriate client based on the host's trustworthiness.
pub fn for_host(&self, url: &DisplaySafeUrl) -> &RedirectClientWithMiddleware {
if self.disable_ssl(url) {
&self.dangerous_client
} else {
&self.client
}
}
/// Executes a request, applying redirect policy.
pub async fn execute(&self, req: Request) -> reqwest_middleware::Result<Response> {
let client = self.for_host(&DisplaySafeUrl::from_url(req.url().clone()));
client.execute(req).await
}
/// Returns `true` if the host is trusted to use the insecure client.
pub fn disable_ssl(&self, url: &DisplaySafeUrl) -> bool {
self.allow_insecure_host
.iter()
.any(|allow_insecure_host| allow_insecure_host.matches(url))
}
/// The configured client timeout, in seconds.
pub fn timeout(&self) -> Duration {
self.timeout
}
/// The configured connectivity mode.
pub fn connectivity(&self) -> Connectivity {
self.connectivity
}
/// The [`RetryPolicy`] for the client.
pub fn retry_policy(&self) -> ExponentialBackoff {
let mut builder = ExponentialBackoff::builder();
if env::var_os(EnvVars::UV_TEST_NO_HTTP_RETRY_DELAY).is_some() {
builder = builder.retry_bounds(Duration::from_millis(0), Duration::from_millis(0));
}
builder.build_with_max_retries(self.retries)
}
pub fn credentials_cache(&self) -> &CredentialsCache {
&self.credentials_cache
}
}
/// Wrapper around [`ClientWithMiddleware`] that manages redirects.
#[derive(Debug, Clone)]
pub struct RedirectClientWithMiddleware {
client: ClientWithMiddleware,
redirect_policy: RedirectPolicy,
/// Whether credentials should be preserved during cross-origin redirects.
///
/// WARNING: This should only be available for tests. In production code, preserving credentials
/// during cross-origin redirects can lead to security vulnerabilities including credential
/// leakage to untrusted domains.
cross_origin_credentials_policy: CrossOriginCredentialsPolicy,
}
impl RedirectClientWithMiddleware {
/// Convenience method to make a `GET` request to a URL.
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder<'_> {
RequestBuilder::new(self.client.get(url), self)
}
/// Convenience method to make a `POST` request to a URL.
pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder<'_> {
RequestBuilder::new(self.client.post(url), self)
}
/// Convenience method to make a `HEAD` request to a URL.
pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder<'_> {
RequestBuilder::new(self.client.head(url), self)
}
/// Executes a request, applying the redirect policy.
pub async fn execute(&self, req: Request) -> reqwest_middleware::Result<Response> {
match self.redirect_policy {
RedirectPolicy::BypassMiddleware => self.client.execute(req).await,
RedirectPolicy::RetriggerMiddleware => self.execute_with_redirect_handling(req).await,
RedirectPolicy::NoRedirect => self.client.execute(req).await,
}
}
/// Executes a request. If the response is a redirect (one of HTTP 301, 302, 303, 307, or 308), the
/// request is executed again with the redirect location URL (up to a maximum number of
/// redirects).
///
/// Unlike the built-in reqwest redirect policies, this sends the redirect request through the
/// entire middleware pipeline again.
///
/// See RFC 7231 7.1.2 <https://www.rfc-editor.org/rfc/rfc7231#section-7.1.2> for details on
/// redirect semantics.
async fn execute_with_redirect_handling(
&self,
req: Request,
) -> reqwest_middleware::Result<Response> {
let mut request = req;
let mut redirects = 0;
let max_redirects = DEFAULT_MAX_REDIRECTS;
loop {
let result = self
.client
.execute(request.try_clone().expect("HTTP request must be cloneable"))
.await;
let Ok(response) = result else {
return result;
};
if redirects >= max_redirects {
return Ok(response);
}
let Some(redirect_request) =
request_into_redirect(request, &response, self.cross_origin_credentials_policy)?
else {
return Ok(response);
};
redirects += 1;
request = redirect_request;
}
}
pub fn raw_client(&self) -> &ClientWithMiddleware {
&self.client
}
}
impl From<RedirectClientWithMiddleware> for ClientWithMiddleware {
fn from(item: RedirectClientWithMiddleware) -> Self {
item.client
}
}
/// Check if this is should be a redirect and, if so, return a new redirect request.
///
/// This implementation is based on the [`reqwest`] crate redirect implementation.
/// It takes ownership of the original [`Request`] and mutates it to create the new
/// redirect [`Request`].
fn request_into_redirect(
mut req: Request,
res: &Response,
cross_origin_credentials_policy: CrossOriginCredentialsPolicy,
) -> reqwest_middleware::Result<Option<Request>> {
let original_req_url = DisplaySafeUrl::from_url(req.url().clone());
let status = res.status();
let should_redirect = match status {
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT => true,
StatusCode::SEE_OTHER => {
// Per RFC 7231, HTTP 303 is intended for the user agent
// to perform a GET or HEAD request to the redirect target.
// Historically, some browsers also changed method from POST
// to GET on 301 or 302, but this is not required by RFC 7231
// and was not intended by the HTTP spec.
*req.body_mut() = None;
for header in &[
TRANSFER_ENCODING,
CONTENT_ENCODING,
CONTENT_TYPE,
CONTENT_LENGTH,
] {
req.headers_mut().remove(header);
}
match *req.method() {
Method::GET | Method::HEAD => {}
_ => {
*req.method_mut() = Method::GET;
}
}
true
}
_ => false,
};
if !should_redirect {
return Ok(None);
}
let location = res
.headers()
.get(LOCATION)
.ok_or(reqwest_middleware::Error::Middleware(anyhow!(
"Server returned redirect (HTTP {status}) without destination URL. This may indicate a server configuration issue"
)))?
.to_str()
.map_err(|_| {
reqwest_middleware::Error::Middleware(anyhow!(
"Invalid HTTP {status} 'Location' value: must only contain visible ascii characters"
))
})?;
let mut redirect_url = match DisplaySafeUrl::parse(location) {
Ok(url) => url,
// Per RFC 7231, URLs should be resolved against the request URL.
Err(DisplaySafeUrlError::Url(ParseError::RelativeUrlWithoutBase)) => original_req_url.join(location).map_err(|err| {
reqwest_middleware::Error::Middleware(anyhow!(
"Invalid HTTP {status} 'Location' value `{location}` relative to `{original_req_url}`: {err}"
))
})?,
Err(err) => {
return Err(reqwest_middleware::Error::Middleware(anyhow!(
"Invalid HTTP {status} 'Location' value `{location}`: {err}"
)));
}
};
// Per RFC 7231, fragments must be propagated
if let Some(fragment) = original_req_url.fragment() {
redirect_url.set_fragment(Some(fragment));
}
// Ensure the URL is a valid HTTP URI.
if let Err(err) = redirect_url.as_str().parse::<http::Uri>() {
return Err(reqwest_middleware::Error::Middleware(anyhow!(
"HTTP {status} 'Location' value `{redirect_url}` is not a valid HTTP URI: {err}"
)));
}
if redirect_url.scheme() != "http" && redirect_url.scheme() != "https" {
return Err(reqwest_middleware::Error::Middleware(anyhow!(
"Invalid HTTP {status} 'Location' value `{redirect_url}`: scheme needs to be https or http"
)));
}
let mut headers = HeaderMap::new();
std::mem::swap(req.headers_mut(), &mut headers);
let cross_host = redirect_url.host_str() != original_req_url.host_str()
| 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-client/src/middleware.rs | crates/uv-client/src/middleware.rs | use http::Extensions;
use std::fmt::Debug;
use uv_redacted::DisplaySafeUrl;
use reqwest::{Request, Response};
use reqwest_middleware::{Middleware, Next};
/// A custom error type for the offline middleware.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct OfflineError {
url: DisplaySafeUrl,
}
impl OfflineError {
/// Returns the URL that caused the error.
pub(crate) fn url(&self) -> &DisplaySafeUrl {
&self.url
}
}
impl std::fmt::Display for OfflineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Network connectivity is disabled, but the requested data wasn't found in the cache for: `{}`",
self.url
)
}
}
impl std::error::Error for OfflineError {}
/// A middleware that always returns an error indicating that the client is offline.
pub(crate) struct OfflineMiddleware;
#[async_trait::async_trait]
impl Middleware for OfflineMiddleware {
async fn handle(
&self,
req: Request,
_extensions: &mut Extensions,
_next: Next<'_>,
) -> reqwest_middleware::Result<Response> {
Err(reqwest_middleware::Error::Middleware(
OfflineError {
url: DisplaySafeUrl::from_url(req.url().clone()),
}
.into(),
))
}
}
| 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-client/src/error.rs | crates/uv-client/src/error.rs | use async_http_range_reader::AsyncHttpRangeReaderError;
use async_zip::error::ZipError;
use serde::Deserialize;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::path::PathBuf;
use uv_cache::Error as CacheError;
use uv_distribution_filename::{WheelFilename, WheelFilenameError};
use uv_normalize::PackageName;
use uv_redacted::DisplaySafeUrl;
use crate::middleware::OfflineError;
use crate::{FlatIndexError, html};
/// RFC 9457 Problem Details for HTTP APIs
///
/// This structure represents the standard format for machine-readable details
/// of errors in HTTP response bodies as defined in RFC 9457.
#[derive(Debug, Clone, Deserialize)]
pub struct ProblemDetails {
/// A URI reference that identifies the problem type.
/// When dereferenced, it SHOULD provide human-readable documentation for the problem type.
#[serde(rename = "type", default = "default_problem_type")]
pub problem_type: String,
/// A short, human-readable summary of the problem type.
pub title: Option<String>,
/// The HTTP status code generated by the origin server for this occurrence of the problem.
pub status: Option<u16>,
/// A human-readable explanation specific to this occurrence of the problem.
pub detail: Option<String>,
/// A URI reference that identifies the specific occurrence of the problem.
pub instance: Option<String>,
}
/// Default problem type URI as per RFC 9457
#[inline]
fn default_problem_type() -> String {
"about:blank".to_string()
}
impl ProblemDetails {
/// Get a human-readable description of the problem
pub fn description(&self) -> Option<String> {
match self {
Self {
title: Some(title),
detail: Some(detail),
..
} => Some(format!("Server message: {title}, {detail}")),
Self {
title: Some(title), ..
} => Some(format!("Server message: {title}")),
Self {
detail: Some(detail),
..
} => Some(format!("Server message: {detail}")),
Self {
status: Some(status),
..
} => Some(format!("HTTP error {status}")),
_ => None,
}
}
}
#[derive(Debug)]
pub struct Error {
kind: Box<ErrorKind>,
retries: u32,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.retries > 0 {
write!(
f,
"Request failed after {retries} {subject}",
retries = self.retries,
subject = if self.retries > 1 { "retries" } else { "retry" }
)
} else {
Display::fmt(&self.kind, f)
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if self.retries > 0 {
Some(&self.kind)
} else {
self.kind.source()
}
}
}
impl Error {
/// Create a new [`Error`] with the given [`ErrorKind`] and number of retries.
pub fn new(kind: ErrorKind, retries: u32) -> Self {
Self {
kind: Box::new(kind),
retries,
}
}
/// Return the number of retries that were attempted before this error was returned.
pub fn retries(&self) -> u32 {
self.retries
}
/// Convert this error into an [`ErrorKind`].
pub fn into_kind(self) -> ErrorKind {
*self.kind
}
/// Return the [`ErrorKind`] of this error.
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
pub(crate) fn with_retries(mut self, retries: u32) -> Self {
self.retries = retries;
self
}
/// Create a new error from a JSON parsing error.
pub(crate) fn from_json_err(err: serde_json::Error, url: DisplaySafeUrl) -> Self {
ErrorKind::BadJson { source: err, url }.into()
}
/// Create a new error from an HTML parsing error.
pub(crate) fn from_html_err(err: html::Error, url: DisplaySafeUrl) -> Self {
ErrorKind::BadHtml { source: err, url }.into()
}
/// Create a new error from a `MessagePack` parsing error.
pub(crate) fn from_msgpack_err(err: rmp_serde::decode::Error, url: DisplaySafeUrl) -> Self {
ErrorKind::BadMessagePack { source: err, url }.into()
}
/// Returns `true` if this error corresponds to an offline error.
pub(crate) fn is_offline(&self) -> bool {
matches!(&*self.kind, ErrorKind::Offline(_))
}
/// Returns `true` if this error corresponds to an I/O "not found" error.
pub(crate) fn is_file_not_exists(&self) -> bool {
let ErrorKind::Io(err) = &*self.kind else {
return false;
};
matches!(err.kind(), std::io::ErrorKind::NotFound)
}
/// Returns `true` if the error is due to an SSL error.
pub fn is_ssl(&self) -> bool {
matches!(&*self.kind, ErrorKind::WrappedReqwestError(.., err) if err.is_ssl())
}
/// Returns `true` if the error is due to the server not supporting HTTP range requests.
pub fn is_http_range_requests_unsupported(&self) -> bool {
match &*self.kind {
// The server doesn't support range requests (as reported by the `HEAD` check).
ErrorKind::AsyncHttpRangeReader(
_,
AsyncHttpRangeReaderError::HttpRangeRequestUnsupported,
) => {
return true;
}
// The server doesn't support range requests (it doesn't return the necessary headers).
ErrorKind::AsyncHttpRangeReader(
_,
AsyncHttpRangeReaderError::ContentLengthMissing
| AsyncHttpRangeReaderError::ContentRangeMissing,
) => {
return true;
}
// The server returned a "Method Not Allowed" error, indicating it doesn't support
// HEAD requests, so we can't check for range requests.
ErrorKind::WrappedReqwestError(_, err) => {
if let Some(status) = err.status() {
// If the server doesn't support HEAD requests, we can't check for range
// requests.
if status == reqwest::StatusCode::METHOD_NOT_ALLOWED {
return true;
}
// In some cases, registries return a 404 for HEAD requests when they're not
// supported. In the worst case, we'll now just proceed to attempt to stream the
// entire file, so it's fine to be somewhat lenient here.
if status == reqwest::StatusCode::NOT_FOUND {
return true;
}
// In some cases, registries (like PyPICloud) return a 403 for HEAD requests
// when they're not supported. Again, it's better to be lenient here.
if status == reqwest::StatusCode::FORBIDDEN {
return true;
}
// In some cases, registries (like Alibaba Cloud) return a 400 for HEAD requests
// when they're not supported. Again, it's better to be lenient here.
if status == reqwest::StatusCode::BAD_REQUEST {
return true;
}
}
}
// The server doesn't support range requests, but we only discovered this while
// unzipping due to erroneous server behavior.
ErrorKind::Zip(_, ZipError::UpstreamReadError(err)) => {
if let Some(inner) = err.get_ref() {
if let Some(inner) = inner.downcast_ref::<AsyncHttpRangeReaderError>() {
if matches!(
inner,
AsyncHttpRangeReaderError::HttpRangeRequestUnsupported
) {
return true;
}
}
}
}
_ => {}
}
false
}
/// Returns `true` if the error is due to the server not supporting HTTP streaming. Most
/// commonly, this is due to serving ZIP files with features that are incompatible with
/// streaming, like data descriptors.
pub fn is_http_streaming_unsupported(&self) -> bool {
matches!(
&*self.kind,
ErrorKind::Zip(_, ZipError::FeatureNotSupported(_))
)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self {
kind: Box::new(kind),
retries: 0,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
#[error(transparent)]
InvalidUrl(#[from] uv_distribution_types::ToUrlError),
#[error(transparent)]
Flat(#[from] FlatIndexError),
#[error("Expected a file URL, but received: {0}")]
NonFileUrl(DisplaySafeUrl),
#[error("Expected an index URL, but received non-base URL: {0}")]
CannotBeABase(DisplaySafeUrl),
#[error("Failed to read metadata: `{0}`")]
Metadata(String, #[source] uv_metadata::Error),
#[error("{0} isn't available locally, but making network requests to registries was banned")]
NoIndex(String),
/// The package was not found in the registry.
///
/// Make sure the package name is spelled correctly and that you've
/// configured the right registry to fetch it from.
#[error("Package `{0}` was not found in the registry")]
RemotePackageNotFound(PackageName),
/// The package was not found in the local (file-based) index.
#[error("Package `{0}` was not found in the local index")]
LocalPackageNotFound(PackageName),
/// The root was not found in the local (file-based) index.
#[error("Local index not found at: `{}`", _0.display())]
LocalIndexNotFound(PathBuf),
/// The metadata file could not be parsed.
#[error("Couldn't parse metadata of {0} from {1}")]
MetadataParseError(
WheelFilename,
String,
#[source] Box<uv_pypi_types::MetadataError>,
),
/// An error that happened while making a request or in a reqwest middleware.
#[error("Failed to fetch: `{0}`")]
WrappedReqwestError(DisplaySafeUrl, #[source] WrappedReqwestError),
/// Add the number of failed retries to the error.
#[error("Request failed after {retries} {subject}", subject = if *retries > 1 { "retries" } else { "retry" })]
RequestWithRetries {
source: Box<ErrorKind>,
retries: u32,
},
#[error("Received some unexpected JSON from {}", url)]
BadJson {
source: serde_json::Error,
url: DisplaySafeUrl,
},
#[error("Received some unexpected HTML from {}", url)]
BadHtml {
source: html::Error,
url: DisplaySafeUrl,
},
#[error("Received some unexpected MessagePack from {}", url)]
BadMessagePack {
source: rmp_serde::decode::Error,
url: DisplaySafeUrl,
},
#[error("Failed to read zip with range requests: `{0}`")]
AsyncHttpRangeReader(DisplaySafeUrl, #[source] AsyncHttpRangeReaderError),
#[error("{0} is not a valid wheel filename")]
WheelFilename(#[source] WheelFilenameError),
#[error("Package metadata name `{metadata}` does not match given name `{given}`")]
NameMismatch {
given: PackageName,
metadata: PackageName,
},
#[error("Failed to unzip wheel: {0}")]
Zip(WheelFilename, #[source] ZipError),
#[error("Failed to write to the client cache")]
CacheWrite(#[source] std::io::Error),
#[error("Failed to acquire lock on the client cache")]
CacheLock(#[source] CacheError),
#[error(transparent)]
Io(std::io::Error),
#[error("Cache deserialization failed")]
Decode(#[source] rmp_serde::decode::Error),
#[error("Cache serialization failed")]
Encode(#[source] rmp_serde::encode::Error),
#[error("Missing `Content-Type` header for {0}")]
MissingContentType(DisplaySafeUrl),
#[error("Invalid `Content-Type` header for {0}")]
InvalidContentTypeHeader(DisplaySafeUrl, #[source] http::header::ToStrError),
#[error("Unsupported `Content-Type` \"{1}\" for {0}. Expected JSON or HTML.")]
UnsupportedMediaType(DisplaySafeUrl, String),
#[error("Reading from cache archive failed: {0}")]
ArchiveRead(String),
#[error("Writing to cache archive failed: {0}")]
ArchiveWrite(String),
#[error(
"Network connectivity is disabled, but the requested data wasn't found in the cache for: `{0}`"
)]
Offline(String),
#[error("Invalid cache control header: `{0}`")]
InvalidCacheControl(String),
}
impl ErrorKind {
/// Create an [`ErrorKind`] from a [`reqwest::Error`].
pub(crate) fn from_reqwest(url: DisplaySafeUrl, error: reqwest::Error) -> Self {
Self::WrappedReqwestError(url, WrappedReqwestError::from(error))
}
/// Create an [`ErrorKind`] from a [`reqwest_middleware::Error`].
pub(crate) fn from_reqwest_middleware(
url: DisplaySafeUrl,
err: reqwest_middleware::Error,
) -> Self {
if let reqwest_middleware::Error::Middleware(ref underlying) = err {
if let Some(err) = underlying.downcast_ref::<OfflineError>() {
return Self::Offline(err.url().to_string());
}
}
Self::WrappedReqwestError(url, WrappedReqwestError::from(err))
}
/// Create an [`ErrorKind`] from a [`reqwest::Error`] with problem details.
pub(crate) fn from_reqwest_with_problem_details(
url: DisplaySafeUrl,
error: reqwest::Error,
problem_details: Option<ProblemDetails>,
) -> Self {
Self::WrappedReqwestError(
url,
WrappedReqwestError::with_problem_details(error.into(), problem_details),
)
}
}
/// Handle the case with no internet by explicitly telling the user instead of showing an obscure
/// DNS error.
///
/// Wraps a [`reqwest_middleware::Error`] instead of an [`reqwest::Error`] since the actual reqwest
/// error may be below some context in the [`anyhow::Error`].
#[derive(Debug)]
pub struct WrappedReqwestError {
error: reqwest_middleware::Error,
problem_details: Option<Box<ProblemDetails>>,
}
impl WrappedReqwestError {
/// Create a new `WrappedReqwestError` with optional problem details
pub fn with_problem_details(
error: reqwest_middleware::Error,
problem_details: Option<ProblemDetails>,
) -> Self {
Self {
error: Self::filter_retries_from_error(error),
problem_details: problem_details.map(Box::new),
}
}
/// Drop `RetryError::WithRetries` to avoid reporting the number of retries twice.
///
/// We attach the number of errors outside by adding the retry counts from the retry middleware
/// and from uv's outer retry loop for streaming bodies. Stripping the inner count from the
/// error context avoids showing two numbers.
fn filter_retries_from_error(error: reqwest_middleware::Error) -> reqwest_middleware::Error {
match error {
reqwest_middleware::Error::Middleware(error) => {
match error.downcast::<reqwest_retry::RetryError>() {
Ok(
reqwest_retry::RetryError::WithRetries { err, .. }
| reqwest_retry::RetryError::Error(err),
) => err,
Err(error) => reqwest_middleware::Error::Middleware(error),
}
}
error @ reqwest_middleware::Error::Reqwest(_) => error,
}
}
/// Return the inner [`reqwest::Error`] from the error chain, if it exists.
pub fn inner(&self) -> Option<&reqwest::Error> {
match &self.error {
reqwest_middleware::Error::Reqwest(err) => Some(err),
reqwest_middleware::Error::Middleware(err) => err.chain().find_map(|err| {
if let Some(err) = err.downcast_ref::<reqwest::Error>() {
Some(err)
} else if let Some(reqwest_middleware::Error::Reqwest(err)) =
err.downcast_ref::<reqwest_middleware::Error>()
{
Some(err)
} else {
None
}
}),
}
}
/// Check if the error chain contains a `reqwest` error that looks like this:
/// * error sending request for url (...)
/// * client error (Connect)
/// * dns error: failed to lookup address information: Name or service not known
/// * failed to lookup address information: Name or service not known
fn is_likely_offline(&self) -> bool {
if let Some(reqwest_err) = self.inner() {
if !reqwest_err.is_connect() {
return false;
}
// Self is "error sending request for url", the first source is "error trying to connect",
// the second source is "dns error". We have to check for the string because hyper errors
// are opaque.
if std::error::Error::source(&reqwest_err)
.and_then(|err| err.source())
.is_some_and(|err| err.to_string().starts_with("dns error: "))
{
return true;
}
}
false
}
/// Check if the error chain contains a `reqwest` error that looks like this:
/// * invalid peer certificate: `UnknownIssuer`
fn is_ssl(&self) -> bool {
if let Some(reqwest_err) = self.inner() {
if !reqwest_err.is_connect() {
return false;
}
// Self is "error sending request for url", the first source is "error trying to connect",
// the second source is "dns error". We have to check for the string because hyper errors
// are opaque.
if std::error::Error::source(&reqwest_err)
.and_then(|err| err.source())
.is_some_and(|err| err.to_string().starts_with("invalid peer certificate: "))
{
return true;
}
}
false
}
}
impl From<reqwest::Error> for WrappedReqwestError {
fn from(error: reqwest::Error) -> Self {
Self {
// No need to filter retries as this error does not have retries.
error: error.into(),
problem_details: None,
}
}
}
impl From<reqwest_middleware::Error> for WrappedReqwestError {
fn from(error: reqwest_middleware::Error) -> Self {
Self {
error: Self::filter_retries_from_error(error),
problem_details: None,
}
}
}
impl Deref for WrappedReqwestError {
type Target = reqwest_middleware::Error;
fn deref(&self) -> &Self::Target {
&self.error
}
}
impl Display for WrappedReqwestError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.is_likely_offline() {
// Insert an extra hint, we'll show the wrapped error through `source`
f.write_str("Could not connect, are you offline?")
} else if let Some(problem_details) = &self.problem_details {
// Show problem details if available
match problem_details.description() {
None => Display::fmt(&self.error, f),
Some(message) => f.write_str(&message),
}
} else {
// Show the wrapped error
Display::fmt(&self.error, f)
}
}
}
impl std::error::Error for WrappedReqwestError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if self.is_likely_offline() {
// `Display` is inserting an extra message, so we need to show the wrapped error
Some(&self.error)
} else if self.problem_details.is_some() {
// `Display` is showing problem details, so show the wrapped error as source
Some(&self.error)
} else {
// `Display` is showing the wrapped error, continue with its source
self.error.source()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_problem_details_parsing() {
let json = r#"{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
"status": 403,
"instance": "/account/12345/msgs/abc"
}"#;
let problem_details: ProblemDetails = serde_json::from_slice(json.as_bytes()).unwrap();
assert_eq!(
problem_details.problem_type,
"https://example.com/probs/out-of-credit"
);
assert_eq!(
problem_details.title,
Some("You do not have enough credit.".to_string())
);
assert_eq!(
problem_details.detail,
Some("Your current balance is 30, but that costs 50.".to_string())
);
assert_eq!(problem_details.status, Some(403));
assert_eq!(
problem_details.instance,
Some("/account/12345/msgs/abc".to_string())
);
}
#[test]
fn test_problem_details_default_type() {
let json = r#"{
"detail": "Something went wrong",
"status": 500
}"#;
let problem_details: ProblemDetails = serde_json::from_slice(json.as_bytes()).unwrap();
assert_eq!(problem_details.problem_type, "about:blank");
assert_eq!(
problem_details.detail,
Some("Something went wrong".to_string())
);
assert_eq!(problem_details.status, Some(500));
}
#[test]
fn test_problem_details_description() {
let json = r#"{
"detail": "Detailed error message",
"title": "Error Title",
"status": 400
}"#;
let problem_details: ProblemDetails = serde_json::from_slice(json.as_bytes()).unwrap();
assert_eq!(
problem_details.description().unwrap(),
"Server message: Error Title, Detailed error message"
);
let json_no_detail = r#"{
"title": "Error Title",
"status": 400
}"#;
let problem_details: ProblemDetails =
serde_json::from_slice(json_no_detail.as_bytes()).unwrap();
assert_eq!(
problem_details.description().unwrap(),
"Server message: Error Title"
);
let json_minimal = r#"{
"status": 400
}"#;
let problem_details: ProblemDetails =
serde_json::from_slice(json_minimal.as_bytes()).unwrap();
assert_eq!(problem_details.description().unwrap(), "HTTP error 400");
}
#[test]
fn test_problem_details_with_extensions() {
let json = r#"{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
"status": 403,
"balance": 30,
"accounts": ["/account/12345", "/account/67890"]
}"#;
let problem_details: ProblemDetails = serde_json::from_slice(json.as_bytes()).unwrap();
assert_eq!(
problem_details.title,
Some("You do not have enough credit.".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-client/src/flat_index.rs | crates/uv-client/src/flat_index.rs | use std::path::{Path, PathBuf};
use futures::{FutureExt, StreamExt};
use reqwest::Response;
use tracing::{Instrument, debug, info_span, warn};
use url::Url;
use uv_cache::{Cache, CacheBucket};
use uv_cache_key::cache_digest;
use uv_distribution_filename::DistFilename;
use uv_distribution_types::{File, FileLocation, IndexUrl, UrlString};
use uv_pypi_types::HashDigests;
use uv_redacted::DisplaySafeUrl;
use uv_small_str::SmallString;
use crate::cached_client::{CacheControl, CachedClientError};
use crate::html::SimpleDetailHTML;
use crate::{CachedClient, Connectivity, Error, ErrorKind, OwnedArchive};
#[derive(Debug, thiserror::Error)]
pub enum FlatIndexError {
#[error("Expected a file URL, but received: {0}")]
NonFileUrl(DisplaySafeUrl),
#[error("Failed to read `--find-links` directory: {0}")]
FindLinksDirectory(PathBuf, #[source] FindLinksDirectoryError),
#[error("Failed to read `--find-links` URL: {0}")]
FindLinksUrl(DisplaySafeUrl, #[source] Error),
}
#[derive(Debug, thiserror::Error)]
pub enum FindLinksDirectoryError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
VerbatimUrl(#[from] uv_pep508::VerbatimUrlError),
}
/// An entry in a `--find-links` index.
#[derive(Debug, Clone)]
pub struct FlatIndexEntry {
pub filename: DistFilename,
pub file: File,
pub index: IndexUrl,
}
#[derive(Debug, Default, Clone)]
pub struct FlatIndexEntries {
/// The list of `--find-links` entries.
pub entries: Vec<FlatIndexEntry>,
/// Whether any `--find-links` entries could not be resolved due to a lack of network
/// connectivity.
pub offline: bool,
}
impl FlatIndexEntries {
/// Create a [`FlatIndexEntries`] from a list of `--find-links` entries.
fn from_entries(entries: Vec<FlatIndexEntry>) -> Self {
Self {
entries,
offline: false,
}
}
/// Create a [`FlatIndexEntries`] to represent an offline `--find-links` entry.
fn offline() -> Self {
Self {
entries: Vec::new(),
offline: true,
}
}
/// Extend this list of `--find-links` entries with another list.
fn extend(&mut self, other: Self) {
self.entries.extend(other.entries);
self.offline |= other.offline;
}
/// Return the number of `--find-links` entries.
fn len(&self) -> usize {
self.entries.len()
}
/// Return `true` if there are no `--find-links` entries.
fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
/// A client for reading distributions from `--find-links` entries (either local directories or
/// remote HTML indexes).
#[derive(Debug, Clone)]
pub struct FlatIndexClient<'a> {
client: &'a CachedClient,
connectivity: Connectivity,
cache: &'a Cache,
}
impl<'a> FlatIndexClient<'a> {
/// Create a new [`FlatIndexClient`].
pub fn new(client: &'a CachedClient, connectivity: Connectivity, cache: &'a Cache) -> Self {
Self {
client,
connectivity,
cache,
}
}
/// Read the directories and flat remote indexes from `--find-links`.
pub async fn fetch_all(
&self,
indexes: impl Iterator<Item = &IndexUrl>,
) -> Result<FlatIndexEntries, FlatIndexError> {
let mut fetches = futures::stream::iter(indexes)
.map(async |index| {
let entries = self.fetch_index(index).await?;
if entries.is_empty() {
warn!("No packages found in `--find-links` entry: {}", index);
} else {
debug!(
"Found {} package{} in `--find-links` entry: {}",
entries.len(),
if entries.len() == 1 { "" } else { "s" },
index
);
}
Ok::<FlatIndexEntries, FlatIndexError>(entries)
})
.buffered(16);
let mut results = FlatIndexEntries::default();
while let Some(entries) = fetches.next().await.transpose()? {
results.extend(entries);
}
results
.entries
.sort_by(|a, b| a.filename.cmp(&b.filename).then(a.index.cmp(&b.index)));
Ok(results)
}
/// Fetch a flat remote index from a `--find-links` URL.
pub async fn fetch_index(&self, index: &IndexUrl) -> Result<FlatIndexEntries, FlatIndexError> {
match index {
IndexUrl::Path(url) => {
let path = url
.to_file_path()
.map_err(|()| FlatIndexError::NonFileUrl(url.to_url()))?;
Self::read_from_directory(&path, index)
.map_err(|err| FlatIndexError::FindLinksDirectory(path.clone(), err))
}
IndexUrl::Pypi(url) | IndexUrl::Url(url) => self
.read_from_url(url, index)
.await
.map_err(|err| FlatIndexError::FindLinksUrl(url.to_url(), err)),
}
}
/// Read a flat remote index from a `--find-links` URL.
async fn read_from_url(
&self,
url: &DisplaySafeUrl,
flat_index: &IndexUrl,
) -> Result<FlatIndexEntries, Error> {
let cache_entry = self.cache.entry(
CacheBucket::FlatIndex,
"html",
format!("{}.msgpack", cache_digest(&url.to_string())),
);
let cache_control = match self.connectivity {
Connectivity::Online => CacheControl::from(
self.cache
.freshness(&cache_entry, None, None)
.map_err(ErrorKind::Io)?,
),
Connectivity::Offline => CacheControl::AllowStale,
};
let flat_index_request = self
.client
.uncached()
.for_host(url)
.get(Url::from(url.clone()))
.header("Accept-Encoding", "gzip")
.header("Accept", "text/html")
.build()
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let parse_simple_response = |response: Response| {
async {
// Use the response URL, rather than the request URL, as the base for relative URLs.
// This ensures that we handle redirects and other URL transformations correctly.
let url = DisplaySafeUrl::from_url(response.url().clone());
let text = response
.text()
.await
.map_err(|err| ErrorKind::from_reqwest(url.clone(), err))?;
let SimpleDetailHTML { base, files } = SimpleDetailHTML::parse(&text, &url)
.map_err(|err| Error::from_html_err(err, url.clone()))?;
// Convert to a reference-counted string.
let base = SmallString::from(base.as_str());
let unarchived: Vec<File> = files
.into_iter()
.filter_map(|file| {
match File::try_from_pypi(file, &base) {
Ok(file) => Some(file),
Err(err) => {
// Ignore files with unparsable version specifiers.
warn!("Skipping file in {}: {err}", &url);
None
}
}
})
.collect();
OwnedArchive::from_unarchived(&unarchived)
}
.boxed_local()
.instrument(info_span!("parse_flat_index_html", url = % url))
};
let response = self
.client
.get_cacheable_with_retry(
flat_index_request,
&cache_entry,
cache_control,
parse_simple_response,
)
.await;
match response {
Ok(files) => {
let files = files
.iter()
.map(|file| {
rkyv::deserialize::<File, rkyv::rancor::Error>(file)
.expect("archived version always deserializes")
})
.filter_map(|file| {
Some(FlatIndexEntry {
filename: DistFilename::try_from_normalized_filename(&file.filename)?,
file,
index: flat_index.clone(),
})
})
.collect();
Ok(FlatIndexEntries::from_entries(files))
}
Err(CachedClientError::Client(err)) if err.is_offline() => {
Ok(FlatIndexEntries::offline())
}
Err(err) => Err(err.into()),
}
}
/// Read a flat remote index from a `--find-links` directory.
fn read_from_directory(
path: &Path,
flat_index: &IndexUrl,
) -> Result<FlatIndexEntries, FindLinksDirectoryError> {
// The path context is provided by the caller.
#[allow(clippy::disallowed_methods)]
let entries = std::fs::read_dir(path)?;
let mut dists = Vec::new();
for entry in entries {
let entry = entry?;
let metadata = entry.metadata()?;
if metadata.is_dir() {
continue;
}
if metadata.is_symlink() {
let Ok(target) = entry.path().read_link() else {
warn!(
"Skipping unreadable symlink in `--find-links` directory: {}",
entry.path().display()
);
continue;
};
if target.is_dir() {
continue;
}
}
let filename = entry.file_name();
let Some(filename) = filename.to_str() else {
warn!(
"Skipping non-UTF-8 filename in `--find-links` directory: {}",
filename.to_string_lossy()
);
continue;
};
// SAFETY: The index path is itself constructed from a URL.
let url = DisplaySafeUrl::from_file_path(entry.path()).unwrap();
let file = File {
dist_info_metadata: false,
filename: filename.into(),
hashes: HashDigests::empty(),
requires_python: None,
size: None,
upload_time_utc_ms: None,
url: FileLocation::AbsoluteUrl(UrlString::from(url)),
yanked: None,
zstd: None,
};
let Some(filename) = DistFilename::try_from_normalized_filename(filename) else {
debug!(
"Ignoring `--find-links` entry (expected a wheel or source distribution filename): {}",
entry.path().display()
);
continue;
};
dists.push(FlatIndexEntry {
filename,
file,
index: flat_index.clone(),
});
}
dists.sort_by(|a, b| {
a.filename
.cmp(&b.filename)
.then_with(|| a.index.cmp(&b.index))
});
Ok(FlatIndexEntries::from_entries(dists))
}
}
#[cfg(test)]
mod tests {
use super::*;
use fs_err::File;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn read_from_directory_sorts_distributions() {
let dir = tempdir().unwrap();
let filenames = [
"beta-2.0.0-py3-none-any.whl",
"alpha-1.0.0.tar.gz",
"alpha-1.0.0-py3-none-any.whl",
];
for name in &filenames {
let mut file = File::create(dir.path().join(name)).unwrap();
file.write_all(b"").unwrap();
}
let entries = FlatIndexClient::read_from_directory(
dir.path(),
&IndexUrl::parse(&dir.path().to_string_lossy(), None).unwrap(),
)
.unwrap();
let actual = entries
.entries
.iter()
.map(|entry| entry.filename.to_string())
.collect::<Vec<_>>();
let mut expected = filenames
.iter()
.map(|name| DistFilename::try_from_normalized_filename(name).unwrap())
.collect::<Vec<_>>();
expected.sort();
let expected = expected
.into_iter()
.map(|filename| filename.to_string())
.collect::<Vec<_>>();
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-client/src/remote_metadata.rs | crates/uv-client/src/remote_metadata.rs | use crate::{Error, ErrorKind};
use async_http_range_reader::AsyncHttpRangeReader;
use futures::io::BufReader;
use tokio_util::compat::TokioAsyncReadCompatExt;
use url::Url;
use uv_distribution_filename::WheelFilename;
use uv_metadata::find_archive_dist_info;
/// Read the `.dist-info/METADATA` file from a async remote zip reader, so we avoid downloading the
/// entire wheel just for the one file.
///
/// This method is derived from `prefix-dev/rip`, which is available under the following BSD-3
/// Clause license:
///
/// ```text
/// BSD 3-Clause License
///
/// Copyright (c) 2023, prefix.dev GmbH
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice, this
/// list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from
/// this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
/// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
/// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
/// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/// ```
///
/// Additional work and modifications to the originating source are available under the
/// Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
/// or MIT license ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/licenses/MIT>), as per the
/// rest of the crate.
pub(crate) async fn wheel_metadata_from_remote_zip(
filename: &WheelFilename,
debug_name: &Url,
reader: &mut AsyncHttpRangeReader,
) -> Result<String, Error> {
// Make sure we have the back part of the stream.
// Best guess for the central directory size inside the zip
const CENTRAL_DIRECTORY_SIZE: u64 = 16384;
// Because the zip index is at the back
reader
.prefetch(reader.len().saturating_sub(CENTRAL_DIRECTORY_SIZE)..reader.len())
.await;
// Construct a zip reader to uses the stream.
let buf = BufReader::new(reader.compat());
let mut reader = async_zip::base::read::seek::ZipFileReader::new(buf)
.await
.map_err(|err| ErrorKind::Zip(filename.clone(), err))?;
let ((metadata_idx, metadata_entry), _dist_info_prefix) = find_archive_dist_info(
filename,
reader
.file()
.entries()
.iter()
.enumerate()
.filter_map(|(idx, e)| Some(((idx, e), e.filename().as_str().ok()?))),
)
.map_err(|err| ErrorKind::Metadata(debug_name.to_string(), err))?;
let offset = metadata_entry.header_offset();
let size = metadata_entry.compressed_size()
+ 30 // Header size in bytes
+ metadata_entry.filename().as_bytes().len() as u64;
// The zip archive uses as BufReader which reads in chunks of 8192. To ensure we prefetch
// enough data we round the size up to the nearest multiple of the buffer size.
let buffer_size = 8192;
let size = size.div_ceil(buffer_size) * buffer_size;
// Fetch the bytes from the zip archive that contain the requested file.
reader
.inner_mut()
.get_mut()
.get_mut()
.prefetch(offset..offset + size)
.await;
// Read the contents of the METADATA file
let mut contents = String::new();
reader
.reader_with_entry(metadata_idx)
.await
.map_err(|err| ErrorKind::Zip(filename.clone(), err))?
.read_to_string_checked(&mut contents)
.await
.map_err(|err| ErrorKind::Zip(filename.clone(), err))?;
Ok(contents)
}
| 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-client/src/cached_client.rs | crates/uv-client/src/cached_client.rs | use std::{borrow::Cow, path::Path};
use futures::FutureExt;
use reqwest::{Request, Response};
use rkyv::util::AlignedVec;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tracing::{Instrument, debug, info_span, instrument, trace, warn};
use uv_cache::{CacheEntry, Freshness};
use uv_fs::write_atomic;
use uv_redacted::DisplaySafeUrl;
use crate::BaseClient;
use crate::base_client::RetryState;
use crate::error::ProblemDetails;
use crate::{
Error, ErrorKind,
httpcache::{AfterResponse, BeforeRequest, CachePolicy, CachePolicyBuilder},
rkyvutil::OwnedArchive,
};
/// Extract problem details from an HTTP response if it has the correct content type
///
/// Note: This consumes the response body, so it should only be called when there's an error status.
async fn extract_problem_details(response: Response) -> Option<ProblemDetails> {
match response.bytes().await {
Ok(bytes) => match serde_json::from_slice(&bytes) {
Ok(details) => Some(details),
Err(err) => {
warn!("Failed to parse problem details: {err}");
None
}
},
Err(err) => {
warn!("Failed to read response body for problem details: {err}");
None
}
}
}
/// A trait the generalizes (de)serialization at a high level.
///
/// The main purpose of this trait is to make the `CachedClient` work for
/// either serde or other mechanisms of serialization such as `rkyv`.
///
/// If you're using Serde, then unless you want to control the format, callers
/// should just use `CachedClient::get_serde`. This will use a default
/// implementation of `Cacheable` internally.
///
/// Alternatively, callers using `rkyv` should use
/// `CachedClient::get_cacheable`. If your types fit into the
/// `rkyvutil::OwnedArchive` mold, then an implementation of `Cacheable` is
/// already provided for that type.
pub trait Cacheable: Sized {
/// This associated type permits customizing what the "output" type of
/// deserialization is. It can be identical to `Self`.
///
/// Typical use of this is for wrapper types used to provide blanket trait
/// impls without hitting overlapping impl problems.
type Target: Send + 'static;
/// Deserialize a value from bytes aligned to a 16-byte boundary.
fn from_aligned_bytes(bytes: AlignedVec) -> Result<Self::Target, Error>;
/// Serialize bytes to a possibly owned byte buffer.
fn to_bytes(&self) -> Result<Cow<'_, [u8]>, Error>;
/// Convert this type into its final form.
fn into_target(self) -> Self::Target;
}
/// A wrapper type that makes anything with Serde support automatically
/// implement `Cacheable`.
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub(crate) struct SerdeCacheable<T> {
inner: T,
}
impl<T: Serialize + DeserializeOwned + Send + 'static> Cacheable for SerdeCacheable<T> {
type Target = T;
fn from_aligned_bytes(bytes: AlignedVec) -> Result<T, Error> {
Ok(rmp_serde::from_slice::<T>(&bytes).map_err(ErrorKind::Decode)?)
}
fn to_bytes(&self) -> Result<Cow<'_, [u8]>, Error> {
Ok(Cow::from(
rmp_serde::to_vec(&self.inner).map_err(ErrorKind::Encode)?,
))
}
fn into_target(self) -> Self::Target {
self.inner
}
}
/// All `OwnedArchive` values are cacheable.
impl<A> Cacheable for OwnedArchive<A>
where
A: rkyv::Archive + for<'a> rkyv::Serialize<crate::rkyvutil::Serializer<'a>> + Send + 'static,
A::Archived: rkyv::Portable
+ rkyv::Deserialize<A, crate::rkyvutil::Deserializer>
+ for<'a> rkyv::bytecheck::CheckBytes<crate::rkyvutil::Validator<'a>>,
{
type Target = Self;
fn from_aligned_bytes(bytes: AlignedVec) -> Result<Self, Error> {
Self::new(bytes)
}
fn to_bytes(&self) -> Result<Cow<'_, [u8]>, Error> {
Ok(Cow::from(Self::as_bytes(self)))
}
fn into_target(self) -> Self::Target {
self
}
}
/// Dispatch type: Either a cached client error or a (user specified) error from the callback.
#[derive(Debug)]
pub enum CachedClientError<CallbackError: std::error::Error + 'static> {
/// The client tracks retries internally.
Client(Error),
/// Track retries before a callback explicitly, as we can't attach them to the callback error
/// type.
Callback { retries: u32, err: CallbackError },
}
impl<CallbackError: std::error::Error + 'static> CachedClientError<CallbackError> {
/// Attach the combined number of retries to the error context, discarding the previous count.
fn with_retries(self, retries: u32) -> Self {
match self {
Self::Client(err) => Self::Client(err.with_retries(retries)),
Self::Callback { retries: _, err } => Self::Callback { retries, err },
}
}
fn retries(&self) -> u32 {
match self {
Self::Client(err) => err.retries(),
Self::Callback { retries, .. } => *retries,
}
}
fn error(&self) -> &(dyn std::error::Error + 'static) {
match self {
Self::Client(err) => err,
Self::Callback { err, .. } => err,
}
}
}
impl<CallbackError: std::error::Error + 'static> From<Error> for CachedClientError<CallbackError> {
fn from(error: Error) -> Self {
Self::Client(error)
}
}
impl<CallbackError: std::error::Error + 'static> From<ErrorKind>
for CachedClientError<CallbackError>
{
fn from(error: ErrorKind) -> Self {
Self::Client(error.into())
}
}
impl<E: Into<Self> + std::error::Error + 'static> From<CachedClientError<E>> for Error {
/// Attach retry error context, if there were retries.
fn from(error: CachedClientError<E>) -> Self {
match error {
CachedClientError::Client(error) => error,
CachedClientError::Callback { retries, err } => {
Self::new(err.into().into_kind(), retries)
}
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum CacheControl<'a> {
/// Respect the `cache-control` header from the response.
None,
/// Apply `max-age=0, must-revalidate` to the request.
MustRevalidate,
/// Allow the client to return stale responses.
AllowStale,
/// Override the cache control header with a custom value.
Override(&'a str),
}
impl From<Freshness> for CacheControl<'_> {
fn from(value: Freshness) -> Self {
match value {
Freshness::Fresh => Self::None,
Freshness::Stale => Self::MustRevalidate,
Freshness::Missing => Self::None,
}
}
}
/// Custom caching layer over [`reqwest::Client`].
///
/// The implementation takes inspiration from the `http-cache` crate, but adds support for running
/// an async callback on the response before caching. We use this to e.g. store a
/// parsed version of the wheel metadata and for our remote zip reader. In the latter case, we want
/// to read a single file from a remote zip using range requests (so we don't have to download the
/// entire file). We send a HEAD request in the caching layer to check if the remote file has
/// changed (and if range requests are supported), and in the callback we make the actual range
/// requests if required.
///
/// Unlike `http-cache`, all outputs must be serializable/deserializable in some way, by
/// implementing the `Cacheable` trait.
///
/// Again unlike `http-cache`, the caller gets full control over the cache key with the assumption
/// that it's a file.
#[derive(Debug, Clone)]
pub struct CachedClient(BaseClient);
impl CachedClient {
pub fn new(client: BaseClient) -> Self {
Self(client)
}
/// The underlying [`BaseClient`] without caching.
pub fn uncached(&self) -> &BaseClient {
&self.0
}
/// Make a cached request with a custom response transformation
/// while using serde to (de)serialize cached responses.
///
/// If a new response was received (no prior cached response or modified
/// on the remote), the response is passed through `response_callback` and
/// only the result is cached and returned. The `response_callback` is
/// allowed to make subsequent requests, e.g. through the uncached client.
#[instrument(skip_all)]
pub async fn get_serde<
Payload: Serialize + DeserializeOwned + Send + 'static,
CallBackError: std::error::Error + 'static,
Callback: AsyncFn(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload, CachedClientError<CallBackError>> {
let payload = self
.get_cacheable(req, cache_entry, cache_control, async |resp| {
let payload = response_callback(resp).await?;
Ok(SerdeCacheable { inner: payload })
})
.await?;
Ok(payload)
}
/// Make a cached request with a custom response transformation while using
/// the `Cacheable` trait to (de)serialize cached responses.
///
/// The purpose of this routine is the use of `Cacheable`. Namely, it
/// generalizes over (de)serialization such that mechanisms other than
/// serde (such as rkyv) can be used to manage (de)serialization of cached
/// data.
///
/// If a new response was received (no prior cached response or modified
/// on the remote), the response is passed through `response_callback` and
/// only the result is cached and returned. The `response_callback` is
/// allowed to make subsequent requests, e.g. through the uncached client.
#[instrument(skip_all)]
pub async fn get_cacheable<
Payload: Cacheable,
CallBackError: std::error::Error + 'static,
Callback: AsyncFn(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload::Target, CachedClientError<CallBackError>> {
let fresh_req = req.try_clone().expect("HTTP request must be cloneable");
let cached_response = if let Some(cached) = Self::read_cache(cache_entry).await {
self.send_cached(req, cache_control, cached)
.boxed_local()
.await?
} else {
debug!("No cache entry for: {}", req.url());
let (response, cache_policy) = self.fresh_request(req, cache_control).await?;
CachedResponse::ModifiedOrNew {
response,
cache_policy,
}
};
match cached_response {
CachedResponse::FreshCache(cached) => match Payload::from_aligned_bytes(cached.data) {
Ok(payload) => Ok(payload),
Err(err) => {
warn!(
"Broken fresh cache entry (for payload) at {}, removing: {err}",
cache_entry.path().display()
);
self.resend_and_heal_cache(
fresh_req,
cache_entry,
cache_control,
response_callback,
)
.await
}
},
CachedResponse::NotModified { cached, new_policy } => {
let refresh_cache =
info_span!("refresh_cache", file = %cache_entry.path().display());
async {
let data_with_cache_policy_bytes =
DataWithCachePolicy::serialize(&new_policy, &cached.data)?;
write_atomic(cache_entry.path(), data_with_cache_policy_bytes)
.await
.map_err(ErrorKind::CacheWrite)?;
match Payload::from_aligned_bytes(cached.data) {
Ok(payload) => Ok(payload),
Err(err) => {
warn!(
"Broken fresh cache entry after revalidation \
(for payload) at {}, removing: {err}",
cache_entry.path().display()
);
self.resend_and_heal_cache(
fresh_req,
cache_entry,
cache_control,
response_callback,
)
.await
}
}
}
.instrument(refresh_cache)
.await
}
CachedResponse::ModifiedOrNew {
response,
cache_policy,
} => {
// If we got a modified response, but it's a 304, then a validator failed (e.g., the
// ETag didn't match). We need to make a fresh request.
if response.status() == http::StatusCode::NOT_MODIFIED {
warn!("Server returned unusable 304 for: {}", fresh_req.url());
self.resend_and_heal_cache(
fresh_req,
cache_entry,
cache_control,
response_callback,
)
.await
} else {
self.run_response_callback(
cache_entry,
cache_policy,
response,
response_callback,
)
.await
}
}
}
}
/// Make a request without checking whether the cache is fresh.
pub async fn skip_cache<
Payload: Serialize + DeserializeOwned + Send + 'static,
CallBackError: std::error::Error + 'static,
Callback: AsyncFnOnce(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload, CachedClientError<CallBackError>> {
let (response, cache_policy) = self.fresh_request(req, cache_control).await?;
let payload = self
.run_response_callback(cache_entry, cache_policy, response, async |resp| {
let payload = response_callback(resp).await?;
Ok(SerdeCacheable { inner: payload })
})
.await?;
Ok(payload)
}
async fn resend_and_heal_cache<
Payload: Cacheable,
CallBackError: std::error::Error + 'static,
Callback: AsyncFnOnce(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload::Target, CachedClientError<CallBackError>> {
let _ = fs_err::tokio::remove_file(&cache_entry.path()).await;
let (response, cache_policy) = self.fresh_request(req, cache_control).await?;
self.run_response_callback(cache_entry, cache_policy, response, response_callback)
.await
}
async fn run_response_callback<
Payload: Cacheable,
CallBackError: std::error::Error + 'static,
Callback: AsyncFnOnce(Response) -> Result<Payload, CallBackError>,
>(
&self,
cache_entry: &CacheEntry,
cache_policy: Option<Box<CachePolicy>>,
response: Response,
response_callback: Callback,
) -> Result<Payload::Target, CachedClientError<CallBackError>> {
let new_cache = info_span!("new_cache", file = %cache_entry.path().display());
// Capture retries from the retry middleware
let retries = response
.extensions()
.get::<reqwest_retry::RetryCount>()
.map(|retries| retries.value())
.unwrap_or_default();
let data = response_callback(response)
.boxed_local()
.await
.map_err(|err| CachedClientError::Callback { retries, err })?;
let Some(cache_policy) = cache_policy else {
return Ok(data.into_target());
};
async {
fs_err::tokio::create_dir_all(cache_entry.dir())
.await
.map_err(ErrorKind::CacheWrite)?;
let data_with_cache_policy_bytes =
DataWithCachePolicy::serialize(&cache_policy, &data.to_bytes()?)?;
write_atomic(cache_entry.path(), data_with_cache_policy_bytes)
.await
.map_err(ErrorKind::CacheWrite)?;
Ok(data.into_target())
}
.instrument(new_cache)
.await
}
#[instrument(name = "read_and_parse_cache", skip_all, fields(file = %cache_entry.path().display()
))]
async fn read_cache(cache_entry: &CacheEntry) -> Option<DataWithCachePolicy> {
match DataWithCachePolicy::from_path_async(cache_entry.path()).await {
Ok(data) => Some(data),
Err(err) => {
// When we know the cache entry doesn't exist, then things are
// normal and we shouldn't emit a WARN.
if err.is_file_not_exists() {
trace!("No cache entry exists for {}", cache_entry.path().display());
} else {
warn!(
"Broken cache policy entry at {}, removing: {err}",
cache_entry.path().display()
);
let _ = fs_err::tokio::remove_file(&cache_entry.path()).await;
}
None
}
}
}
/// Send a request given that we have a (possibly) stale cached response.
///
/// If the cached response is valid but stale, then this will attempt a
/// revalidation request.
async fn send_cached(
&self,
mut req: Request,
cache_control: CacheControl<'_>,
cached: DataWithCachePolicy,
) -> Result<CachedResponse, Error> {
// Apply the cache control header, if necessary.
match cache_control {
CacheControl::None | CacheControl::AllowStale | CacheControl::Override(..) => {}
CacheControl::MustRevalidate => {
req.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-cache"),
);
}
}
Ok(match cached.cache_policy.before_request(&mut req) {
BeforeRequest::Fresh => {
debug!("Found fresh response for: {}", req.url());
CachedResponse::FreshCache(cached)
}
BeforeRequest::Stale(new_cache_policy_builder) => match cache_control {
CacheControl::None | CacheControl::MustRevalidate | CacheControl::Override(_) => {
debug!("Found stale response for: {}", req.url());
self.send_cached_handle_stale(
req,
cache_control,
cached,
new_cache_policy_builder,
)
.await?
}
CacheControl::AllowStale => {
debug!("Found stale (but allowed) response for: {}", req.url());
CachedResponse::FreshCache(cached)
}
},
BeforeRequest::NoMatch => {
// This shouldn't happen; if it does, we'll override the cache.
warn!(
"Cached response doesn't match current request for: {}",
req.url()
);
let (response, cache_policy) = self.fresh_request(req, cache_control).await?;
CachedResponse::ModifiedOrNew {
response,
cache_policy,
}
}
})
}
async fn send_cached_handle_stale(
&self,
req: Request,
cache_control: CacheControl<'_>,
cached: DataWithCachePolicy,
new_cache_policy_builder: CachePolicyBuilder,
) -> Result<CachedResponse, Error> {
let url = DisplaySafeUrl::from_url(req.url().clone());
debug!("Sending revalidation request for: {url}");
let mut response = self
.0
.execute(req)
.instrument(info_span!("revalidation_request", url = url.as_str()))
.await
.map_err(|err| ErrorKind::from_reqwest_middleware(url.clone(), err))?;
// Check for HTTP error status and extract problem details if available
if let Err(status_error) = response.error_for_status_ref() {
// Clone the response to extract problem details before the error consumes it
let problem_details = if response
.headers()
.get("content-type")
.and_then(|ct| ct.to_str().ok())
.map(|ct| ct == "application/problem+json")
.unwrap_or(false)
{
extract_problem_details(response).await
} else {
None
};
return Err(ErrorKind::from_reqwest_with_problem_details(
url.clone(),
status_error,
problem_details,
)
.into());
}
// If the user set a custom `Cache-Control` header, override it.
if let CacheControl::Override(header) = cache_control {
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_str(header)
.expect("Cache-Control header must be valid UTF-8"),
);
}
match cached
.cache_policy
.after_response(new_cache_policy_builder, &response)
{
AfterResponse::NotModified(new_policy) => {
debug!("Found not-modified response for: {url}");
Ok(CachedResponse::NotModified {
cached,
new_policy: Box::new(new_policy),
})
}
AfterResponse::Modified(new_policy) => {
debug!("Found modified response for: {url}");
Ok(CachedResponse::ModifiedOrNew {
response,
cache_policy: new_policy
.to_archived()
.is_storable()
.then(|| Box::new(new_policy)),
})
}
}
}
#[instrument(skip_all, fields(url = req.url().as_str()))]
async fn fresh_request(
&self,
req: Request,
cache_control: CacheControl<'_>,
) -> Result<(Response, Option<Box<CachePolicy>>), Error> {
let url = DisplaySafeUrl::from_url(req.url().clone());
trace!("Sending fresh {} request for {}", req.method(), url);
let cache_policy_builder = CachePolicyBuilder::new(&req);
let mut response = self
.0
.execute(req)
.await
.map_err(|err| ErrorKind::from_reqwest_middleware(url.clone(), err))?;
// If the user set a custom `Cache-Control` header, override it.
if let CacheControl::Override(header) = cache_control {
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_str(header)
.expect("Cache-Control header must be valid UTF-8"),
);
}
let retry_count = response
.extensions()
.get::<reqwest_retry::RetryCount>()
.map(|retries| retries.value());
if let Err(status_error) = response.error_for_status_ref() {
let problem_details = if response
.headers()
.get("content-type")
.and_then(|ct| ct.to_str().ok())
.map(|ct| ct.starts_with("application/problem+json"))
.unwrap_or(false)
{
extract_problem_details(response).await
} else {
None
};
return Err(Error::new(
ErrorKind::from_reqwest_with_problem_details(url, status_error, problem_details),
retry_count.unwrap_or_default(),
));
}
let cache_policy = cache_policy_builder.build(&response);
let cache_policy = if cache_policy.to_archived().is_storable() {
Some(Box::new(cache_policy))
} else {
None
};
Ok((response, cache_policy))
}
/// Perform a [`CachedClient::get_serde`] request with a default retry strategy.
#[instrument(skip_all)]
pub async fn get_serde_with_retry<
Payload: Serialize + DeserializeOwned + Send + 'static,
CallBackError: std::error::Error + 'static,
Callback: AsyncFn(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload, CachedClientError<CallBackError>> {
let payload = self
.get_cacheable_with_retry(req, cache_entry, cache_control, async |resp| {
let payload = response_callback(resp).await?;
Ok(SerdeCacheable { inner: payload })
})
.await?;
Ok(payload)
}
/// Perform a [`CachedClient::get_cacheable`] request with a default retry strategy.
///
/// See: <https://github.com/TrueLayer/reqwest-middleware/blob/8a494c165734e24c62823714843e1c9347027e8a/reqwest-retry/src/middleware.rs#L137>
#[instrument(skip_all)]
pub async fn get_cacheable_with_retry<
Payload: Cacheable,
CallBackError: std::error::Error + 'static,
Callback: AsyncFn(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload::Target, CachedClientError<CallBackError>> {
let mut retry_state = RetryState::start(self.uncached().retry_policy(), req.url().clone());
loop {
let fresh_req = req.try_clone().expect("HTTP request must be cloneable");
let result = self
.get_cacheable(fresh_req, cache_entry, cache_control, &response_callback)
.await;
match result {
Ok(ok) => return Ok(ok),
Err(err) => {
if let Some(backoff) = retry_state.should_retry(err.error(), err.retries()) {
retry_state.sleep_backoff(backoff).await;
continue;
}
return Err(err.with_retries(retry_state.total_retries()));
}
}
}
}
/// Perform a [`CachedClient::skip_cache`] request with a default retry strategy.
///
/// See: <https://github.com/TrueLayer/reqwest-middleware/blob/8a494c165734e24c62823714843e1c9347027e8a/reqwest-retry/src/middleware.rs#L137>
pub async fn skip_cache_with_retry<
Payload: Serialize + DeserializeOwned + Send + 'static,
CallBackError: std::error::Error + 'static,
Callback: AsyncFn(Response) -> Result<Payload, CallBackError>,
>(
&self,
req: Request,
cache_entry: &CacheEntry,
cache_control: CacheControl<'_>,
response_callback: Callback,
) -> Result<Payload, CachedClientError<CallBackError>> {
let mut retry_state = RetryState::start(self.uncached().retry_policy(), req.url().clone());
loop {
let fresh_req = req.try_clone().expect("HTTP request must be cloneable");
let result = self
.skip_cache(fresh_req, cache_entry, cache_control, &response_callback)
.await;
match result {
Ok(ok) => return Ok(ok),
Err(err) => {
if let Some(backoff) = retry_state.should_retry(err.error(), err.retries()) {
retry_state.sleep_backoff(backoff).await;
continue;
}
return Err(err.with_retries(retry_state.total_retries()));
}
}
}
}
}
#[derive(Debug)]
enum CachedResponse {
/// The cached response is fresh without an HTTP request (e.g. age < max-age).
FreshCache(DataWithCachePolicy),
/// The cached response is fresh after an HTTP request (e.g. 304 not modified)
NotModified {
/// The cached response (with its old cache policy).
cached: DataWithCachePolicy,
/// The new [`CachePolicy`] is used to determine if the response
/// is fresh or stale when making subsequent requests for the same
/// resource. This policy should overwrite the old policy associated
/// with the cached response. In particular, this new policy is derived
/// from data received in a revalidation response, which might change
/// the parameters of cache behavior.
///
/// The policy is large (352 bytes at time of writing), so we reduce
/// the stack size by boxing it.
new_policy: Box<CachePolicy>,
},
/// There was no prior cached response or the cache was outdated
///
/// The cache policy is `None` if it isn't storable
ModifiedOrNew {
/// The response received from the server.
response: Response,
/// The [`CachePolicy`] is used to determine if the response is fresh or
/// stale when making subsequent requests for the same resource.
///
/// The policy is large (352 bytes at time of writing), so we reduce
/// the stack size by boxing it.
cache_policy: Option<Box<CachePolicy>>,
},
}
/// Represents an arbitrary data blob with an associated HTTP cache policy.
///
/// The cache policy is used to determine whether the data blob is stale or
/// not.
///
/// # Format
///
/// This type encapsulates the format for how blobs of data are stored on
/// disk. The format is very simple. First, the blob of data is written as-is.
/// Second, the archived representation of a `CachePolicy` is written. Thirdly,
/// the length, in bytes, of the archived `CachePolicy` is written as a 64-bit
/// little endian integer.
///
/// Reading the format is done via an `AlignedVec` so that `rkyv` can correctly
/// read the archived representation of the data blob. The cache policy is
/// split into its own `AlignedVec` allocation.
///
/// # Future ideas
///
/// This format was also chosen because it should in theory permit rewriting
/// the cache policy without needing to rewrite the data blob if the blob has
/// not changed. For example, this case occurs when a revalidation request
/// responds with HTTP 304 NOT MODIFIED. At time of writing, this is not yet
/// implemented because 1) the synchronization specifics of mutating a cache
/// file have not been worked out and 2) it's not clear if it's a win.
///
/// An alternative format would be to write the cache policy and the
/// blob in two distinct files. This would avoid needing to worry about
/// synchronization, but it means reading two files instead of one for every
/// cached response in the fast path. It's unclear whether it's worth it.
/// (Experiments have not yet been done.)
///
/// Another approach here would be to memory map the file and rejigger
/// `OwnedArchive` (or create a new type) that works with a memory map instead
/// of an `AlignedVec`. This will require care to ensure alignment is handled
/// correctly. This approach has not been litigated yet. I did not start with
/// it because experiments with ripgrep have tended to show that (on Linux)
/// memory mapping a bunch of small files ends up being quite a bit slower than
/// just reading them on to the heap.
#[derive(Debug)]
pub struct DataWithCachePolicy {
pub data: AlignedVec,
cache_policy: OwnedArchive<CachePolicy>,
}
impl DataWithCachePolicy {
/// Loads cached data and its associated HTTP cache policy from the given
/// file path in an asynchronous fashion (via `spawn_blocking`).
///
/// # Errors
///
| 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-client/src/httpcache/control.rs | crates/uv-client/src/httpcache/control.rs | use std::collections::HashSet;
use crate::rkyvutil::OwnedArchive;
/// Represents values for relevant cache-control directives.
///
/// This does include some directives that we don't use mostly because they are
/// trivial to support. (For example, `must-understand` at time of writing is
/// not used in our HTTP cache semantics. Neither is `proxy-revalidate` since
/// we are not a proxy.)
#[derive(
Clone,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Serialize,
)]
#[rkyv(derive(Debug))]
pub struct CacheControl {
// directives for requests and responses
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-max-age>
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-max-age-2>
pub max_age_seconds: Option<u64>,
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-cache>
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-cache-2>
pub no_cache: bool,
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-store>
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-store-2>
pub no_store: bool,
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-transform>
/// * <https://www.rfc-editor.org/rfc/rfc9111.html#name-no-transform-2>
pub no_transform: bool,
// request-only directives
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-max-stale>
pub max_stale_seconds: Option<u64>,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-min-fresh>
pub min_fresh_seconds: Option<u64>,
// response-only directives
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-only-if-cached>
pub only_if_cached: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-must-revalidate>
pub must_revalidate: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-must-understand>
pub must_understand: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-private>
pub private: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-proxy-revalidate>
pub proxy_revalidate: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-public>
pub public: bool,
/// <https://www.rfc-editor.org/rfc/rfc9111.html#name-s-maxage>
pub s_maxage_seconds: Option<u64>,
/// <https://httpwg.org/specs/rfc8246.html>
pub immutable: bool,
}
impl CacheControl {
/// Convert this to an owned archive value.
pub fn to_archived(&self) -> OwnedArchive<Self> {
// There's no way (other than OOM) for serializing this type to fail.
OwnedArchive::from_unarchived(self).expect("all possible values can be archived")
}
}
impl<'b, B: 'b + ?Sized + AsRef<[u8]>> FromIterator<&'b B> for CacheControl {
fn from_iter<T: IntoIterator<Item = &'b B>>(it: T) -> Self {
CacheControlParser::new(it).collect()
}
}
impl FromIterator<CacheControlDirective> for CacheControl {
fn from_iter<T: IntoIterator<Item = CacheControlDirective>>(it: T) -> Self {
fn parse_int(value: &[u8]) -> Option<u64> {
if !value.iter().all(u8::is_ascii_digit) {
return None;
}
std::str::from_utf8(value).ok()?.parse().ok()
}
let mut cc = Self::default();
for ccd in it {
// Note that when we see invalid directive values, we follow [RFC
// 9111 S4.2.1]. It says that invalid cache-control directives
// should result in treating the response as stale. (Which we
// accomplished by setting `must_revalidate` to `true`.)
//
// [RFC 9111 S4.2.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.2.1
match &*ccd.name {
// request + response directives
"max-age" => match parse_int(&ccd.value) {
None => cc.must_revalidate = true,
Some(seconds) => cc.max_age_seconds = Some(seconds),
},
"no-cache" => cc.no_cache = true,
"no-store" => cc.no_store = true,
"no-transform" => cc.no_transform = true,
// request-only directives
"max-stale" => {
// As per [RFC 9111 S5.2.1.2], "If no value is assigned to
// max-stale, then the client will accept a stale response
// of any age." We implement that by just using the maximum
// number of seconds.
//
// [RFC 9111 S5.2.1.2]: https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.2
if ccd.value.is_empty() {
cc.max_stale_seconds = Some(u64::MAX);
} else {
match parse_int(&ccd.value) {
None => cc.must_revalidate = true,
Some(seconds) => cc.max_stale_seconds = Some(seconds),
}
}
}
"min-fresh" => match parse_int(&ccd.value) {
None => cc.must_revalidate = true,
Some(seconds) => cc.min_fresh_seconds = Some(seconds),
},
"only-if-cached" => cc.only_if_cached = true,
"must-revalidate" => cc.must_revalidate = true,
"must-understand" => cc.must_understand = true,
"private" => cc.private = true,
"proxy-revalidate" => cc.proxy_revalidate = true,
"public" => cc.public = true,
"s-maxage" => match parse_int(&ccd.value) {
None => cc.must_revalidate = true,
Some(seconds) => cc.s_maxage_seconds = Some(seconds),
},
"immutable" => cc.immutable = true,
_ => {}
}
}
cc
}
}
/// A parser for the HTTP `Cache-Control` header.
///
/// The parser is mostly defined across multiple parts of multiple RFCs.
/// Namely, [RFC 9110 S5.6.2] says how to parse the names (or "keys") of each
/// directive (whose format is a "token"). [RFC 9110 S5.6.4] says how to parse
/// quoted values. And finally, [RFC 9111 Appendix A] gives the ABNF for the
/// overall header value.
///
/// This parser accepts an iterator of anything that can be cheaply converted
/// to a byte string (e.g., `http::header::HeaderValue`). Directives are parsed
/// from zero or more of these byte strings. Parsing cannot return an error,
/// but if something unexpected is found, the rest of that header value is
/// skipped.
///
/// Duplicate directives provoke an automatic insertion of `must-revalidate`,
/// as implied by [RFC 9111 S4.2.1], to ensure that the client will talk to the
/// server before using anything in case.
///
/// This parser handles a bit more than what we actually need in
/// `uv-client`. For example, we don't need to handle quoted values at all
/// since either don't use or care about values that require quoted. With that
/// said, the parser handles these because it wasn't that much extra work to do
/// so and just generally seemed like good sense. (If we didn't handle them and
/// parsed them incorrectly, that might mean parsing subsequent directives that
/// we do care about incorrectly.)
///
/// [RFC 9110 S5.6.2]: https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens
/// [RFC 9110 S5.6.4]: https://www.rfc-editor.org/rfc/rfc9110.html#name-quoted-strings
/// [RFC 9111 Appendix A]: https://www.rfc-editor.org/rfc/rfc9111.html#name-collected-abnf
/// [RFC 9111 S4.2.1]: https://www.rfc-editor.org/rfc/rfc9111.html#calculating.freshness.lifetime
struct CacheControlParser<'b, I> {
cur: &'b [u8],
directives: I,
seen: HashSet<String>,
}
impl<'b, B: 'b + ?Sized + AsRef<[u8]>, I: Iterator<Item = &'b B>> CacheControlParser<'b, I> {
/// Create a new parser of zero or more `Cache-Control` header values. The
/// given iterator should yield elements that satisfy `AsRef<[u8]>`.
fn new<II: IntoIterator<IntoIter = I>>(headers: II) -> Self {
let mut directives = headers.into_iter();
let cur = directives.next().map(AsRef::as_ref).unwrap_or(b"");
CacheControlParser {
cur,
directives,
seen: HashSet::new(),
}
}
/// Parses a token according to [RFC 9110 S5.6.2].
///
/// If no token is found at the current position, then this returns `None`.
/// Usually this indicates an invalid cache-control directive.
///
/// This does not trim whitespace before or after the token.
///
/// [RFC 9110 S5.6.2]: https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens
fn parse_token(&mut self) -> Option<String> {
/// Returns true when the given byte can appear in a token, as
/// defined by [RFC 9110 S5.6.2].
///
/// [RFC 9110 S5.6.2]: https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens
fn is_token_byte(byte: u8) -> bool {
matches!(
byte,
| b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+'
| b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~'
| b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z',
)
}
let mut end = 0;
while self.cur.get(end).copied().is_some_and(is_token_byte) {
end += 1;
}
if end == 0 {
None
} else {
let (token, rest) = self.cur.split_at(end);
self.cur = rest;
// This can't fail because `end` is only incremented when the
// current byte is a valid token byte. And all valid token bytes
// are ASCII and thus valid UTF-8.
Some(String::from_utf8(token.to_vec()).expect("all valid token bytes are valid UTF-8"))
}
}
/// Looks for an `=` as per [RFC 9111 Appendix A] which indicates that a
/// cache directive has a value.
///
/// This returns true if one was found. In which case, the `=` is consumed.
///
/// This does not trim whitespace before or after the token.
///
/// [RFC 9111 Appendix A]: https://www.rfc-editor.org/rfc/rfc9111.html#name-collected-abnf
fn maybe_parse_equals(&mut self) -> bool {
if self.cur.first().is_some_and(|&byte| byte == b'=') {
self.cur = &self.cur[1..];
true
} else {
false
}
}
/// Parses a directive value as either an unquoted token or a quoted string
/// as per [RFC 9111 Appendix A].
///
/// If a valid value could not be found (for example, end-of-input or an
/// opening quote without a closing quote), then `None` is returned. In
/// this case, one should consider the cache-control header invalid.
///
/// This does not trim whitespace before or after the token.
///
/// Note that the returned value is *not* guaranteed to be valid UTF-8.
/// Namely, it is possible for a quoted string to contain invalid UTF-8.
///
/// [RFC 9111 Appendix A]: https://www.rfc-editor.org/rfc/rfc9111.html#name-collected-abnf
fn parse_value(&mut self) -> Option<Vec<u8>> {
if *self.cur.first()? == b'"' {
self.cur = &self.cur[1..];
self.parse_quoted_string()
} else {
self.parse_token().map(String::into_bytes)
}
}
/// Parses a quoted string as per [RFC 9110 S5.6.4].
///
/// This assumes the opening quote has already been consumed.
///
/// If an invalid quoted string was found (e.g., no closing quote), then
/// `None` is returned. An empty value may be returned.
///
/// Note that the returned value is *not* guaranteed to be valid UTF-8.
/// Namely, it is possible for a quoted string to contain invalid UTF-8.
///
/// [RFC 9110 S5.6.4]: https://www.rfc-editor.org/rfc/rfc9110.html#name-quoted-strings
fn parse_quoted_string(&mut self) -> Option<Vec<u8>> {
fn is_qdtext_byte(byte: u8) -> bool {
matches!(byte, b'\t' | b' ' | 0x21 | 0x23..=0x5B | 0x5D..=0x7E | 0x80..=0xFF)
}
fn is_quoted_pair_byte(byte: u8) -> bool {
matches!(byte, b'\t' | b' ' | 0x21..=0x7E | 0x80..=0xFF)
}
let mut value = vec![];
while !self.cur.is_empty() {
let byte = self.cur[0];
self.cur = &self.cur[1..];
if byte == b'"' {
return Some(value);
} else if byte == b'\\' {
let byte = *self.cur.first()?;
self.cur = &self.cur[1..];
// If we saw an escape but didn't see a valid
// escaped byte, then we treat this value as
// invalid.
if !is_quoted_pair_byte(byte) {
return None;
}
value.push(byte);
} else if is_qdtext_byte(byte) {
value.push(byte);
} else {
break;
}
}
// If we got here, it means we hit end-of-input before seeing a closing
// quote. So we treat this as invalid and return `None`.
None
}
/// Looks for a `,` as per [RFC 9111 Appendix A]. If one is found, then it
/// is consumed and this returns true.
///
/// This does not trim whitespace before or after the token.
///
/// [RFC 9111 Appendix A]: https://www.rfc-editor.org/rfc/rfc9111.html#name-collected-abnf
fn maybe_parse_directive_delimiter(&mut self) -> bool {
if self.cur.first().is_some_and(|&byte| byte == b',') {
self.cur = &self.cur[1..];
true
} else {
false
}
}
/// [RFC 9111 Appendix A] says that optional whitespace may appear between
/// cache directives. We actually also allow whitespace to appear before
/// the first directive and after the last directive.
///
/// [RFC 9111 Appendix A]: https://www.rfc-editor.org/rfc/rfc9111.html#name-collected-abnf
fn skip_whitespace(&mut self) {
while self.cur.first().is_some_and(u8::is_ascii_whitespace) {
self.cur = &self.cur[1..];
}
}
fn emit_directive(
&mut self,
directive: CacheControlDirective,
) -> Option<CacheControlDirective> {
let duplicate = !self.seen.insert(directive.name.clone());
if duplicate {
self.emit_revalidation()
} else {
Some(directive)
}
}
fn emit_revalidation(&mut self) -> Option<CacheControlDirective> {
if self.seen.insert("must-revalidate".to_string()) {
Some(CacheControlDirective::must_revalidate())
} else {
// If we've already emitted a must-revalidate
// directive, then don't do it again.
None
}
}
}
impl<'b, B: 'b + ?Sized + AsRef<[u8]>, I: Iterator<Item = &'b B>> Iterator
for CacheControlParser<'b, I>
{
type Item = CacheControlDirective;
fn next(&mut self) -> Option<CacheControlDirective> {
loop {
if self.cur.is_empty() {
self.cur = self.directives.next().map(AsRef::as_ref)?;
}
while !self.cur.is_empty() {
self.skip_whitespace();
let Some(mut name) = self.parse_token() else {
// If we fail to parse a token, then this header value is
// either corrupt or empty. So skip the rest of it.
let invalid = !self.cur.is_empty();
self.cur = b"";
// But if it was invalid, force revalidation.
if invalid {
if let Some(d) = self.emit_revalidation() {
return Some(d);
}
}
break;
};
name.make_ascii_lowercase();
if !self.maybe_parse_equals() {
// Eat up whitespace and the next delimiter. We don't care
// if we find a terminator.
self.skip_whitespace();
self.maybe_parse_directive_delimiter();
let directive = CacheControlDirective {
name,
value: vec![],
};
match self.emit_directive(directive) {
None => continue,
Some(d) => return Some(d),
}
}
let Some(value) = self.parse_value() else {
// If we expected a value (we saw an =) but couldn't find a
// valid value, then this header value is probably corrupt.
// So skip the rest of it.
self.cur = b"";
match self.emit_revalidation() {
None => break,
Some(d) => return Some(d),
}
};
// Eat up whitespace and the next delimiter. We don't care if
// we find a terminator.
self.skip_whitespace();
self.maybe_parse_directive_delimiter();
let directive = CacheControlDirective { name, value };
if let Some(d) = self.emit_directive(directive) {
return Some(d);
}
}
}
}
}
/// A single directive from the `Cache-Control` header.
#[derive(Debug, Eq, PartialEq)]
struct CacheControlDirective {
/// The name of the directive.
name: String,
/// A possibly empty value.
///
/// Note that directive values may contain invalid UTF-8. (Although they
/// cannot actually contain arbitrary bytes. For example, NUL bytes, among
/// others, are not allowed.)
value: Vec<u8>,
}
impl CacheControlDirective {
/// Returns a `must-revalidate` directive. This is useful for forcing a
/// cache decision that the response is stale, and thus the server should
/// be consulted for whether the cached response ought to be used or not.
fn must_revalidate() -> Self {
Self {
name: "must-revalidate".to_string(),
value: vec![],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cache_control_token() {
let cc: CacheControl = CacheControlParser::new(["no-cache"]).collect();
assert!(cc.no_cache);
assert!(!cc.must_revalidate);
}
#[test]
fn cache_control_max_age() {
let cc: CacheControl = CacheControlParser::new(["max-age=60"]).collect();
assert_eq!(Some(60), cc.max_age_seconds);
assert!(!cc.must_revalidate);
}
// [RFC 9111 S5.2.1.1] says that client MUST NOT quote max-age, but we
// support parsing it that way anyway.
//
// [RFC 9111 S5.2.1.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.1
#[test]
fn cache_control_max_age_quoted() {
let cc: CacheControl = CacheControlParser::new([r#"max-age="60""#]).collect();
assert_eq!(Some(60), cc.max_age_seconds);
assert!(!cc.must_revalidate);
}
#[test]
fn cache_control_max_age_invalid() {
let cc: CacheControl = CacheControlParser::new(["max-age=6a0"]).collect();
assert_eq!(None, cc.max_age_seconds);
assert!(cc.must_revalidate);
}
#[test]
fn cache_control_immutable() {
let cc: CacheControl = CacheControlParser::new(["max-age=31536000, immutable"]).collect();
assert_eq!(Some(31_536_000), cc.max_age_seconds);
assert!(cc.immutable);
assert!(!cc.must_revalidate);
}
#[test]
fn cache_control_unrecognized() {
let cc: CacheControl = CacheControlParser::new(["lion,max-age=60,zebra"]).collect();
assert_eq!(Some(60), cc.max_age_seconds);
}
#[test]
fn cache_control_invalid_squashes_remainder() {
let cc: CacheControl = CacheControlParser::new(["no-cache,\x00,max-age=60"]).collect();
// The invalid data doesn't impact things before it.
assert!(cc.no_cache);
// The invalid data precludes parsing anything after.
assert_eq!(None, cc.max_age_seconds);
// The invalid contents should force revalidation.
assert!(cc.must_revalidate);
}
#[test]
fn cache_control_invalid_squashes_remainder_but_not_other_header_values() {
let cc: CacheControl =
CacheControlParser::new(["no-cache,\x00,max-age=60", "max-stale=30"]).collect();
// The invalid data doesn't impact things before it.
assert!(cc.no_cache);
// The invalid data precludes parsing anything after
// in the same header value, but not in other
// header values.
assert_eq!(Some(30), cc.max_stale_seconds);
// The invalid contents should force revalidation.
assert!(cc.must_revalidate);
}
#[test]
fn cache_control_parse_token() {
let directives = CacheControlParser::new(["no-cache"]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
}]
);
}
#[test]
fn cache_control_parse_token_to_token_value() {
let directives = CacheControlParser::new(["max-age=60"]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
}]
);
}
#[test]
fn cache_control_parse_token_to_quoted_string() {
let directives =
CacheControlParser::new([r#"private="cookie,x-something-else""#]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![CacheControlDirective {
name: "private".to_string(),
value: b"cookie,x-something-else".to_vec(),
}]
);
}
#[test]
fn cache_control_parse_token_to_quoted_string_with_escape() {
let directives =
CacheControlParser::new([r#"private="something\"crazy""#]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![CacheControlDirective {
name: "private".to_string(),
value: br#"something"crazy"#.to_vec(),
}]
);
}
#[test]
fn cache_control_parse_multiple_directives() {
let header = r#"max-age=60, no-cache, private="cookie", no-transform"#;
let directives = CacheControlParser::new([header]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "private".to_string(),
value: b"cookie".to_vec(),
},
CacheControlDirective {
name: "no-transform".to_string(),
value: vec![]
},
]
);
}
#[test]
fn cache_control_parse_multiple_directives_across_multiple_header_values() {
let headers = [
r"max-age=60, no-cache",
r#"private="cookie""#,
r"no-transform",
];
let directives = CacheControlParser::new(headers).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "private".to_string(),
value: b"cookie".to_vec(),
},
CacheControlDirective {
name: "no-transform".to_string(),
value: vec![]
},
]
);
}
#[test]
fn cache_control_parse_one_header_invalid() {
let headers = [
r"max-age=60, no-cache",
r#", private="cookie""#,
r"no-transform",
];
let directives = CacheControlParser::new(headers).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "must-revalidate".to_string(),
value: vec![]
},
CacheControlDirective {
name: "no-transform".to_string(),
value: vec![]
},
]
);
}
#[test]
fn cache_control_parse_invalid_directive_drops_remainder() {
let header = r#"max-age=60, no-cache, ="cookie", no-transform"#;
let directives = CacheControlParser::new([header]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "must-revalidate".to_string(),
value: vec![]
},
]
);
}
#[test]
fn cache_control_parse_name_normalized() {
let header = r"MAX-AGE=60";
let directives = CacheControlParser::new([header]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
}]
);
}
// When a duplicate directive is found, we keep the first one
// and add in a `must-revalidate` directive to indicate that
// things are stale and the client should do a re-check.
#[test]
fn cache_control_parse_duplicate_directives() {
let header = r"max-age=60, no-cache, max-age=30";
let directives = CacheControlParser::new([header]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "must-revalidate".to_string(),
value: vec![]
},
]
);
}
#[test]
fn cache_control_parse_duplicate_directives_across_headers() {
let headers = [r"max-age=60, no-cache", r"max-age=30"];
let directives = CacheControlParser::new(headers).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "must-revalidate".to_string(),
value: vec![]
},
]
);
}
// Tests that we don't emit must-revalidate multiple times
// even when something is duplicated multiple times.
#[test]
fn cache_control_parse_duplicate_redux() {
let header = r"max-age=60, no-cache, no-cache, max-age=30";
let directives = CacheControlParser::new([header]).collect::<Vec<_>>();
assert_eq!(
directives,
vec![
CacheControlDirective {
name: "max-age".to_string(),
value: b"60".to_vec(),
},
CacheControlDirective {
name: "no-cache".to_string(),
value: vec![]
},
CacheControlDirective {
name: "must-revalidate".to_string(),
value: vec![]
},
]
);
}
}
| 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-client/src/httpcache/mod.rs | crates/uv-client/src/httpcache/mod.rs | /*!
A somewhat simplistic implementation of HTTP cache semantics.
This implementation was guided by the following things:
* RFCs 9110 and 9111.
* The `http-cache-semantics` crate. (The implementation here is completely
different, but the source of `http-cache-semantics` helped guide the
implementation here and understanding of HTTP caching.)
* A desire for our cache policy to support zero-copy deserialization. That
is, we want the cached response fast path (where no revalidation request is
necessary) to avoid any costly deserialization for the cache policy at all.
# Flow
While one has to read the relevant RFCs to get a full understanding of HTTP
caching, doing so is... difficult to say the least. It is at the very least
not quick to do because the semantics are scattered all over the place. But, I
think we can do a quick overview here.
Let's start with the obvious. HTTP caching exists to avoid network requests,
and, if a request is unavoidable, bandwidth. The central actor in HTTP
caching is the `Cache-Control` header, which can exist on *both* requests and
responses. The value of this header is a list of directives that control caching
behavior. They can outright disable it (`no-store`), force cache invalidation
(`no-cache`) or even permit the cache to return responses that are explicitly
stale (`max-stale`).
The main thing that typically drives cache interactions is `max-age`. When set
on a response, this means that the server is willing to let clients hold on to
a response for up to the amount of time in `max-age` before the client must ask
the server for a fresh response. In our case, the main utility of `max-age` is
two fold:
* PyPI sets a `max-age` of 600 seconds (10 minutes) on its responses. As long
as our cached responses have an age less than this, we can completely avoid
talking to PyPI at all when we need access to the full set of versions for a
package.
* Most other assets, like wheels, are forever immutable. They will never
change. So servers will typically set a very high `max-age`, which means we
will almost never need to ask the server for permission to reuse our cached
wheel.
When a cached response exceeds the `max-age` configured on a response, then
we call that response stale. Generally speaking, we won't return responses
from the cache that are known to be stale. (This can be overridden in the
request by adding a `max-stale` cache-control directive, but nothing in uv
does this at time of writing.) When a response is stale, we don't necessarily
need to give up completely. It is at this point that we can send something
called a re-validation request.
A re-validation request includes with it some metadata (usually an "entity tag"
or `etag` for short) that was on the cached response (which is now stale).
When we send this request, the server can compare it with its most up-to-date
version of the resource. If its entity tag matches the one we gave it (among
other possible criteria), then the server can skip returning the body and
instead just return a small HTTP 304 NOT MODIFIED response. When we get this
type of response, it's the server telling us that our cached response which we
*thought* was stale is no longer stale. It's fresh again and we needn't get a
new copy. We will need to update our stored `CachePolicy` though, since the
HTTP 304 NOT MODIFIED response we got might included updated metadata relevant
to the behavior of caching (like a new `Age` header).
# Scope
In general, the cache semantics implemented below are targeted toward uv's
use case: a private client cache for custom data objects. This constraint
results in a modest simplification in what we need to support. That is, we
don't need to cache the entirety of the request's or response's headers (like
what `http-cache-semantics`) does. Instead, we only need to cache the data
necessary to *make decisions* about HTTP caching.
One example of this is the `Vary` response header. This requires checking the
the headers listed in a cached response have the same value in the original
request and the new request. If the new request has different values for those
headers (as specified in the cached response) than what was in the original
request, then the new request cannot used our cached response. Normally, this
would seemingly require storing all of the original request's headers. But we
only store the headers listed in the response.
Also, since we aren't a proxy, there are a host of proxy-specific rules for
managing headers and data that we needn't care about.
# Zero-copy deserialization
As mentioned above, we would really like our fast path (that is, a cached
response that we deem "fresh" and thus don't need to send a re-validation
request for) to avoid needing to actually deserialize a `CachePolicy`. While a
`CachePolicy` isn't particularly big, it is in our critical path. Yet, we still
need a `CachePolicy` to be able to decide whether a cached response is still
fresh or not. (This decision procedure is non-trivial, so it *probably* doesn't
make too much sense to hack around it with something simpler.)
We attempt to achieve this by implementing the `rkyv` traits for all of our
types. This means that if we read a `Vec<u8>` from a file, then we can very
cheaply turn that into a `rkyvutil::OwnedArchive<CachePolicy>`. Creating that
only requires a quick validation step, but is otherwise free. We can then
use that as-if it were an `Archived<CachePolicy>` (which is an alias for the
`ArchivedCachePolicy` type implicitly introduced by `derive(rkyv::Archive)`).
Crucially, this is why we implement all of our HTTP cache semantics logic on
`ArchivedCachePolicy` and *not* `CachePolicy`. It can be easy to forget this
because `rkyv` does such an amazing job of making its use of archived types
very closely resemble that of the standard types. For example, whenever the
methods below are accessing a field whose type is a `Vec` in the normal type,
what's actually being accessed is a [`rkyv::vec::ArchivedVec`]. Similarly,
for strings, it's [`rkyv::string::ArchivedString`] and not a standard library
`String`. This all works somewhat seamlessly because all of the cache semantics
are generally just read-only operations, but if you stray from the path, you're
likely to get whacked over the head.
One catch here is that we actually want the HTTP cache semantics to be
available on `CachePolicy` too. At least, at time of writing, we do. To
achieve this `CachePolicy::to_archived` is provided, which will serialize the
`CachePolicy` to its archived representation in bytes, and then turn that
into an `OwnedArchive<CachePolicy>` which derefs to `ArchivedCachePolicy`.
This is a little extra cost, but the idea is that a `CachePolicy` (not an
`ArchivedCachePolicy`) should only be used in the slower path (i.e., when you
actually need to make an HTTP request).
[`rkyv::vec::ArchivedVec`]: https://docs.rs/rkyv/0.7.43/rkyv/vec/struct.ArchivedVec.html
[`rkyv::string::ArchivedString`]: https://docs.rs/rkyv/0.7.43/rkyv/string/struct.ArchivedString.html
# Additional reading
* Short introduction to `Cache-Control`: <https://csswizardry.com/2019/03/cache-control-for-civilians/>
* Caching best practices: <https://jakearchibald.com/2016/caching-best-practices/>
* Overview of HTTP caching: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching>
* MDN docs for `Cache-Control`: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control>
* The 1997 RFC for HTTP 1.1: <https://www.rfc-editor.org/rfc/rfc2068#section-13>
* The 1999 update to HTTP 1.1: <https://www.rfc-editor.org/rfc/rfc2616.html#section-13>
* The "stale content" cache-control extension: <https://httpwg.org/specs/rfc5861.html>
* HTTP 1.1 caching (superseded by RFC 9111): <https://httpwg.org/specs/rfc7234.html>
* The "immutable" cache-control extension: <https://httpwg.org/specs/rfc8246.html>
* HTTP semantics (If-None-Match, etc.): <https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3>
* HTTP caching (obsoletes RFC 7234): <https://www.rfc-editor.org/rfc/rfc9111.html>
*/
use std::time::{Duration, SystemTime};
use http::header::HeaderValue;
use crate::rkyvutil::OwnedArchive;
use self::control::CacheControl;
mod control;
/// Knobs to configure uv's cache behavior.
///
/// At time of writing, we don't expose any way of modifying these since I
/// suspect we won't ever need to. We split them out into their own type so
/// that they can be shared between `CachePolicyBuilder` and `CachePolicy`.
#[derive(
Clone,
Debug,
Default,
rkyv::Archive,
rkyv::Deserialize,
rkyv::Portable,
rkyv::Serialize,
bytecheck::CheckBytes,
)]
// Since `CacheConfig` is so simple, we can use itself as the archived type.
// But note that this will fall apart if even something like an Option<u8> is
// added.
#[rkyv(as = Self)]
#[repr(C)]
struct CacheConfig {
shared: bool,
}
/// A builder for constructing a `CachePolicy`.
///
/// A builder can be used directly when spawning fresh HTTP requests
/// without a cached response. A builder is also constructed for you via
/// [`CachePolicy::before_request`] when a cached response exists but is stale.
///
/// The main idea of a builder is that it manages the flow of data needed to
/// construct a `CachePolicy`. That is, you start with an HTTP request, then
/// you get a response and finally a new `CachePolicy`.
#[derive(Debug)]
pub struct CachePolicyBuilder {
/// The configuration controlling the behavior of the cache.
config: CacheConfig,
/// A subset of information from the HTTP request that we will store. This
/// is needed to make future decisions about cache behavior.
request: Request,
/// The full set of request headers. This copy is necessary because the
/// headers are needed in order to correctly capture the values necessary
/// to implement the `Vary` check, as per [RFC 9111 S4.1]. The upside is
/// that this is not actually persisted in a `CachePolicy`. We only need it
/// until we have the response.
///
/// The precise reason why this copy is intrinsically needed is because
/// sending a request requires ownership of the request. Yet, we don't know
/// which header values we need to store in our cache until we get the
/// response back. Thus, these headers must be persisted until after the
/// point we've given up ownership of the request.
///
/// [RFC 9111 S4.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1
request_headers: http::HeaderMap,
}
impl CachePolicyBuilder {
/// Create a new builder of a cache policy, starting with the request.
pub fn new(request: &reqwest::Request) -> Self {
let config = CacheConfig::default();
let request_headers = request.headers().clone();
let request = Request::from(request);
Self {
config,
request,
request_headers,
}
}
/// Return a new policy given the response to the request that this builder
/// was created with.
pub fn build(self, response: &reqwest::Response) -> CachePolicy {
let vary = Vary::from_request_response_headers(&self.request_headers, response.headers());
CachePolicy {
config: self.config,
request: self.request,
response: Response::from(response),
vary,
}
}
}
/// A value encapsulating the data needed to implement HTTP caching behavior
/// for uv.
///
/// A cache policy is meant to be stored and persisted with the data being
/// cached. It is specifically meant to capture the smallest amount of
/// information needed to determine whether a cached response is stale or not,
/// and the information required to issue a re-validation request.
///
/// This does not provide a complete set of HTTP cache semantics. Notably
/// absent from this (among other things that uv probably doesn't care
/// about it) are proxy cache semantics.
#[derive(Debug, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)]
#[rkyv(derive(Debug))]
pub struct CachePolicy {
/// The configuration controlling the behavior of the cache.
config: CacheConfig,
/// A subset of information from the HTTP request that we will store. This
/// is needed to make future decisions about cache behavior.
request: Request,
/// A subset of information from the HTTP response that we will store. This
/// is needed to make future decisions about cache behavior.
response: Response,
/// This contains the set of vary header names (from the cached response)
/// and the corresponding values (from the original request) used to verify
/// whether a new request can utilize a cached response or not. This is
/// placed outside of `request` and `response` because it contains bits
/// from both!
vary: Vary,
}
impl CachePolicy {
/// Convert this to an owned archive value.
///
/// It's necessary to call this in order to make decisions with this cache
/// policy. Namely, all of the cache semantics logic is implemented on the
/// archived types.
///
/// These do incur an extra cost, but this should only be needed when you
/// don't have an `ArchivedCachePolicy`. And that should only occur when
/// you're actually performing an HTTP request. In that case, the extra
/// cost that is done here to convert a `CachePolicy` to its archived form
/// should be marginal.
pub fn to_archived(&self) -> OwnedArchive<Self> {
// There's no way (other than OOM) for serializing this type to fail.
OwnedArchive::from_unarchived(self).expect("all possible values can be archived")
}
}
impl ArchivedCachePolicy {
/// Determines what caching behavior is correct given an existing
/// `CachePolicy` and a new HTTP request for the resource managed by this
/// cache policy. This is done as per [RFC 9111 S4].
///
/// Calling this method conceptually corresponds to asking the following
/// question: "I have a cached response for an incoming HTTP request. May I
/// return that cached response, or do I need to go back to the progenitor
/// of that response to determine whether it's still the latest thing?"
///
/// This returns one of three possible behaviors:
///
/// 1. The cached response is still fresh, and the caller may return
/// the cached response without issuing an HTTP requests.
/// 2. The cached response is stale. The caller should send a re-validation
/// request and then call `CachePolicy::after_response` to determine whether
/// the cached response is actually fresh, or if it's stale and needs to
/// be updated.
/// 3. The given request does not match the cache policy identification.
/// Generally speaking, this usually implies a bug with the cache in that
/// it loaded a cache policy that does not match the request.
///
/// In the case of (2), the given request is modified in place such that
/// it is suitable as a revalidation request.
///
/// [RFC 9111 S4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4
pub fn before_request(&self, request: &mut reqwest::Request) -> BeforeRequest {
let now = SystemTime::now();
// If the response was never storable, then we just bail out
// completely.
if !self.is_storable() {
tracing::trace!(
"Request {} does not match cache request {} because it isn't storable",
request.url(),
self.request.uri,
);
return BeforeRequest::NoMatch;
}
// "When presented with a request, a cache MUST NOT reuse a stored
// response unless..."
//
// "the presented target URI and that of the stored response match,
// and..."
if self.request.uri != request.url().as_str() {
tracing::trace!(
"Request {} does not match cache URL of {}",
request.url(),
self.request.uri,
);
return BeforeRequest::NoMatch;
}
// "the request method associated with the stored response allows it to
// be used for the presented request, and..."
if request.method() != http::Method::GET && request.method() != http::Method::HEAD {
tracing::trace!(
"Method {:?} for request {} is not supported by this cache",
request.method(),
request.url(),
);
return BeforeRequest::NoMatch;
}
// "Request header fields nominated by the stored response (if any)
// match those presented, and..."
//
// We don't support the `Vary` header, so if it was set, we
// conservatively require revalidation.
if !self.vary.matches(request.headers()) {
tracing::trace!(
"Request {} does not match cached request because of the 'Vary' header",
request.url(),
);
self.set_revalidation_headers(request);
return BeforeRequest::Stale(self.new_cache_policy_builder(request));
}
// "the stored response does not contain the no-cache directive, unless
// it is successfully validated, and..."
if self.response.headers.cc.no_cache {
self.set_revalidation_headers(request);
return BeforeRequest::Stale(self.new_cache_policy_builder(request));
}
// "the stored response is one of the following: ..."
//
// "fresh, or..."
// "allowed to be served stale, or..."
if self.is_fresh(now, request) {
return BeforeRequest::Fresh;
}
// "successfully validated."
//
// In this case, callers will need to send a revalidation request.
self.set_revalidation_headers(request);
BeforeRequest::Stale(self.new_cache_policy_builder(request))
}
/// This implements the logic for handling the response to a request that
/// may be a revalidation request, as per [RFC 9111 S4.3.3] and [RFC 9111
/// S4.3.4]. That is, the cache policy builder given here should be the one
/// returned by `CachePolicy::before_request` with the response received
/// from the origin server for the possibly-revalidating request.
///
/// Even if the request is new (in that there is no response cached
/// for it), callers may use this routine. But generally speaking,
/// callers are only supposed to use this routine after getting a
/// [`BeforeRequest::Stale`].
///
/// The return value indicates whether the cached response is still fresh
/// (that is, `AfterResponse::NotModified`) or if it has changed (that is,
/// `AfterResponse::Modified`). In the latter case, the cached response has
/// been invalidated and the caller should cache the new response. In the
/// former case, the cached response is still considered fresh.
///
/// In either case, callers should update their cache with the new policy.
///
/// [RFC 9111 S4.3.3]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.3
/// [RFC 9111 S4.3.4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.4
pub fn after_response(
&self,
cache_policy_builder: CachePolicyBuilder,
response: &reqwest::Response,
) -> AfterResponse {
let mut new_policy = cache_policy_builder.build(response);
if self.is_modified(&new_policy) {
AfterResponse::Modified(new_policy)
} else {
new_policy.response.status = self.response.status.into();
AfterResponse::NotModified(new_policy)
}
}
fn is_modified(&self, new_policy: &CachePolicy) -> bool {
// From [RFC 9111 S4.3.3],
//
// "A 304 (Not Modified) response status code indicates that the stored
// response can be updated and reused"
//
// So if we don't get a 304, then we know our cached response is seen
// as stale by the origin server.
//
// [RFC 9111 S4.3.3]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.3
if new_policy.response.status != 304 {
tracing::trace!(
"Resource is modified because status is {:?} and not 304",
new_policy.response.status
);
return true;
}
// As per [RFC 9111 S4.3.4], we need to confirm that our validators match. Here,
// we check `ETag`.
//
// [RFC 9111 S4.3.4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.4
if let Some(old_etag) = self.response.headers.etag.as_ref() {
if let Some(new_etag) = new_policy.response.headers.etag.as_ref() {
// We don't support weak validators, so only match if they're
// both strong.
if !old_etag.weak && !new_etag.weak && old_etag.value == new_etag.value {
tracing::trace!(
"Resource is not modified because old and new etag values ({:?}) match",
new_etag.value,
);
return false;
}
}
}
// As per [RFC 9111 S4.3.4], we need to confirm that our validators match. Here,
// we check `Last-Modified`.
//
// [RFC 9111 S4.3.4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.4
if let Some(old_last_modified) = self.response.headers.last_modified_unix_timestamp.as_ref()
{
if let Some(new_last_modified) = new_policy
.response
.headers
.last_modified_unix_timestamp
.as_ref()
{
if old_last_modified == new_last_modified {
tracing::trace!(
"Resource is not modified because modified times ({new_last_modified:?}) match",
);
return false;
}
}
}
// As per [RFC 9111 S4.3.4], if we have no validators anywhere, then
// we can just rely on the HTTP 304 status code and reuse the cached
// response.
//
// [RFC 9111 S4.3.4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.4
if self.response.headers.etag.is_none()
&& new_policy.response.headers.etag.is_none()
&& self.response.headers.last_modified_unix_timestamp.is_none()
&& new_policy
.response
.headers
.last_modified_unix_timestamp
.is_none()
{
tracing::trace!(
"Resource is not modified because there are no etags or last modified \
timestamps, so we assume the 304 status is correct",
);
return false;
}
true
}
/// Sets the relevant headers on the given request so that it can be used
/// as a revalidation request. As per [RFC 9111 S4.3.1], this permits the
/// origin server to check if the content is different from our cached
/// response. If it isn't, then the origin server can return an HTTP 304
/// NOT MODIFIED status, which avoids the need to re-transmit the response
/// body. That is, it indicates that our cached response is still fresh.
///
/// This will always use a strong etag validator if it's present on the
/// cached response. If the given request already has an etag validator
/// on it, this routine will add to it and not replace it.
///
/// In contrast, if the request already has the `If-Modified-Since` header
/// set, then this will not change or replace it. If it's not set, then one
/// is added if the cached response had a valid `Last-Modified` header.
///
/// [RFC 9111 S4.3.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.1
fn set_revalidation_headers(&self, request: &mut reqwest::Request) {
// As per [RFC 9110 13.1.2] and [RFC 9111 S4.3.1], if our stored
// response has an etag, we should send it back via the `If-None-Match`
// header. The idea is that the server should only "do" the request if
// none of the tags match. If there is a match, then the server can
// return HTTP 304 indicating that our stored response is still fresh.
//
// [RFC 9110 S13.1.2]: https://www.rfc-editor.org/rfc/rfc9110#section-13.1.2
// [RFC 9111 S4.3.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.1
if let Some(etag) = self.response.headers.etag.as_ref() {
// We don't support weak validation principally because we want to
// be notified if there was a change in the content. Namely, from
// RFC 9110 S13.1.2: "... weak entity tags can be used for cache
// validation even if there have been changes to the representation
// data."
if !etag.weak {
if let Ok(header) = HeaderValue::from_bytes(&etag.value) {
request.headers_mut().append("if-none-match", header);
}
}
}
// We also set `If-Modified-Since` as per [RFC 9110 S13.1.3] and [RFC
// 9111 S4.3.1]. Generally, `If-None-Match` will override this, but we
// set it in case `If-None-Match` is not supported.
//
// [RFC 9110 S13.1.3]: https://www.rfc-editor.org/rfc/rfc9110#section-13.1.3
// [RFC 9111 S4.3.1]: https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.1
if !request.headers().contains_key("if-modified-since") {
if let Some(&last_modified_unix_timestamp) =
self.response.headers.last_modified_unix_timestamp.as_ref()
{
if let Some(last_modified) =
unix_timestamp_to_header(last_modified_unix_timestamp.into())
{
request
.headers_mut()
.insert("if-modified-since", last_modified);
}
}
}
}
/// Returns true if and only if the response is storable as per
/// [RFC 9111 S3].
///
/// [RFC 9111 S3]: https://www.rfc-editor.org/rfc/rfc9111.html#section-3
pub fn is_storable(&self) -> bool {
// In the absence of other signals, we are limited to caching responses
// with a code that is heuristically cacheable as per [RFC 9110 S15.1].
//
// [RFC 9110 S15.1]: https://www.rfc-editor.org/rfc/rfc9110#section-15.1
const HEURISTICALLY_CACHEABLE_STATUS_CODES: &[u16] =
&[200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501];
// N.B. This routine could be "simpler", but we bias toward
// following the flow of logic as closely as possible as written
// in RFC 9111 S3.
// "the request method is understood by the cache"
//
// We just don't bother with anything that isn't GET.
if !matches!(
self.request.method,
ArchivedMethod::Get | ArchivedMethod::Head
) {
tracing::trace!(
"Response from {} is not storable because of the request method {:?}",
self.request.uri,
self.request.method
);
return false;
}
// "the response status code is final"
//
// ... and we'll put more restrictions on status code
// below, but we can bail out early here.
if !self.response.has_final_status() {
tracing::trace!(
"Response from {} is not storable because it has \
a non-final status code {:?}",
self.request.uri,
self.response.status,
);
return false;
}
// "if the response status code is 206 or 304, or the must-understand
// cache directive (see Section 5.2.2.3) is present: the cache
// understands the response status code"
//
// We don't currently support `must-understand`. We also don't support
// partial content (206). And 304 not modified shouldn't be cached
// itself.
if self.response.status == 206 || self.response.status == 304 {
tracing::trace!(
"Response from {} is not storable because it has \
an unsupported status code {:?}",
self.request.uri,
self.response.status,
);
return false;
}
// "The no-store request directive indicates that a cache MUST NOT
// store any part of either this request or any response to it."
//
// (This is from RFC 9111 S5.2.1.5, and doesn't seem to be mentioned in
// S3.)
if self.request.headers.cc.no_store {
tracing::trace!(
"Response from {} is not storable because its request has \
a 'no-store' cache-control directive",
self.request.uri,
);
return false;
}
// "the no-store cache directive is not present in the response"
if self.response.headers.cc.no_store {
tracing::trace!(
"Response from {} is not storable because it has \
a 'no-store' cache-control directive",
self.request.uri,
);
return false;
}
// "if the cache is shared ..."
if self.config.shared {
// "if the cache is shared: the private response directive is either
// not present or allows a shared cache to store a modified response"
//
// We don't support more granular "private" directives (which allow
// caching all of a private HTTP response in a shared cache only after
// removing some subset of the response's headers that are deemed
// private).
if self.response.headers.cc.private {
tracing::trace!(
"Response from {} is not storable because this is a shared \
cache and has a 'private' cache-control directive",
self.request.uri,
);
return false;
}
// "if the cache is shared: the Authorization header field is not
// present in the request or a response directive is present that
// explicitly allows shared caching"
if self.request.headers.authorization && !self.allows_authorization_storage() {
tracing::trace!(
"Response from {} is not storable because this is a shared \
cache and the request has an 'Authorization' header set and \
the response has indicated that caching requests with an \
'Authorization' header is allowed",
self.request.uri,
);
return false;
}
}
// "the response contains at least one of the following ..."
//
// "a public response directive"
if self.response.headers.cc.public {
tracing::trace!(
"Response from {} is storable because it has \
a 'public' cache-control directive",
self.request.uri,
);
return true;
}
// "a private response directive, if the cache is not shared"
if !self.config.shared && self.response.headers.cc.private {
tracing::trace!(
"Response from {} is storable because this is a shared cache \
and has a 'private' cache-control directive",
self.request.uri,
);
return true;
}
// "an Expires header field"
if self.response.headers.expires_unix_timestamp.is_some() {
tracing::trace!(
"Response from {} is storable because it has an \
'Expires' header set",
self.request.uri,
);
return true;
}
// "a max-age response directive"
if self.response.headers.cc.max_age_seconds.is_some() {
tracing::trace!(
"Response from {} is storable because it has an \
'max-age' cache-control directive",
self.request.uri,
);
return true;
}
// "if the cache is shared: an s-maxage response directive"
| 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-client/tests/it/user_agent_version.rs | crates/uv-client/tests/it/user_agent_version.rs | use std::str::FromStr;
use anyhow::Result;
use insta::{assert_json_snapshot, assert_snapshot, with_settings};
use url::Url;
use uv_cache::Cache;
use uv_client::RegistryClientBuilder;
use uv_client::{BaseClientBuilder, LineHaul};
use uv_pep508::{MarkerEnvironment, MarkerEnvironmentBuilder};
use uv_platform_tags::{Arch, Os, Platform};
use uv_redacted::DisplaySafeUrl;
use uv_version::version;
use crate::http_util::start_http_user_agent_server;
#[tokio::test]
async fn test_user_agent_has_version() -> Result<()> {
// Initialize dummy http server
let (server_task, addr) = start_http_user_agent_server().await?;
// Initialize uv-client
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
// Send request to our dummy server
let url = DisplaySafeUrl::from_str(&format!("http://{addr}"))?;
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await?;
// Check the HTTP status
assert!(res.status().is_success());
// Check User Agent
let body = res.text().await?;
let (uv_version, uv_linehaul) = body
.split_once(' ')
.expect("Failed to split User-Agent header");
// Deserializing Linehaul
let linehaul: LineHaul = serde_json::from_str(uv_linehaul)?;
// Assert linehaul user agent
let filters = vec![(version(), "[VERSION]")];
with_settings!({
filters => filters
}, {
// Assert uv version
assert_snapshot!(uv_version, @"uv/[VERSION]");
// Assert linehaul json
assert_json_snapshot!(&linehaul.installer, @r#"
{
"name": "uv",
"version": "[VERSION]",
"subcommand": null
}
"#);
});
// Wait for the server task to complete, to be a good citizen.
let _ = server_task.await?;
Ok(())
}
#[tokio::test]
async fn test_user_agent_has_subcommand() -> Result<()> {
// Initialize dummy http server
let (server_task, addr) = start_http_user_agent_server().await?;
// Initialize uv-client
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(
BaseClientBuilder::default().subcommand(vec!["foo".to_owned(), "bar".to_owned()]),
cache,
)
.build();
// Send request to our dummy server
let url = DisplaySafeUrl::from_str(&format!("http://{addr}"))?;
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await?;
// Check the HTTP status
assert!(res.status().is_success());
// Check User Agent
let body = res.text().await?;
let (uv_version, uv_linehaul) = body
.split_once(' ')
.expect("Failed to split User-Agent header");
// Deserializing Linehaul
let linehaul: LineHaul = serde_json::from_str(uv_linehaul)?;
// Assert linehaul user agent
let filters = vec![(version(), "[VERSION]")];
with_settings!({
filters => filters
}, {
// Assert uv version
assert_snapshot!(uv_version, @"uv/[VERSION]");
// Assert linehaul json
assert_json_snapshot!(&linehaul.installer, @r#"
{
"name": "uv",
"version": "[VERSION]",
"subcommand": [
"foo",
"bar"
]
}
"#);
});
// Wait for the server task to complete, to be a good citizen.
let _ = server_task.await?;
Ok(())
}
#[tokio::test]
async fn test_user_agent_has_linehaul() -> Result<()> {
// Initialize dummy http server
let (server_task, addr) = start_http_user_agent_server().await?;
// Add some representative markers for an Ubuntu CI runner
let markers = MarkerEnvironment::try_from(MarkerEnvironmentBuilder {
implementation_name: "cpython",
implementation_version: "3.12.2",
os_name: "posix",
platform_machine: "x86_64",
platform_python_implementation: "CPython",
platform_release: "6.5.0-1016-azure",
platform_system: "Linux",
platform_version: "#16~22.04.1-Ubuntu SMP Fri Feb 16 15:42:02 UTC 2024",
python_full_version: "3.12.2",
python_version: "3.12",
sys_platform: "linux",
})?;
// Initialize uv-client
let cache = Cache::temp()?.init().await?;
let mut builder =
RegistryClientBuilder::new(BaseClientBuilder::default(), cache).markers(&markers);
let linux = Platform::new(
Os::Manylinux {
major: 2,
minor: 38,
},
Arch::X86_64,
);
let macos = Platform::new(
Os::Macos {
major: 14,
minor: 4,
},
Arch::Aarch64,
);
if cfg!(target_os = "linux") {
builder = builder.platform(&linux);
} else if cfg!(target_os = "macos") {
builder = builder.platform(&macos);
}
let client = builder.build();
// Send request to our dummy server
let url = DisplaySafeUrl::from_str(&format!("http://{addr}"))?;
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await?;
// Check the HTTP status
assert!(res.status().is_success());
// Check User Agent
let body = res.text().await?;
// Wait for the server task to complete, to be a good citizen.
let _ = server_task.await?;
// Unpack User-Agent with linehaul
let (uv_version, uv_linehaul) = body
.split_once(' ')
.expect("Failed to split User-Agent header");
// Deserializing Linehaul
let linehaul: LineHaul = serde_json::from_str(uv_linehaul)?;
// Assert linehaul user agent
let filters = vec![(version(), "[VERSION]")];
with_settings!({
filters => filters
}, {
// Assert uv version
assert_snapshot!(uv_version, @"uv/[VERSION]");
// Assert linehaul json
assert_json_snapshot!(&linehaul, {
".distro" => "[distro]",
".ci" => "[ci]"
}, @r#"
{
"installer": {
"name": "uv",
"version": "[VERSION]",
"subcommand": null
},
"python": "3.12.2",
"implementation": {
"name": "CPython",
"version": "3.12.2"
},
"distro": "[distro]",
"system": {
"name": "Linux",
"release": "6.5.0-1016-azure"
},
"cpu": "x86_64",
"openssl_version": null,
"setuptools_version": null,
"rustc_version": null,
"ci": "[ci]"
}
"#);
});
// Assert distro
if cfg!(windows) {
assert_json_snapshot!(&linehaul.distro, @"null");
} else if cfg!(target_os = "linux") {
assert_json_snapshot!(&linehaul.distro, {
".id" => "[distro.id]",
".name" => "[distro.name]",
".version" => "[distro.version]"
// We mock the libc version already
}, @r###"
{
"name": "[distro.name]",
"version": "[distro.version]",
"id": "[distro.id]",
"libc": {
"lib": "glibc",
"version": "2.38"
}
}"###
);
// Check dynamic values
let distro_info = linehaul
.distro
.expect("got no distro, but expected one in linehaul");
// Gather distribution info from /etc/os-release.
let release_info = sys_info::linux_os_release()
.expect("got no os release info, but expected one in linux");
assert_eq!(distro_info.id, release_info.version_codename);
assert_eq!(distro_info.name, release_info.name);
assert_eq!(distro_info.version, release_info.version_id);
} else if cfg!(target_os = "macos") {
// We mock the macOS distro
assert_json_snapshot!(&linehaul.distro, @r###"
{
"name": "macOS",
"version": "14.4",
"id": null,
"libc": null
}"###
);
}
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-client/tests/it/main.rs | crates/uv-client/tests/it/main.rs | mod http_util;
mod remote_metadata;
mod ssl_certs;
mod user_agent_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-client/tests/it/http_util.rs | crates/uv-client/tests/it/http_util.rs | use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result};
use futures::future;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::header::USER_AGENT;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder;
use rcgen::{
BasicConstraints, Certificate, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa,
Issuer, KeyPair, KeyUsagePurpose, SanType, date_time_ymd,
};
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::{RootCertStore, ServerConfig};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tokio_rustls::TlsAcceptor;
use uv_fs::Simplified;
/// An issued certificate, together with the subject keypair.
#[derive(Debug)]
pub(crate) struct SelfSigned {
/// An issued certificate.
pub public: Certificate,
/// The certificate's subject signing key.
pub private: KeyPair,
}
/// Defines the base location for temporary generated certs.
///
/// See [`TestContext::test_bucket_dir`] for implementation rationale.
pub(crate) fn test_cert_dir() -> PathBuf {
std::env::temp_dir()
.simple_canonicalize()
.expect("failed to canonicalize temp dir")
.join("uv")
.join("tests")
.join("certs")
}
/// Generates a self-signed server certificate for `uv-test-server`, `localhost` and `127.0.0.1`.
/// This certificate is standalone and not issued by a self-signed Root CA.
///
/// Use sparingly as generation of certs is a slow operation.
pub(crate) fn generate_self_signed_certs() -> Result<SelfSigned> {
let mut params = CertificateParams::default();
params.is_ca = IsCa::NoCa;
params.not_before = date_time_ymd(1975, 1, 1);
params.not_after = date_time_ymd(4096, 1, 1);
params.key_usages.push(KeyUsagePurpose::DigitalSignature);
params.key_usages.push(KeyUsagePurpose::KeyEncipherment);
params
.extended_key_usages
.push(ExtendedKeyUsagePurpose::ServerAuth);
params
.distinguished_name
.push(DnType::OrganizationName, "Astral Software Inc.");
params
.distinguished_name
.push(DnType::CommonName, "uv-test-server");
params
.subject_alt_names
.push(SanType::DnsName("uv-test-server".try_into()?));
params
.subject_alt_names
.push(SanType::DnsName("localhost".try_into()?));
params
.subject_alt_names
.push(SanType::IpAddress("127.0.0.1".parse()?));
let private = KeyPair::generate()?;
let public = params.self_signed(&private)?;
Ok(SelfSigned { public, private })
}
/// Generates a self-signed root CA, server certificate, and client certificate.
/// There are no intermediate certs generated as part of this function.
/// The server certificate is for `uv-test-server`, `localhost` and `127.0.0.1` issued by this CA.
/// The client certificate is for `uv-test-client` issued by this CA.
///
/// Use sparingly as generation of these certs is a very slow operation.
pub(crate) fn generate_self_signed_certs_with_ca() -> Result<(SelfSigned, SelfSigned, SelfSigned)> {
// Generate the CA
let mut ca_params = CertificateParams::default();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); // root cert
ca_params.not_before = date_time_ymd(1975, 1, 1);
ca_params.not_after = date_time_ymd(4096, 1, 1);
ca_params.key_usages.push(KeyUsagePurpose::DigitalSignature);
ca_params.key_usages.push(KeyUsagePurpose::KeyCertSign);
ca_params.key_usages.push(KeyUsagePurpose::CrlSign);
ca_params
.distinguished_name
.push(DnType::OrganizationName, "Astral Software Inc.");
ca_params
.distinguished_name
.push(DnType::CommonName, "uv-test-ca");
ca_params
.subject_alt_names
.push(SanType::DnsName("uv-test-ca".try_into()?));
let ca_private_key = KeyPair::generate()?;
let ca_public_cert = ca_params.self_signed(&ca_private_key)?;
let ca_cert_issuer = Issuer::new(ca_params, &ca_private_key);
// Generate server cert issued by this CA
let mut server_params = CertificateParams::default();
server_params.is_ca = IsCa::NoCa;
server_params.not_before = date_time_ymd(1975, 1, 1);
server_params.not_after = date_time_ymd(4096, 1, 1);
server_params.use_authority_key_identifier_extension = true;
server_params
.key_usages
.push(KeyUsagePurpose::DigitalSignature);
server_params
.key_usages
.push(KeyUsagePurpose::KeyEncipherment);
server_params
.extended_key_usages
.push(ExtendedKeyUsagePurpose::ServerAuth);
server_params
.distinguished_name
.push(DnType::OrganizationName, "Astral Software Inc.");
server_params
.distinguished_name
.push(DnType::CommonName, "uv-test-server");
server_params
.subject_alt_names
.push(SanType::DnsName("uv-test-server".try_into()?));
server_params
.subject_alt_names
.push(SanType::DnsName("localhost".try_into()?));
server_params
.subject_alt_names
.push(SanType::IpAddress("127.0.0.1".parse()?));
let server_private_key = KeyPair::generate()?;
let server_public_cert = server_params.signed_by(&server_private_key, &ca_cert_issuer)?;
// Generate client cert issued by this CA
let mut client_params = CertificateParams::default();
client_params.is_ca = IsCa::NoCa;
client_params.not_before = date_time_ymd(1975, 1, 1);
client_params.not_after = date_time_ymd(4096, 1, 1);
client_params.use_authority_key_identifier_extension = true;
client_params
.key_usages
.push(KeyUsagePurpose::DigitalSignature);
client_params
.extended_key_usages
.push(ExtendedKeyUsagePurpose::ClientAuth);
client_params
.distinguished_name
.push(DnType::OrganizationName, "Astral Software Inc.");
client_params
.distinguished_name
.push(DnType::CommonName, "uv-test-client");
client_params
.subject_alt_names
.push(SanType::DnsName("uv-test-client".try_into()?));
let client_private_key = KeyPair::generate()?;
let client_public_cert = client_params.signed_by(&client_private_key, &ca_cert_issuer)?;
let ca_self_signed = SelfSigned {
public: ca_public_cert,
private: ca_private_key,
};
let server_self_signed = SelfSigned {
public: server_public_cert,
private: server_private_key,
};
let client_self_signed = SelfSigned {
public: client_public_cert,
private: client_private_key,
};
Ok((ca_self_signed, server_self_signed, client_self_signed))
}
// Plain is fine for now; Arc/Box could be used later if we need to support move.
type ServerSvcFn =
fn(
Request<Incoming>,
) -> future::Ready<Result<Response<BoxBody<Bytes, hyper::Error>>, hyper::Error>>;
#[derive(Default)]
pub(crate) struct TestServerBuilder<'a> {
// Custom server response function
svc_fn: Option<ServerSvcFn>,
// CA certificate
ca_cert: Option<&'a SelfSigned>,
// Server certificate
server_cert: Option<&'a SelfSigned>,
// Enable mTLS Verification
mutual_tls: bool,
}
impl<'a> TestServerBuilder<'a> {
pub(crate) fn new() -> Self {
Self {
svc_fn: None,
server_cert: None,
ca_cert: None,
mutual_tls: false,
}
}
#[expect(unused)]
/// Provide a custom server response function.
pub(crate) fn with_svc_fn(mut self, svc_fn: ServerSvcFn) -> Self {
self.svc_fn = Some(svc_fn);
self
}
/// Provide the server certificate. This will enable TLS (HTTPS).
pub(crate) fn with_server_cert(mut self, server_cert: &'a SelfSigned) -> Self {
self.server_cert = Some(server_cert);
self
}
/// CA certificate used to build the `RootCertStore` for client verification.
/// Requires `with_server_cert`.
pub(crate) fn with_ca_cert(mut self, ca_cert: &'a SelfSigned) -> Self {
self.ca_cert = Some(ca_cert);
self
}
/// Enforce mutual TLS (client cert auth).
/// Requires `with_server_cert` and `with_ca_cert`.
pub(crate) fn with_mutual_tls(mut self, mutual: bool) -> Self {
self.mutual_tls = mutual;
self
}
/// Starts the HTTP(S) server with optional mTLS enforcement.
pub(crate) async fn start(self) -> Result<(JoinHandle<Result<()>>, SocketAddr)> {
// Validate builder input combinations
if self.ca_cert.is_some() && self.server_cert.is_none() {
anyhow::bail!("server certificate is required when CA certificate is provided");
}
if self.mutual_tls && (self.ca_cert.is_none() || self.server_cert.is_none()) {
anyhow::bail!("ca certificate is required for mTLS");
}
// Set up the TCP listener on a random available port
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
// Setup TLS Config (if any)
let tls_acceptor = if let Some(server_cert) = self.server_cert {
// Prepare Server Cert and KeyPair
let server_key = PrivateKeyDer::try_from(server_cert.private.serialize_der()).unwrap();
let server_cert = vec![CertificateDer::from(server_cert.public.der().to_vec())];
// Setup CA Verifier
let client_verifier = if let Some(ca_cert) = self.ca_cert {
let mut root_store = RootCertStore::empty();
root_store
.add(CertificateDer::from(ca_cert.public.der().to_vec()))
.expect("failed to add CA cert");
if self.mutual_tls {
// Setup mTLS CA config
WebPkiClientVerifier::builder(root_store.into())
.build()
.expect("failed to setup client verifier")
} else {
// Only load the CA roots
WebPkiClientVerifier::builder(root_store.into())
.allow_unauthenticated()
.build()
.expect("failed to setup client verifier")
}
} else {
WebPkiClientVerifier::no_client_auth()
};
let mut tls_config = ServerConfig::builder()
.with_client_cert_verifier(client_verifier)
.with_single_cert(server_cert, server_key)?;
tls_config.alpn_protocols = vec![b"http/1.1".to_vec(), b"http/1.0".to_vec()];
Some(TlsAcceptor::from(Arc::new(tls_config)))
} else {
None
};
// Setup Response Handler
let svc_fn = if let Some(custom_svc_fn) = self.svc_fn {
custom_svc_fn
} else {
|req: Request<Incoming>| {
// Get User Agent Header and send it back in the response
let user_agent = req
.headers()
.get(USER_AGENT)
.and_then(|v| v.to_str().ok())
.map(ToString::to_string)
.unwrap_or_default(); // Empty Default
let response_content = Full::new(Bytes::from(user_agent))
.map_err(|_| unreachable!())
.boxed();
// If we ever want a true echo server, we can use instead
// let response_content = req.into_body().boxed();
// although uv-client doesn't expose post currently.
future::ok::<_, hyper::Error>(Response::new(response_content))
}
};
// Spawn the server loop in a background task
let server_task = tokio::spawn(async move {
let svc = service_fn(move |req: Request<Incoming>| svc_fn(req));
let (tcp_stream, _remote_addr) = listener
.accept()
.await
.context("Failed to accept TCP connection")?;
// Start Server (not wrapped in loop {} since we want a single response server)
// If we want server to accept multiple connections, we can wrap it in loop {}
// but we'll need to ensure to handle termination signals in the tests otherwise
// it may never stop.
if let Some(tls_acceptor) = tls_acceptor {
let tls_stream = tls_acceptor
.accept(tcp_stream)
.await
.context("Failed to accept TLS connection")?;
let socket = TokioIo::new(tls_stream);
tokio::task::spawn(async move {
Builder::new(TokioExecutor::new())
.serve_connection(socket, svc)
.await
.expect("HTTPS Server Started");
});
} else {
let socket = TokioIo::new(tcp_stream);
tokio::task::spawn(async move {
Builder::new(TokioExecutor::new())
.serve_connection(socket, svc)
.await
.expect("HTTP Server Started");
});
}
Ok(())
});
Ok((server_task, addr))
}
}
/// Single Request HTTP server that echoes the User Agent Header.
pub(crate) async fn start_http_user_agent_server() -> Result<(JoinHandle<Result<()>>, SocketAddr)> {
TestServerBuilder::new().start().await
}
/// Single Request HTTPS server that echoes the User Agent Header.
pub(crate) async fn start_https_user_agent_server(
server_cert: &SelfSigned,
) -> Result<(JoinHandle<Result<()>>, SocketAddr)> {
TestServerBuilder::new()
.with_server_cert(server_cert)
.start()
.await
}
/// Single Request HTTPS mTLS server that echoes the User Agent Header.
pub(crate) async fn start_https_mtls_user_agent_server(
ca_cert: &SelfSigned,
server_cert: &SelfSigned,
) -> Result<(JoinHandle<Result<()>>, SocketAddr)> {
TestServerBuilder::new()
.with_ca_cert(ca_cert)
.with_server_cert(server_cert)
.with_mutual_tls(true)
.start()
.await
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-client/tests/it/ssl_certs.rs | crates/uv-client/tests/it/ssl_certs.rs | use std::str::FromStr;
use anyhow::Result;
use rustls::AlertDescription;
use url::Url;
use uv_cache::Cache;
use uv_client::BaseClientBuilder;
use uv_client::RegistryClientBuilder;
use uv_redacted::DisplaySafeUrl;
use uv_static::EnvVars;
use crate::http_util::{
generate_self_signed_certs, generate_self_signed_certs_with_ca,
start_https_mtls_user_agent_server, start_https_user_agent_server, test_cert_dir,
};
// SAFETY: This test is meant to run with single thread configuration
#[tokio::test]
#[allow(unsafe_code)]
async fn ssl_env_vars() -> Result<()> {
// Ensure our environment is not polluted with anything that may affect `rustls-native-certs`
unsafe {
std::env::remove_var(EnvVars::UV_NATIVE_TLS);
std::env::remove_var(EnvVars::SSL_CERT_FILE);
std::env::remove_var(EnvVars::SSL_CERT_DIR);
std::env::remove_var(EnvVars::SSL_CLIENT_CERT);
}
// Create temporary cert dirs
let cert_dir = test_cert_dir();
fs_err::create_dir_all(&cert_dir).expect("Failed to create test cert bucket");
let cert_dir =
tempfile::TempDir::new_in(cert_dir).expect("Failed to create test cert directory");
let does_not_exist_cert_dir = cert_dir.path().join("does_not_exist");
// Generate self-signed standalone cert
let standalone_server_cert = generate_self_signed_certs()?;
let standalone_public_pem_path = cert_dir.path().join("standalone_public.pem");
let standalone_private_pem_path = cert_dir.path().join("standalone_private.pem");
// Generate self-signed CA, server, and client certs
let (ca_cert, server_cert, client_cert) = generate_self_signed_certs_with_ca()?;
let ca_public_pem_path = cert_dir.path().join("ca_public.pem");
let ca_private_pem_path = cert_dir.path().join("ca_private.pem");
let server_public_pem_path = cert_dir.path().join("server_public.pem");
let server_private_pem_path = cert_dir.path().join("server_private.pem");
let client_combined_pem_path = cert_dir.path().join("client_combined.pem");
// Persist the certs in PKCS8 format as the env vars expect a path on disk
fs_err::write(
standalone_public_pem_path.as_path(),
standalone_server_cert.public.pem(),
)?;
fs_err::write(
standalone_private_pem_path.as_path(),
standalone_server_cert.private.serialize_pem(),
)?;
fs_err::write(ca_public_pem_path.as_path(), ca_cert.public.pem())?;
fs_err::write(
ca_private_pem_path.as_path(),
ca_cert.private.serialize_pem(),
)?;
fs_err::write(server_public_pem_path.as_path(), server_cert.public.pem())?;
fs_err::write(
server_private_pem_path.as_path(),
server_cert.private.serialize_pem(),
)?;
fs_err::write(
client_combined_pem_path.as_path(),
// SSL_CLIENT_CERT expects a "combined" cert with the public and private key.
format!(
"{}\n{}",
client_cert.public.pem(),
client_cert.private.serialize_pem()
),
)?;
// ** Set SSL_CERT_FILE to non-existent location
// ** Then verify our request fails to establish a connection
unsafe {
std::env::set_var(EnvVars::SSL_CERT_FILE, does_not_exist_cert_dir.as_os_str());
}
let (server_task, addr) = start_https_user_agent_server(&standalone_server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_FILE);
}
// Validate the client error
let Some(reqwest_middleware::Error::Middleware(middleware_error)) = res.err() else {
panic!("expected middleware error");
};
let reqwest_error = middleware_error
.chain()
.find_map(|err| {
err.downcast_ref::<reqwest_middleware::Error>().map(|err| {
if let reqwest_middleware::Error::Reqwest(inner) = err {
inner
} else {
panic!("expected reqwest error")
}
})
})
.expect("expected reqwest error");
assert!(reqwest_error.is_connect());
// Validate the server error
let server_res = server_task.await?;
let expected_err = if let Err(anyhow_err) = server_res
&& let Some(io_err) = anyhow_err.downcast_ref::<std::io::Error>()
&& let Some(wrapped_err) = io_err.get_ref()
&& let Some(tls_err) = wrapped_err.downcast_ref::<rustls::Error>()
&& matches!(
tls_err,
rustls::Error::AlertReceived(AlertDescription::UnknownCA)
) {
true
} else {
false
};
assert!(expected_err);
// ** Set SSL_CERT_FILE to our public certificate
// ** Then verify our request successfully establishes a connection
unsafe {
std::env::set_var(
EnvVars::SSL_CERT_FILE,
standalone_public_pem_path.as_os_str(),
);
}
let (server_task, addr) = start_https_user_agent_server(&standalone_server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
assert!(res.is_ok());
let _ = server_task.await?; // wait for server shutdown
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_FILE);
}
// ** Set SSL_CERT_DIR to our cert dir as well as some other dir that does not exist
// ** Then verify our request still successfully establishes a connection
unsafe {
std::env::set_var(
EnvVars::SSL_CERT_DIR,
std::env::join_paths(vec![
cert_dir.path().as_os_str(),
does_not_exist_cert_dir.as_os_str(),
])?,
);
}
let (server_task, addr) = start_https_user_agent_server(&standalone_server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
assert!(res.is_ok());
let _ = server_task.await?; // wait for server shutdown
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_DIR);
}
// ** Set SSL_CERT_DIR to only the dir that does not exist
// ** Then verify our request fails to establish a connection
unsafe {
std::env::set_var(EnvVars::SSL_CERT_DIR, does_not_exist_cert_dir.as_os_str());
}
let (server_task, addr) = start_https_user_agent_server(&standalone_server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_DIR);
}
// Validate the client error
let Some(reqwest_middleware::Error::Middleware(middleware_error)) = res.err() else {
panic!("expected middleware error");
};
let reqwest_error = middleware_error
.chain()
.find_map(|err| {
err.downcast_ref::<reqwest_middleware::Error>().map(|err| {
if let reqwest_middleware::Error::Reqwest(inner) = err {
inner
} else {
panic!("expected reqwest error")
}
})
})
.expect("expected reqwest error");
assert!(reqwest_error.is_connect());
// Validate the server error
let server_res = server_task.await?;
let expected_err = if let Err(anyhow_err) = server_res
&& let Some(io_err) = anyhow_err.downcast_ref::<std::io::Error>()
&& let Some(wrapped_err) = io_err.get_ref()
&& let Some(tls_err) = wrapped_err.downcast_ref::<rustls::Error>()
&& matches!(
tls_err,
rustls::Error::AlertReceived(AlertDescription::UnknownCA)
) {
true
} else {
false
};
assert!(expected_err);
// *** mTLS Tests
// ** Set SSL_CERT_FILE to our CA and SSL_CLIENT_CERT to our client cert
// ** Then verify our request still successfully establishes a connection
// We need to set SSL_CERT_FILE or SSL_CERT_DIR to our CA as we need to tell
// our HTTP client that we trust certificates issued by our self-signed CA.
// This inherently also tests that our server cert is also validated as part
// of the certificate path validation algorithm.
unsafe {
std::env::set_var(EnvVars::SSL_CERT_FILE, ca_public_pem_path.as_os_str());
std::env::set_var(
EnvVars::SSL_CLIENT_CERT,
client_combined_pem_path.as_os_str(),
);
}
let (server_task, addr) = start_https_mtls_user_agent_server(&ca_cert, &server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
assert!(res.is_ok());
let _ = server_task.await?; // wait for server shutdown
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_FILE);
std::env::remove_var(EnvVars::SSL_CLIENT_CERT);
}
// ** Set SSL_CERT_FILE to our CA and unset SSL_CLIENT_CERT
// ** Then verify our request fails to establish a connection
unsafe {
std::env::set_var(EnvVars::SSL_CERT_FILE, ca_public_pem_path.as_os_str());
}
let (server_task, addr) = start_https_mtls_user_agent_server(&ca_cert, &server_cert).await?;
let url = DisplaySafeUrl::from_str(&format!("https://{addr}"))?;
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
let res = client
.cached_client()
.uncached()
.for_host(&url)
.get(Url::from(url))
.send()
.await;
unsafe {
std::env::remove_var(EnvVars::SSL_CERT_FILE);
}
// Validate the client error
let Some(reqwest_middleware::Error::Middleware(middleware_error)) = res.err() else {
panic!("expected middleware error");
};
let reqwest_error = middleware_error
.chain()
.find_map(|err| {
err.downcast_ref::<reqwest_middleware::Error>().map(|err| {
if let reqwest_middleware::Error::Reqwest(inner) = err {
inner
} else {
panic!("expected reqwest error")
}
})
})
.expect("expected reqwest error");
assert!(reqwest_error.is_connect());
// Validate the server error
let server_res = server_task.await?;
let expected_err = if let Err(anyhow_err) = server_res
&& let Some(io_err) = anyhow_err.downcast_ref::<std::io::Error>()
&& let Some(wrapped_err) = io_err.get_ref()
&& let Some(tls_err) = wrapped_err.downcast_ref::<rustls::Error>()
&& matches!(tls_err, rustls::Error::NoCertificatesPresented)
{
true
} else {
false
};
assert!(expected_err);
// Fin.
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-client/tests/it/remote_metadata.rs | crates/uv-client/tests/it/remote_metadata.rs | use std::str::FromStr;
use anyhow::Result;
use uv_cache::Cache;
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{BuiltDist, DirectUrlBuiltDist, IndexCapabilities};
use uv_pep508::VerbatimUrl;
use uv_redacted::DisplaySafeUrl;
#[tokio::test]
async fn remote_metadata_with_and_without_cache() -> Result<()> {
let cache = Cache::temp()?.init().await?;
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache).build();
// The first run is without cache (the tempdir is empty), the second has the cache from the
// first run.
for _ in 0..2 {
let url = "https://files.pythonhosted.org/packages/00/e5/f12a80907d0884e6dff9c16d0c0114d81b8cd07dc3ae54c5e962cc83037e/tqdm-4.66.1-py3-none-any.whl";
let filename = WheelFilename::from_str(url.rsplit_once('/').unwrap().1)?;
let dist = BuiltDist::DirectUrl(DirectUrlBuiltDist {
filename,
location: Box::new(DisplaySafeUrl::parse(url)?),
url: VerbatimUrl::from_str(url)?,
});
let capabilities = IndexCapabilities::default();
let metadata = client.wheel_metadata(&dist, &capabilities).await?;
assert_eq!(metadata.version.to_string(), "4.66.1");
}
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-frontend/src/lib.rs | crates/uv-build-frontend/src/lib.rs | //! Build wheels from source distributions.
//!
//! <https://packaging.python.org/en/latest/specifications/source-distribution-format/>
mod error;
mod pipreqs;
use std::borrow::Cow;
use std::ffi::OsString;
use std::fmt::Formatter;
use std::fmt::Write;
use std::io;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::LazyLock;
use std::{env, iter};
use fs_err as fs;
use indoc::formatdoc;
use itertools::Itertools;
use rustc_hash::FxHashMap;
use serde::de::{self, IntoDeserializer, SeqAccess, Visitor, value};
use serde::{Deserialize, Deserializer};
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::process::Command;
use tokio::sync::{Mutex, Semaphore};
use tracing::{Instrument, debug, info_span, instrument, warn};
use uv_auth::CredentialsCache;
use uv_cache_key::cache_digest;
use uv_configuration::{BuildKind, BuildOutput, SourceStrategy};
use uv_distribution::BuildRequires;
use uv_distribution_types::{
ConfigSettings, ExtraBuildRequirement, ExtraBuildRequires, IndexLocations, Requirement,
Resolution,
};
use uv_fs::{LockedFile, LockedFileMode};
use uv_fs::{PythonExt, Simplified};
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_preview::Preview;
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::{Interpreter, PythonEnvironment};
use uv_static::EnvVars;
use uv_types::{AnyErrorBuild, BuildContext, BuildIsolation, BuildStack, SourceBuildTrait};
use uv_warnings::warn_user_once;
use uv_workspace::WorkspaceCache;
pub use crate::error::{Error, MissingHeaderCause};
/// The default backend to use when PEP 517 is used without a `build-system` section.
static DEFAULT_BACKEND: LazyLock<Pep517Backend> = LazyLock::new(|| Pep517Backend {
backend: "setuptools.build_meta:__legacy__".to_string(),
backend_path: None,
requirements: vec![Requirement::from(
uv_pep508::Requirement::from_str("setuptools >= 40.8.0").unwrap(),
)],
});
/// A `pyproject.toml` as specified in PEP 517.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct PyProjectToml {
/// Build-related data
build_system: Option<BuildSystem>,
/// Project metadata
project: Option<Project>,
/// Tool configuration
tool: Option<Tool>,
}
/// The `[project]` section of a pyproject.toml as specified in PEP 621.
///
/// This representation only includes a subset of the fields defined in PEP 621 necessary for
/// informing wheel builds.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct Project {
/// The name of the project
name: PackageName,
/// The version of the project as supported by PEP 440
version: Option<Version>,
/// Specifies which fields listed by PEP 621 were intentionally unspecified so another tool
/// can/will provide such metadata dynamically.
dynamic: Option<Vec<String>>,
}
/// The `[build-system]` section of a pyproject.toml as specified in PEP 517.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct BuildSystem {
/// PEP 508 dependencies required to execute the build system.
requires: Vec<uv_pep508::Requirement<VerbatimParsedUrl>>,
/// A string naming a Python object that will be used to perform the build.
build_backend: Option<String>,
/// Specify that their backend code is hosted in-tree, this key contains a list of directories.
backend_path: Option<BackendPath>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct Tool {
uv: Option<ToolUv>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct ToolUv {
workspace: Option<de::IgnoredAny>,
}
impl BackendPath {
/// Return an iterator over the paths in the backend path.
fn iter(&self) -> impl Iterator<Item = &str> {
self.0.iter().map(String::as_str)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct BackendPath(Vec<String>);
impl<'de> Deserialize<'de> for BackendPath {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct StringOrVec;
impl<'de> Visitor<'de> for StringOrVec {
type Value = Vec<String>;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("list of strings")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
// Allow exactly `backend-path = "."`, as used in `flit_core==2.3.0`.
if s == "." {
Ok(vec![".".to_string()])
} else {
Err(de::Error::invalid_value(de::Unexpected::Str(s), &self))
}
}
fn visit_seq<S>(self, seq: S) -> Result<Self::Value, S::Error>
where
S: SeqAccess<'de>,
{
Deserialize::deserialize(value::SeqAccessDeserializer::new(seq))
}
}
deserializer.deserialize_any(StringOrVec).map(BackendPath)
}
}
/// `[build-backend]` from pyproject.toml
#[derive(Debug, Clone, PartialEq, Eq)]
struct Pep517Backend {
/// The build backend string such as `setuptools.build_meta:__legacy__` or `maturin` from
/// `build-backend.backend` in pyproject.toml
///
/// <https://peps.python.org/pep-0517/#build-wheel>
backend: String,
/// `build-backend.requirements` in pyproject.toml
requirements: Vec<Requirement>,
/// <https://peps.python.org/pep-0517/#in-tree-build-backends>
backend_path: Option<BackendPath>,
}
impl Pep517Backend {
fn backend_import(&self) -> String {
let import = if let Some((path, object)) = self.backend.split_once(':') {
format!("from {path} import {object} as backend")
} else {
format!("import {} as backend", self.backend)
};
let backend_path_encoded = self
.backend_path
.iter()
.flat_map(BackendPath::iter)
.map(|path| {
// Turn into properly escaped python string
'"'.to_string()
+ &path.replace('\\', "\\\\").replace('"', "\\\"")
+ &'"'.to_string()
})
.join(", ");
// > Projects can specify that their backend code is hosted in-tree by including the
// > backend-path key in pyproject.toml. This key contains a list of directories, which the
// > frontend will add to the start of sys.path when loading the backend, and running the
// > backend hooks.
formatdoc! {r#"
import sys
if sys.path[0] == "":
sys.path.pop(0)
sys.path = [{backend_path}] + sys.path
{import}
"#, backend_path = backend_path_encoded}
}
fn is_setuptools(&self) -> bool {
// either `setuptools.build_meta` or `setuptools.build_meta:__legacy__`
self.backend.split(':').next() == Some("setuptools.build_meta")
}
}
/// Uses an [`Rc`] internally, clone freely.
#[derive(Debug, Default, Clone)]
pub struct SourceBuildContext {
/// An in-memory resolution of the default backend's requirements for PEP 517 builds.
default_resolution: Rc<Mutex<Option<Resolution>>>,
}
/// Holds the state through a series of PEP 517 frontend to backend calls or a single `setup.py`
/// invocation.
///
/// This keeps both the temp dir and the result of a potential `prepare_metadata_for_build_wheel`
/// call which changes how we call `build_wheel`.
pub struct SourceBuild {
temp_dir: TempDir,
source_tree: PathBuf,
config_settings: ConfigSettings,
/// If performing a PEP 517 build, the backend to use.
pep517_backend: Pep517Backend,
/// The PEP 621 project metadata, if any.
project: Option<Project>,
/// The virtual environment in which to build the source distribution.
venv: PythonEnvironment,
/// Populated if `prepare_metadata_for_build_wheel` was called.
///
/// > If the build frontend has previously called `prepare_metadata_for_build_wheel` and depends
/// > on the wheel resulting from this call to have metadata matching this earlier call, then
/// > it should provide the path to the created .dist-info directory as the `metadata_directory`
/// > argument. If this argument is provided, then `build_wheel` MUST produce a wheel with
/// > identical metadata. The directory passed in by the build frontend MUST be identical to the
/// > directory created by `prepare_metadata_for_build_wheel`, including any unrecognized files
/// > it created.
metadata_directory: Option<PathBuf>,
/// The name of the package, if known.
package_name: Option<PackageName>,
/// The version of the package, if known.
package_version: Option<Version>,
/// Distribution identifier, e.g., `foo-1.2.3`. Used for error reporting if the name and
/// version are unknown.
version_id: Option<String>,
/// Whether we do a regular PEP 517 build or an PEP 660 editable build
build_kind: BuildKind,
/// Whether to send build output to `stderr` or `tracing`, etc.
level: BuildOutput,
/// Modified PATH that contains the `venv_bin`, `user_path` and `system_path` variables in that order
modified_path: OsString,
/// Environment variables to be passed in during metadata or wheel building
environment_variables: FxHashMap<OsString, OsString>,
/// Runner for Python scripts.
runner: PythonRunner,
}
impl SourceBuild {
/// Create a virtual environment in which to build a source distribution, extracting the
/// contents from an archive if necessary.
///
/// `source_dist` is for error reporting only.
pub async fn setup(
source: &Path,
subdirectory: Option<&Path>,
install_path: &Path,
fallback_package_name: Option<&PackageName>,
fallback_package_version: Option<&Version>,
interpreter: &Interpreter,
build_context: &impl BuildContext,
source_build_context: SourceBuildContext,
version_id: Option<&str>,
locations: &IndexLocations,
source_strategy: SourceStrategy,
workspace_cache: &WorkspaceCache,
config_settings: ConfigSettings,
build_isolation: BuildIsolation<'_>,
extra_build_requires: &ExtraBuildRequires,
build_stack: &BuildStack,
build_kind: BuildKind,
mut environment_variables: FxHashMap<OsString, OsString>,
level: BuildOutput,
concurrent_builds: usize,
credentials_cache: &CredentialsCache,
preview: Preview,
) -> Result<Self, Error> {
let temp_dir = build_context.cache().venv_dir()?;
let source_tree = if let Some(subdir) = subdirectory {
source.join(subdir)
} else {
source.to_path_buf()
};
// Check if we have a PEP 517 build backend.
let (pep517_backend, project) = Self::extract_pep517_backend(
&source_tree,
install_path,
fallback_package_name,
locations,
source_strategy,
workspace_cache,
credentials_cache,
)
.await
.map_err(|err| *err)?;
let package_name = project
.as_ref()
.map(|project| &project.name)
.or(fallback_package_name)
.cloned();
let package_version = project
.as_ref()
.and_then(|project| project.version.as_ref())
.or(fallback_package_version)
.cloned();
let extra_build_dependencies = package_name
.as_ref()
.and_then(|name| extra_build_requires.get(name).cloned())
.unwrap_or_default()
.into_iter()
.map(|requirement| {
match requirement {
ExtraBuildRequirement {
requirement,
match_runtime: true,
} if requirement.source.is_empty() => {
Err(Error::UnmatchedRuntime(
requirement.name.clone(),
// SAFETY: if `package_name` is `None`, the iterator is empty.
package_name.clone().unwrap(),
))
}
requirement => Ok(requirement),
}
})
.map_ok(Requirement::from)
.collect::<Result<Vec<_>, _>>()?;
// Create a virtual environment, or install into the shared environment if requested.
let venv = if let Some(venv) = build_isolation.shared_environment(package_name.as_ref()) {
venv.clone()
} else {
uv_virtualenv::create_venv(
temp_dir.path(),
interpreter.clone(),
uv_virtualenv::Prompt::None,
false,
uv_virtualenv::OnExisting::Remove(
uv_virtualenv::RemovalReason::TemporaryEnvironment,
),
false,
false,
false,
preview,
)?
};
// Set up the build environment. If build isolation is disabled, we assume the build
// environment is already setup.
if build_isolation.is_isolated(package_name.as_ref()) {
debug!("Resolving build requirements");
let dependency_sources = if extra_build_dependencies.is_empty() {
"`build-system.requires`"
} else {
"`build-system.requires` and `extra-build-dependencies`"
};
let resolved_requirements = Self::get_resolved_requirements(
build_context,
source_build_context,
&pep517_backend,
extra_build_dependencies,
build_stack,
)
.await?;
build_context
.install(&resolved_requirements, &venv, build_stack)
.await
.map_err(|err| Error::RequirementsInstall(dependency_sources, err.into()))?;
} else {
debug!("Proceeding without build isolation");
}
// Figure out what the modified path should be, and remove the PATH variable from the
// environment variables if it's there.
let user_path = environment_variables.remove(&OsString::from(EnvVars::PATH));
// See if there is an OS PATH variable.
let os_path = env::var_os(EnvVars::PATH);
// Prepend the user supplied PATH to the existing OS PATH
let modified_path = if let Some(user_path) = user_path {
match os_path {
// Prepend the user supplied PATH to the existing PATH
Some(env_path) => {
let user_path = PathBuf::from(user_path);
let new_path = env::split_paths(&user_path).chain(env::split_paths(&env_path));
Some(env::join_paths(new_path).map_err(Error::BuildScriptPath)?)
}
// Use the user supplied PATH
None => Some(user_path),
}
} else {
os_path
};
// Prepend the venv bin directory to the modified path
let modified_path = if let Some(path) = modified_path {
let venv_path = iter::once(venv.scripts().to_path_buf()).chain(env::split_paths(&path));
env::join_paths(venv_path).map_err(Error::BuildScriptPath)?
} else {
OsString::from(venv.scripts())
};
// Create the PEP 517 build environment. If build isolation is disabled, we assume the build
// environment is already setup.
let runner = PythonRunner::new(concurrent_builds, level);
if build_isolation.is_isolated(package_name.as_ref()) {
debug!("Creating PEP 517 build environment");
create_pep517_build_environment(
&runner,
&source_tree,
install_path,
&venv,
&pep517_backend,
build_context,
package_name.as_ref(),
package_version.as_ref(),
version_id,
locations,
source_strategy,
workspace_cache,
build_stack,
build_kind,
level,
&config_settings,
&environment_variables,
&modified_path,
&temp_dir,
credentials_cache,
)
.await?;
}
Ok(Self {
temp_dir,
source_tree,
pep517_backend,
project,
venv,
build_kind,
level,
config_settings,
metadata_directory: None,
package_name,
package_version,
version_id: version_id.map(ToString::to_string),
environment_variables,
modified_path,
runner,
})
}
/// Acquire a lock on the source tree, if necessary.
async fn acquire_lock(&self) -> Result<Option<LockedFile>, Error> {
// Depending on the command, setuptools puts `*.egg-info`, `build/`, and `dist/` in the
// source tree, and concurrent invocations of setuptools using the same source dir can
// stomp on each other. We need to lock something to fix that, but we don't want to dump a
// `.lock` file into the source tree that the user will need to .gitignore. Take a global
// proxy lock instead.
let mut source_tree_lock = None;
if self.pep517_backend.is_setuptools() {
debug!("Locking the source tree for setuptools");
let canonical_source_path = self.source_tree.canonicalize()?;
let lock_path = env::temp_dir().join(format!(
"uv-setuptools-{}.lock",
cache_digest(&canonical_source_path)
));
source_tree_lock = LockedFile::acquire(
lock_path,
LockedFileMode::Exclusive,
self.source_tree.to_string_lossy(),
)
.await
.inspect_err(|err| {
warn!("Failed to acquire build lock: {err}");
})
.ok();
}
Ok(source_tree_lock)
}
async fn get_resolved_requirements(
build_context: &impl BuildContext,
source_build_context: SourceBuildContext,
pep517_backend: &Pep517Backend,
extra_build_dependencies: Vec<Requirement>,
build_stack: &BuildStack,
) -> Result<Resolution, Error> {
Ok(
if pep517_backend.requirements == DEFAULT_BACKEND.requirements
&& extra_build_dependencies.is_empty()
{
let mut resolution = source_build_context.default_resolution.lock().await;
if let Some(resolved_requirements) = &*resolution {
resolved_requirements.clone()
} else {
let resolved_requirements = build_context
.resolve(&DEFAULT_BACKEND.requirements, build_stack)
.await
.map_err(|err| {
Error::RequirementsResolve("`setup.py` build", err.into())
})?;
*resolution = Some(resolved_requirements.clone());
resolved_requirements
}
} else {
let (requirements, dependency_sources) = if extra_build_dependencies.is_empty() {
(
Cow::Borrowed(&pep517_backend.requirements),
"`build-system.requires`",
)
} else {
// If there are extra build dependencies, we need to resolve them together with
// the backend requirements.
let mut requirements = pep517_backend.requirements.clone();
requirements.extend(extra_build_dependencies);
(
Cow::Owned(requirements),
"`build-system.requires` and `extra-build-dependencies`",
)
};
build_context
.resolve(&requirements, build_stack)
.await
.map_err(|err| Error::RequirementsResolve(dependency_sources, err.into()))?
},
)
}
/// Extract the PEP 517 backend from the `pyproject.toml` or `setup.py` file.
async fn extract_pep517_backend(
source_tree: &Path,
install_path: &Path,
package_name: Option<&PackageName>,
locations: &IndexLocations,
source_strategy: SourceStrategy,
workspace_cache: &WorkspaceCache,
credentials_cache: &CredentialsCache,
) -> Result<(Pep517Backend, Option<Project>), Box<Error>> {
match fs::read_to_string(source_tree.join("pyproject.toml")) {
Ok(toml) => {
let pyproject_toml = toml_edit::Document::from_str(&toml)
.map_err(Error::InvalidPyprojectTomlSyntax)?;
let pyproject_toml = PyProjectToml::deserialize(pyproject_toml.into_deserializer())
.map_err(Error::InvalidPyprojectTomlSchema)?;
let backend = if let Some(build_system) = pyproject_toml.build_system {
// If necessary, lower the requirements.
let requirements = match source_strategy {
SourceStrategy::Enabled => {
if let Some(name) = pyproject_toml
.project
.as_ref()
.map(|project| &project.name)
.or(package_name)
{
let build_requires = uv_pypi_types::BuildRequires {
name: Some(name.clone()),
requires_dist: build_system.requires,
};
let build_requires = BuildRequires::from_project_maybe_workspace(
build_requires,
install_path,
locations,
source_strategy,
workspace_cache,
credentials_cache,
)
.await
.map_err(Error::Lowering)?;
build_requires.requires_dist
} else {
build_system
.requires
.into_iter()
.map(Requirement::from)
.collect()
}
}
SourceStrategy::Disabled => build_system
.requires
.into_iter()
.map(Requirement::from)
.collect(),
};
Pep517Backend {
// If `build-backend` is missing, inject the legacy setuptools backend, but
// retain the `requires`, to match `pip` and `build`. Note that while PEP 517
// says that in this case we "should revert to the legacy behaviour of running
// `setup.py` (either directly, or by implicitly invoking the
// `setuptools.build_meta:__legacy__` backend)", we found that in practice, only
// the legacy setuptools backend is allowed. See also:
// https://github.com/pypa/build/blob/de5b44b0c28c598524832dff685a98d5a5148c44/src/build/__init__.py#L114-L118
backend: build_system
.build_backend
.unwrap_or_else(|| "setuptools.build_meta:__legacy__".to_string()),
backend_path: build_system.backend_path,
requirements,
}
} else {
// If a `pyproject.toml` is present, but `[build-system]` is missing, proceed
// with a PEP 517 build using the default backend (`setuptools`), to match `pip`
// and `build`.
//
// If there is no build system defined and there is no metadata source for
// `setuptools`, warn. The build will succeed, but the metadata will be
// incomplete (for example, the package name will be `UNKNOWN`).
if pyproject_toml.project.is_none()
&& !source_tree.join("setup.py").is_file()
&& !source_tree.join("setup.cfg").is_file()
{
// Give a specific hint for `uv pip install .` in a workspace root.
let looks_like_workspace_root = pyproject_toml
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|tool| tool.workspace.as_ref())
.is_some();
if looks_like_workspace_root {
warn_user_once!(
"`{}` appears to be a workspace root without a Python project; \
consider using `uv sync` to install the workspace, or add a \
`[build-system]` table to `pyproject.toml`",
source_tree.simplified_display().cyan(),
);
} else {
warn_user_once!(
"`{}` does not appear to be a Python project, as the `pyproject.toml` \
does not include a `[build-system]` table, and neither `setup.py` \
nor `setup.cfg` are present in the directory",
source_tree.simplified_display().cyan(),
);
}
}
DEFAULT_BACKEND.clone()
};
Ok((backend, pyproject_toml.project))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => {
// We require either a `pyproject.toml` or a `setup.py` file at the top level.
if !source_tree.join("setup.py").is_file() {
return Err(Box::new(Error::InvalidSourceDist(
source_tree.to_path_buf(),
)));
}
// If no `pyproject.toml` is present, by default, proceed with a PEP 517 build using
// the default backend, to match `build`. `pip` uses `setup.py` directly in this
// case, but plans to make PEP 517 builds the default in the future.
// See: https://github.com/pypa/pip/issues/9175.
Ok((DEFAULT_BACKEND.clone(), None))
}
Err(err) => Err(Box::new(err.into())),
}
}
/// Try calling `prepare_metadata_for_build_wheel` to get the metadata without executing the
/// actual build.
pub async fn get_metadata_without_build(&mut self) -> Result<Option<PathBuf>, Error> {
// We've already called this method; return the existing result.
if let Some(metadata_dir) = &self.metadata_directory {
return Ok(Some(metadata_dir.clone()));
}
// Lock the source tree, if necessary.
let _lock = self.acquire_lock().await?;
// Hatch allows for highly dynamic customization of metadata via hooks. In such cases, Hatch
// can't uphold the PEP 517 contract, in that the metadata Hatch would return by
// `prepare_metadata_for_build_wheel` isn't guaranteed to match that of the built wheel.
//
// Hatch disables `prepare_metadata_for_build_wheel` entirely for pip. We'll instead disable
// it on our end when metadata is defined as "dynamic" in the pyproject.toml, which should
// allow us to leverage the hook in _most_ cases while still avoiding incorrect metadata for
// the remaining cases.
//
// This heuristic will have false positives (i.e., there will be some Hatch projects for
// which we could have safely called `prepare_metadata_for_build_wheel`, despite having
// dynamic metadata). However, false positives are preferable to false negatives, since
// this is just an optimization.
//
// See: https://github.com/astral-sh/uv/issues/2130
if self.pep517_backend.backend == "hatchling.build" {
if self
.project
.as_ref()
.and_then(|project| project.dynamic.as_ref())
.is_some_and(|dynamic| {
dynamic
.iter()
.any(|field| field == "dependencies" || field == "optional-dependencies")
})
{
return Ok(None);
}
}
let metadata_directory = self.temp_dir.path().join("metadata_directory");
fs::create_dir(&metadata_directory)?;
// Write the hook output to a file so that we can read it back reliably.
let outfile = self.temp_dir.path().join(format!(
"prepare_metadata_for_build_{}.txt",
self.build_kind
));
debug!(
"Calling `{}.prepare_metadata_for_build_{}()`",
self.pep517_backend.backend, self.build_kind,
);
let script = formatdoc! {
r#"
{}
import json
prepare_metadata_for_build = getattr(backend, "prepare_metadata_for_build_{}", None)
if prepare_metadata_for_build:
dirname = prepare_metadata_for_build("{}", {})
else:
dirname = None
with open("{}", "w") as fp:
fp.write(dirname or "")
"#,
self.pep517_backend.backend_import(),
self.build_kind,
escape_path_for_python(&metadata_directory),
self.config_settings.escape_for_python(),
outfile.escape_for_python(),
};
let span = info_span!(
"run_python_script",
script = format!("prepare_metadata_for_build_{}", self.build_kind),
version_id = self.version_id,
);
let output = self
.runner
.run_script(
&self.venv,
&script,
&self.source_tree,
&self.environment_variables,
&self.modified_path,
)
.instrument(span)
.await?;
if !output.status.success() {
return Err(Error::from_command_output(
format!(
"Call to `{}.prepare_metadata_for_build_{}` failed",
self.pep517_backend.backend, self.build_kind
),
&output,
self.level,
self.package_name.as_ref(),
self.package_version.as_ref(),
self.version_id.as_deref(),
));
}
let dirname = fs::read_to_string(&outfile)?;
if dirname.is_empty() {
return Ok(None);
}
self.metadata_directory = Some(metadata_directory.join(dirname));
Ok(self.metadata_directory.clone())
}
/// Build a distribution from an archive (`.zip` or `.tar.gz`) or source tree, and return the
/// location of the built distribution.
///
/// The location will be inside `temp_dir`, i.e., you must use the distribution before dropping
/// the temporary directory.
///
/// <https://packaging.python.org/en/latest/specifications/source-distribution-format/>
#[instrument(skip_all, fields(version_id = self.version_id))]
| 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-frontend/src/pipreqs.rs | crates/uv-build-frontend/src/pipreqs.rs | use std::str::FromStr;
use std::sync::LazyLock;
use rustc_hash::FxHashMap;
use uv_normalize::PackageName;
/// A mapping from module name to PyPI package name.
pub(crate) struct ModuleMap<'a>(FxHashMap<&'a str, PackageName>);
impl<'a> ModuleMap<'a> {
/// Generate a [`ModuleMap`] from a string representation, encoded in `${module}:{package}` format.
fn from_str(source: &'a str) -> Self {
let mut mapping = FxHashMap::default();
for line in source.lines() {
if let Some((module, package)) = line.split_once(':') {
let module = module.trim();
let package = PackageName::from_str(package.trim()).unwrap();
mapping.insert(module, package);
}
}
Self(mapping)
}
/// Look up a PyPI package name for a given module name.
pub(crate) fn lookup(&self, module: &str) -> Option<&PackageName> {
self.0.get(module)
}
}
/// A mapping from module name to PyPI package name.
pub(crate) static MODULE_MAPPING: LazyLock<ModuleMap> =
LazyLock::new(|| ModuleMap::from_str(include_str!("pipreqs/mapping")));
| 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-frontend/src/error.rs | crates/uv-build-frontend/src/error.rs | use std::env;
use std::fmt::{Display, Formatter};
use std::io;
use std::path::PathBuf;
use std::process::ExitStatus;
use std::sync::LazyLock;
use crate::PythonRunnerOutput;
use owo_colors::OwoColorize;
use regex::Regex;
use thiserror::Error;
use tracing::error;
use uv_configuration::BuildOutput;
use uv_distribution_types::IsBuildBackendError;
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_types::AnyErrorBuild;
/// e.g. `pygraphviz/graphviz_wrap.c:3020:10: fatal error: graphviz/cgraph.h: No such file or directory`
static MISSING_HEADER_RE_GCC: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r".*\.(?:c|c..|h|h..):\d+:\d+: fatal error: (.*\.(?:h|h..)): No such file or directory",
)
.unwrap()
});
/// e.g. `pygraphviz/graphviz_wrap.c:3023:10: fatal error: 'graphviz/cgraph.h' file not found`
static MISSING_HEADER_RE_CLANG: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r".*\.(?:c|c..|h|h..):\d+:\d+: fatal error: '(.*\.(?:h|h..))' file not found")
.unwrap()
});
/// e.g. `pygraphviz/graphviz_wrap.c(3023): fatal error C1083: Cannot open include file: 'graphviz/cgraph.h': No such file or directory`
static MISSING_HEADER_RE_MSVC: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r".*\.(?:c|c..|h|h..)\(\d+\): fatal error C1083: Cannot open include file: '(.*\.(?:h|h..))': No such file or directory")
.unwrap()
});
/// e.g. `/usr/bin/ld: cannot find -lncurses: No such file or directory`
static LD_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"/usr/bin/ld: cannot find -l([a-zA-Z10-9]+): No such file or directory").unwrap()
});
/// e.g. `error: invalid command 'bdist_wheel'`
static WHEEL_NOT_FOUND_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"error: invalid command 'bdist_wheel'").unwrap());
/// e.g. `ModuleNotFoundError`
static MODULE_NOT_FOUND: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("ModuleNotFoundError: No module named ['\"]([^'\"]+)['\"]").unwrap()
});
/// e.g. `ModuleNotFoundError: No module named 'distutils'`
static DISTUTILS_NOT_FOUND_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"ModuleNotFoundError: No module named 'distutils'").unwrap());
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Lowering(#[from] uv_distribution::MetadataError),
#[error("{} does not appear to be a Python project, as neither `pyproject.toml` nor `setup.py` are present in the directory", _0.simplified_display())]
InvalidSourceDist(PathBuf),
#[error("Invalid `pyproject.toml`")]
InvalidPyprojectTomlSyntax(#[from] toml_edit::TomlError),
#[error(
"`pyproject.toml` does not match the required schema. When the `[project]` table is present, `project.name` must be present and non-empty."
)]
InvalidPyprojectTomlSchema(#[from] toml_edit::de::Error),
#[error("Failed to resolve requirements from {0}")]
RequirementsResolve(&'static str, #[source] AnyErrorBuild),
#[error("Failed to install requirements from {0}")]
RequirementsInstall(&'static str, #[source] AnyErrorBuild),
#[error("Failed to create temporary virtualenv")]
Virtualenv(#[from] uv_virtualenv::Error),
// Build backend errors
#[error("Failed to run `{0}`")]
CommandFailed(PathBuf, #[source] io::Error),
#[error("The build backend returned an error")]
BuildBackend(#[from] BuildBackendError),
#[error("The build backend returned an error")]
MissingHeader(#[from] MissingHeaderError),
#[error("Failed to build PATH for build script")]
BuildScriptPath(#[source] env::JoinPathsError),
// For the convenience of typing `setup_build` properly.
#[error("Building source distributions for `{0}` is disabled")]
NoSourceDistBuild(PackageName),
#[error("Building source distributions is disabled")]
NoSourceDistBuilds,
#[error("Cyclic build dependency detected for `{0}`")]
CyclicBuildDependency(PackageName),
#[error(
"Extra build requirement `{0}` was declared with `match-runtime = true`, but `{1}` does not declare static metadata, making runtime-matching impossible"
)]
UnmatchedRuntime(PackageName, PackageName),
}
impl IsBuildBackendError for Error {
fn is_build_backend_error(&self) -> bool {
match self {
Self::Io(_)
| Self::Lowering(_)
| Self::InvalidSourceDist(_)
| Self::InvalidPyprojectTomlSyntax(_)
| Self::InvalidPyprojectTomlSchema(_)
| Self::RequirementsResolve(_, _)
| Self::RequirementsInstall(_, _)
| Self::Virtualenv(_)
| Self::NoSourceDistBuild(_)
| Self::NoSourceDistBuilds
| Self::CyclicBuildDependency(_)
| Self::UnmatchedRuntime(_, _) => false,
Self::CommandFailed(_, _)
| Self::BuildBackend(_)
| Self::MissingHeader(_)
| Self::BuildScriptPath(_) => true,
}
}
}
#[derive(Debug)]
enum MissingLibrary {
Header(String),
Linker(String),
BuildDependency(String),
DeprecatedModule(String, Version),
}
#[derive(Debug, Error)]
pub struct MissingHeaderCause {
missing_library: MissingLibrary,
package_name: Option<PackageName>,
package_version: Option<Version>,
version_id: Option<String>,
}
/// Extract the package name from a version specifier string.
/// Uses PEP 508 naming rules but more lenient for hinting purposes.
fn extract_package_name(version_id: &str) -> &str {
// https://peps.python.org/pep-0508/#names
// ^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$ with re.IGNORECASE
// Since we're only using this for a hint, we're more lenient than what we would be doing if this was used for parsing
let end = version_id
.char_indices()
.take_while(|(_, char)| matches!(char, 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_'))
.last()
.map_or(0, |(i, c)| i + c.len_utf8());
if end == 0 {
version_id
} else {
&version_id[..end]
}
}
/// Write a hint about missing build dependencies.
fn hint_build_dependency(
f: &mut std::fmt::Formatter<'_>,
display_name: &str,
package_name: &str,
package: &str,
) -> std::fmt::Result {
let table_key = if package_name.contains('.') {
format!("\"{package_name}\"")
} else {
package_name.to_string()
};
write!(
f,
"This error likely indicates that `{}` depends on `{}`, but doesn't declare it as a build dependency. \
If `{}` is a first-party package, consider adding `{}` to its `{}`. \
Otherwise, either add it to your `pyproject.toml` under:\n\
\n\
[tool.uv.extra-build-dependencies]\n\
{} = [\"{}\"]\n\
\n\
or `{}` into the environment and re-run with `{}`.",
display_name.cyan(),
package.cyan(),
package_name.cyan(),
package.cyan(),
"build-system.requires".green(),
table_key.cyan(),
package.cyan(),
format!("uv pip install {package}").green(),
"--no-build-isolation".green(),
)
}
impl Display for MissingHeaderCause {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.missing_library {
MissingLibrary::Header(header) => {
if let (Some(package_name), Some(package_version)) =
(&self.package_name, &self.package_version)
{
write!(
f,
"This error likely indicates that you need to install a library that provides \"{}\" for `{}`",
header.cyan(),
format!("{package_name}@{package_version}").cyan(),
)
} else if let Some(version_id) = &self.version_id {
write!(
f,
"This error likely indicates that you need to install a library that provides \"{}\" for `{}`",
header.cyan(),
version_id.cyan(),
)
} else {
write!(
f,
"This error likely indicates that you need to install a library that provides \"{}\"",
header.cyan(),
)
}
}
MissingLibrary::Linker(library) => {
if let (Some(package_name), Some(package_version)) =
(&self.package_name, &self.package_version)
{
write!(
f,
"This error likely indicates that you need to install the library that provides a shared library for `{}` for `{}` (e.g., `{}`)",
library.cyan(),
format!("{package_name}@{package_version}").cyan(),
format!("lib{library}-dev").cyan(),
)
} else if let Some(version_id) = &self.version_id {
write!(
f,
"This error likely indicates that you need to install the library that provides a shared library for `{}` for `{}` (e.g., `{}`)",
library.cyan(),
version_id.cyan(),
format!("lib{library}-dev").cyan(),
)
} else {
write!(
f,
"This error likely indicates that you need to install the library that provides a shared library for `{}` (e.g., `{}`)",
library.cyan(),
format!("lib{library}-dev").cyan(),
)
}
}
MissingLibrary::BuildDependency(package) => {
if let (Some(package_name), Some(package_version)) =
(&self.package_name, &self.package_version)
{
hint_build_dependency(
f,
&format!("{package_name}@{package_version}"),
package_name.as_str(),
package,
)
} else if let Some(version_id) = &self.version_id {
let package_name = extract_package_name(version_id);
hint_build_dependency(f, package_name, package_name, package)
} else {
write!(
f,
"This error likely indicates that a package depends on `{}`, but doesn't declare it as a build dependency. If the package is a first-party package, consider adding `{}` to its `{}`. Otherwise, `{}` into the environment and re-run with `{}`.",
package.cyan(),
package.cyan(),
"build-system.requires".green(),
format!("uv pip install {package}").green(),
"--no-build-isolation".green(),
)
}
}
MissingLibrary::DeprecatedModule(package, version) => {
if let (Some(package_name), Some(package_version)) =
(&self.package_name, &self.package_version)
{
write!(
f,
"`{}` was removed from the standard library in Python {version}. Consider adding a constraint (like `{}`) to avoid building a version of `{}` that depends on `{}`.",
package.cyan(),
format!("{package_name} >{package_version}").green(),
package_name.cyan(),
package.cyan(),
)
} else {
write!(
f,
"`{}` was removed from the standard library in Python {version}. Consider adding a constraint to avoid building a package that depends on `{}`.",
package.cyan(),
package.cyan(),
)
}
}
}
}
}
#[derive(Debug, Error)]
pub struct BuildBackendError {
message: String,
exit_code: ExitStatus,
stdout: Vec<String>,
stderr: Vec<String>,
}
impl Display for BuildBackendError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.message, self.exit_code)?;
let mut non_empty = false;
if self.stdout.iter().any(|line| !line.trim().is_empty()) {
write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout.join("\n"))?;
non_empty = true;
}
if self.stderr.iter().any(|line| !line.trim().is_empty()) {
write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr.join("\n"))?;
non_empty = true;
}
if non_empty {
writeln!(f)?;
}
write!(
f,
"\n{}{} This usually indicates a problem with the package or the build environment.",
"hint".bold().cyan(),
":".bold()
)?;
Ok(())
}
}
#[derive(Debug, Error)]
pub struct MissingHeaderError {
message: String,
exit_code: ExitStatus,
stdout: Vec<String>,
stderr: Vec<String>,
cause: MissingHeaderCause,
}
impl Display for MissingHeaderError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.message, self.exit_code)?;
if self.stdout.iter().any(|line| !line.trim().is_empty()) {
write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout.join("\n"))?;
}
if self.stderr.iter().any(|line| !line.trim().is_empty()) {
write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr.join("\n"))?;
}
write!(
f,
"\n\n{}{} {}",
"hint".bold().cyan(),
":".bold(),
self.cause
)?;
Ok(())
}
}
impl Error {
/// Construct an [`Error`] from the output of a failed command.
pub(crate) fn from_command_output(
message: String,
output: &PythonRunnerOutput,
level: BuildOutput,
name: Option<&PackageName>,
version: Option<&Version>,
version_id: Option<&str>,
) -> Self {
// In the cases I've seen it was the 5th and 3rd last line (see test case), 10 seems like a reasonable cutoff.
let missing_library = output.stderr.iter().rev().take(10).find_map(|line| {
if let Some((_, [header])) = MISSING_HEADER_RE_GCC
.captures(line.trim())
.or(MISSING_HEADER_RE_CLANG.captures(line.trim()))
.or(MISSING_HEADER_RE_MSVC.captures(line.trim()))
.map(|c| c.extract())
{
Some(MissingLibrary::Header(header.to_string()))
} else if let Some((_, [library])) =
LD_NOT_FOUND_RE.captures(line.trim()).map(|c| c.extract())
{
Some(MissingLibrary::Linker(library.to_string()))
} else if WHEEL_NOT_FOUND_RE.is_match(line.trim()) {
Some(MissingLibrary::BuildDependency("wheel".to_string()))
} else if DISTUTILS_NOT_FOUND_RE.is_match(line.trim()) {
Some(MissingLibrary::DeprecatedModule(
"distutils".to_string(),
Version::new([3, 12]),
))
} else if let Some(caps) = MODULE_NOT_FOUND.captures(line.trim()) {
if let Some(module_match) = caps.get(1) {
let module_name = module_match.as_str();
let package_name = match crate::pipreqs::MODULE_MAPPING.lookup(module_name) {
Some(package) => package.to_string(),
None => module_name.to_string(),
};
Some(MissingLibrary::BuildDependency(package_name))
} else {
None
}
} else {
None
}
});
if let Some(missing_library) = missing_library {
return match level {
BuildOutput::Stderr | BuildOutput::Quiet => {
Self::MissingHeader(MissingHeaderError {
message,
exit_code: output.status,
stdout: vec![],
stderr: vec![],
cause: MissingHeaderCause {
missing_library,
package_name: name.cloned(),
package_version: version.cloned(),
version_id: version_id.map(ToString::to_string),
},
})
}
BuildOutput::Debug => Self::MissingHeader(MissingHeaderError {
message,
exit_code: output.status,
stdout: output.stdout.clone(),
stderr: output.stderr.clone(),
cause: MissingHeaderCause {
missing_library,
package_name: name.cloned(),
package_version: version.cloned(),
version_id: version_id.map(ToString::to_string),
},
}),
};
}
match level {
BuildOutput::Stderr | BuildOutput::Quiet => Self::BuildBackend(BuildBackendError {
message,
exit_code: output.status,
stdout: vec![],
stderr: vec![],
}),
BuildOutput::Debug => Self::BuildBackend(BuildBackendError {
message,
exit_code: output.status,
stdout: output.stdout.clone(),
stderr: output.stderr.clone(),
}),
}
}
}
#[cfg(test)]
mod test {
use crate::{Error, PythonRunnerOutput};
use indoc::indoc;
use std::process::ExitStatus;
use std::str::FromStr;
use uv_configuration::BuildOutput;
use uv_normalize::PackageName;
use uv_pep440::Version;
#[test]
fn missing_header() {
let output = PythonRunnerOutput {
status: ExitStatus::default(), // This is wrong but `from_raw` is platform-gated.
stdout: indoc!(r"
running bdist_wheel
running build
[...]
creating build/temp.linux-x86_64-cpython-39/pygraphviz
gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DOPENSSL_NO_SSL3 -fPIC -DSWIG_PYTHON_STRICT_BYTE_CHAR -I/tmp/.tmpy6vVes/.venv/include -I/home/konsti/.pyenv/versions/3.9.18/include/python3.9 -c pygraphviz/graphviz_wrap.c -o build/temp.linux-x86_64-cpython-39/pygraphviz/graphviz_wrap.o
"
).lines().map(ToString::to_string).collect(),
stderr: indoc!(r#"
warning: no files found matching '*.png' under directory 'doc'
warning: no files found matching '*.txt' under directory 'doc'
[...]
no previously-included directories found matching 'doc/build'
pygraphviz/graphviz_wrap.c:3020:10: fatal error: graphviz/cgraph.h: No such file or directory
3020 | #include "graphviz/cgraph.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
error: command '/usr/bin/gcc' failed with exit code 1
"#
).lines().map(ToString::to_string).collect(),
};
let err = Error::from_command_output(
"Failed building wheel through setup.py".to_string(),
&output,
BuildOutput::Debug,
None,
None,
Some("pygraphviz-1.11"),
);
assert!(matches!(err, Error::MissingHeader { .. }));
// Unix uses exit status, Windows uses exit code.
let formatted = std::error::Error::source(&err)
.unwrap()
.to_string()
.replace("exit status: ", "exit code: ");
let formatted = anstream::adapter::strip_str(&formatted);
insta::assert_snapshot!(formatted, @r###"
Failed building wheel through setup.py (exit code: 0)
[stdout]
running bdist_wheel
running build
[...]
creating build/temp.linux-x86_64-cpython-39/pygraphviz
gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DOPENSSL_NO_SSL3 -fPIC -DSWIG_PYTHON_STRICT_BYTE_CHAR -I/tmp/.tmpy6vVes/.venv/include -I/home/konsti/.pyenv/versions/3.9.18/include/python3.9 -c pygraphviz/graphviz_wrap.c -o build/temp.linux-x86_64-cpython-39/pygraphviz/graphviz_wrap.o
[stderr]
warning: no files found matching '*.png' under directory 'doc'
warning: no files found matching '*.txt' under directory 'doc'
[...]
no previously-included directories found matching 'doc/build'
pygraphviz/graphviz_wrap.c:3020:10: fatal error: graphviz/cgraph.h: No such file or directory
3020 | #include "graphviz/cgraph.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
error: command '/usr/bin/gcc' failed with exit code 1
hint: This error likely indicates that you need to install a library that provides "graphviz/cgraph.h" for `pygraphviz-1.11`
"###);
}
#[test]
fn missing_linker_library() {
let output = PythonRunnerOutput {
status: ExitStatus::default(), // This is wrong but `from_raw` is platform-gated.
stdout: Vec::new(),
stderr: indoc!(
r"
1099 | n = strlen(p);
| ^~~~~~~~~
/usr/bin/ld: cannot find -lncurses: No such file or directory
collect2: error: ld returned 1 exit status
error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1"
)
.lines()
.map(ToString::to_string)
.collect(),
};
let err = Error::from_command_output(
"Failed building wheel through setup.py".to_string(),
&output,
BuildOutput::Debug,
None,
None,
Some("pygraphviz-1.11"),
);
assert!(matches!(err, Error::MissingHeader { .. }));
// Unix uses exit status, Windows uses exit code.
let formatted = std::error::Error::source(&err)
.unwrap()
.to_string()
.replace("exit status: ", "exit code: ");
let formatted = anstream::adapter::strip_str(&formatted);
insta::assert_snapshot!(formatted, @r###"
Failed building wheel through setup.py (exit code: 0)
[stderr]
1099 | n = strlen(p);
| ^~~~~~~~~
/usr/bin/ld: cannot find -lncurses: No such file or directory
collect2: error: ld returned 1 exit status
error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
hint: This error likely indicates that you need to install the library that provides a shared library for `ncurses` for `pygraphviz-1.11` (e.g., `libncurses-dev`)
"###);
}
#[test]
fn missing_wheel_package() {
let output = PythonRunnerOutput {
status: ExitStatus::default(), // This is wrong but `from_raw` is platform-gated.
stdout: Vec::new(),
stderr: indoc!(
r"
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'"
)
.lines()
.map(ToString::to_string)
.collect(),
};
let err = Error::from_command_output(
"Failed building wheel through setup.py".to_string(),
&output,
BuildOutput::Debug,
None,
None,
Some("pygraphviz-1.11"),
);
assert!(matches!(err, Error::MissingHeader { .. }));
// Unix uses exit status, Windows uses exit code.
let formatted = std::error::Error::source(&err)
.unwrap()
.to_string()
.replace("exit status: ", "exit code: ");
let formatted = anstream::adapter::strip_str(&formatted);
insta::assert_snapshot!(formatted, @r#"
Failed building wheel through setup.py (exit code: 0)
[stderr]
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
hint: This error likely indicates that `pygraphviz-1.11` depends on `wheel`, but doesn't declare it as a build dependency. If `pygraphviz-1.11` is a first-party package, consider adding `wheel` to its `build-system.requires`. Otherwise, either add it to your `pyproject.toml` under:
[tool.uv.extra-build-dependencies]
"pygraphviz-1.11" = ["wheel"]
or `uv pip install wheel` into the environment and re-run with `--no-build-isolation`.
"#);
}
#[test]
fn missing_distutils() {
let output = PythonRunnerOutput {
status: ExitStatus::default(), // This is wrong but `from_raw` is platform-gated.
stdout: Vec::new(),
stderr: indoc!(
r"
import distutils.core
ModuleNotFoundError: No module named 'distutils'
"
)
.lines()
.map(ToString::to_string)
.collect(),
};
let err = Error::from_command_output(
"Failed building wheel through setup.py".to_string(),
&output,
BuildOutput::Debug,
Some(&PackageName::from_str("pygraphviz").unwrap()),
Some(&Version::new([1, 11])),
Some("pygraphviz-1.11"),
);
assert!(matches!(err, Error::MissingHeader { .. }));
// Unix uses exit status, Windows uses exit code.
let formatted = std::error::Error::source(&err)
.unwrap()
.to_string()
.replace("exit status: ", "exit code: ");
let formatted = anstream::adapter::strip_str(&formatted);
insta::assert_snapshot!(formatted, @r###"
Failed building wheel through setup.py (exit code: 0)
[stderr]
import distutils.core
ModuleNotFoundError: No module named 'distutils'
hint: `distutils` was removed from the standard library in Python 3.12. Consider adding a constraint (like `pygraphviz >1.11`) to avoid building a version of `pygraphviz` that depends on `distutils`.
"###);
}
}
| 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/src/main.rs | crates/uv-build/src/main.rs | use std::env;
use std::io::Write;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
use uv_logging::UvFormat;
/// Entrypoint for the `uv-build` Python package.
fn main() -> Result<()> {
// Support configuring the log level with `RUST_LOG` (shows only the error level by default) and
// color.
//
// This configuration is a simplified version of the uv logging configuration. When using
// uv_build through uv proper, the uv logging configuration applies.
let filter = EnvFilter::builder()
.with_default_directive(LevelFilter::OFF.into())
.from_env()
.context("Invalid RUST_LOG directives")?;
let stderr_layer = tracing_subscriber::fmt::layer()
.event_format(UvFormat::default())
.with_writer(std::sync::Mutex::new(anstream::stderr()))
.with_filter(filter);
tracing_subscriber::registry().with(stderr_layer).init();
// Handrolled to avoid the large clap dependency
let mut args = env::args_os();
// Skip the name of the binary
args.next();
let command = args
.next()
.context("Missing command")?
.to_str()
.context("Invalid non-UTF8 command")?
.to_string();
match command.as_str() {
"build-sdist" => {
let sdist_directory = PathBuf::from(args.next().context("Missing sdist directory")?);
let filename = uv_build_backend::build_source_dist(
&env::current_dir()?,
&sdist_directory,
uv_version::version(),
false,
)?;
// Tell the build frontend about the name of the artifact we built
writeln!(&mut std::io::stdout(), "{filename}").context("stdout is closed")?;
}
"build-wheel" => {
let wheel_directory = PathBuf::from(args.next().context("Missing wheel directory")?);
let metadata_directory = args.next().map(PathBuf::from);
let filename = uv_build_backend::build_wheel(
&env::current_dir()?,
&wheel_directory,
metadata_directory.as_deref(),
uv_version::version(),
false,
)?;
// Tell the build frontend about the name of the artifact we built
writeln!(&mut std::io::stdout(), "{filename}").context("stdout is closed")?;
}
"build-editable" => {
let wheel_directory = PathBuf::from(args.next().context("Missing wheel directory")?);
let metadata_directory = args.next().map(PathBuf::from);
let filename = uv_build_backend::build_editable(
&env::current_dir()?,
&wheel_directory,
metadata_directory.as_deref(),
uv_version::version(),
false,
)?;
// Tell the build frontend about the name of the artifact we built
writeln!(&mut std::io::stdout(), "{filename}").context("stdout is closed")?;
}
"prepare-metadata-for-build-wheel" => {
let wheel_directory = PathBuf::from(args.next().context("Missing wheel directory")?);
let filename = uv_build_backend::metadata(
&env::current_dir()?,
&wheel_directory,
uv_version::version(),
)?;
// Tell the build frontend about the name of the artifact we built
writeln!(&mut std::io::stdout(), "{filename}").context("stdout is closed")?;
}
"prepare-metadata-for-build-editable" => {
let wheel_directory = PathBuf::from(args.next().context("Missing wheel directory")?);
let filename = uv_build_backend::metadata(
&env::current_dir()?,
&wheel_directory,
uv_version::version(),
)?;
// Tell the build frontend about the name of the artifact we built
writeln!(&mut std::io::stdout(), "{filename}").context("stdout is closed")?;
}
"--help" => {
// This works both as redirect to use the proper uv package and as smoke test.
writeln!(
&mut std::io::stderr(),
"uv_build contains only the PEP 517 build backend for uv and can't be used on the CLI. \
Use `uv build` or another build frontend instead."
).context("stdout is closed")?;
}
unknown => {
bail!(
"Unknown subcommand: {} (cli: {:?})",
unknown,
env::args_os()
);
}
}
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-extract/src/stream.rs | crates/uv-extract/src/stream.rs | use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use async_zip::base::read::cd::Entry;
use async_zip::error::ZipError;
use futures::{AsyncReadExt, StreamExt};
use rustc_hash::{FxHashMap, FxHashSet};
use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt};
use tracing::{debug, warn};
use uv_distribution_filename::SourceDistExtension;
use crate::{Error, insecure_no_validate, validate_archive_member_name};
const DEFAULT_BUF_SIZE: usize = 128 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
struct LocalHeaderEntry {
/// The relative path of the entry, as computed from the local file header.
relpath: PathBuf,
/// The computed CRC32 checksum of the entry.
crc32: u32,
/// The computed compressed size of the entry.
compressed_size: u64,
/// The computed uncompressed size of the entry.
uncompressed_size: u64,
/// Whether the entry has a data descriptor.
data_descriptor: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ComputedEntry {
/// The computed CRC32 checksum of the entry.
crc32: u32,
/// The computed uncompressed size of the entry.
uncompressed_size: u64,
/// The computed compressed size of the entry.
compressed_size: u64,
}
/// Unpack a `.zip` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unzipping files as they're being downloaded. If the archive
/// is already fully on disk, consider using `unzip_archive`, which can use multiple
/// threads to work faster in that case.
pub async fn unzip<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
/// Ensure the file path is safe to use as a [`Path`].
///
/// See: <https://docs.rs/zip/latest/zip/read/struct.ZipFile.html#method.enclosed_name>
pub(crate) fn enclosed_name(file_name: &str) -> Option<PathBuf> {
if file_name.contains('\0') {
return None;
}
let path = PathBuf::from(file_name);
let mut depth = 0usize;
for component in path.components() {
match component {
Component::Prefix(_) | Component::RootDir => return None,
Component::ParentDir => depth = depth.checked_sub(1)?,
Component::Normal(_) => depth += 1,
Component::CurDir => (),
}
}
Some(path)
}
// Determine whether ZIP validation is disabled.
let skip_validation = insecure_no_validate();
let target = target.as_ref();
let mut reader = futures::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader.compat());
let mut zip = async_zip::base::read::stream::ZipFileReader::new(&mut reader);
let mut directories = FxHashSet::default();
let mut local_headers = FxHashMap::default();
let mut offset = 0;
while let Some(mut entry) = zip.next_with_entry().await? {
// Construct the (expected) path to the file on-disk.
let path = match entry.reader().entry().filename().as_str() {
Ok(path) => path,
Err(ZipError::StringNotUtf8) => return Err(Error::LocalHeaderNotUtf8 { offset }),
Err(err) => return Err(err.into()),
};
// Apply sanity checks to the file names in local headers.
if let Err(e) = validate_archive_member_name(path) {
if !skip_validation {
return Err(e);
}
}
// Sanitize the file name to prevent directory traversal attacks.
let Some(relpath) = enclosed_name(path) else {
warn!("Skipping unsafe file name: {path}");
// Close current file prior to proceeding, as per:
// https://docs.rs/async_zip/0.0.16/async_zip/base/read/stream/
(.., zip) = entry.skip().await?;
// Store the current offset.
offset = zip.offset();
continue;
};
let file_offset = entry.reader().entry().file_offset();
let expected_compressed_size = entry.reader().entry().compressed_size();
let expected_uncompressed_size = entry.reader().entry().uncompressed_size();
let expected_data_descriptor = entry.reader().entry().data_descriptor();
// Either create the directory or write the file to disk.
let path = target.join(&relpath);
let is_dir = entry.reader().entry().dir()?;
let computed = if is_dir {
if directories.insert(path.clone()) {
fs_err::tokio::create_dir_all(path)
.await
.map_err(Error::Io)?;
}
// If this is a directory, we expect the CRC32 to be 0.
if entry.reader().entry().crc32() != 0 {
if !skip_validation {
return Err(Error::BadCrc32 {
path: relpath.clone(),
computed: 0,
expected: entry.reader().entry().crc32(),
});
}
}
// If this is a directory, we expect the uncompressed size to be 0.
if entry.reader().entry().uncompressed_size() != 0 {
if !skip_validation {
return Err(Error::BadUncompressedSize {
path: relpath.clone(),
computed: 0,
expected: entry.reader().entry().uncompressed_size(),
});
}
}
ComputedEntry {
crc32: 0,
uncompressed_size: 0,
compressed_size: 0,
}
} else {
if let Some(parent) = path.parent() {
if directories.insert(parent.to_path_buf()) {
fs_err::tokio::create_dir_all(parent)
.await
.map_err(Error::Io)?;
}
}
// We don't know the file permissions here, because we haven't seen the central directory yet.
let (actual_uncompressed_size, reader) = match fs_err::tokio::File::create_new(&path)
.await
{
Ok(file) => {
// Write the file to disk.
let size = entry.reader().entry().uncompressed_size();
let mut writer = if let Ok(size) = usize::try_from(size) {
tokio::io::BufWriter::with_capacity(std::cmp::min(size, 1024 * 1024), file)
} else {
tokio::io::BufWriter::new(file)
};
let mut reader = entry.reader_mut().compat();
let bytes_read = tokio::io::copy(&mut reader, &mut writer)
.await
.map_err(Error::io_or_compression)?;
let reader = reader.into_inner();
(bytes_read, reader)
}
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
debug!(
"Found duplicate local file header for: {}",
relpath.display()
);
// Read the existing file into memory.
let existing_contents = fs_err::tokio::read(&path).await.map_err(Error::Io)?;
// Read the entry into memory.
let mut expected_contents = Vec::with_capacity(existing_contents.len());
let entry_reader = entry.reader_mut();
let bytes_read = entry_reader
.read_to_end(&mut expected_contents)
.await
.map_err(Error::io_or_compression)?;
// Verify that the existing file contents match the expected contents.
if existing_contents != expected_contents {
if !skip_validation {
return Err(Error::DuplicateLocalFileHeader {
path: relpath.clone(),
});
}
}
(bytes_read as u64, entry_reader)
}
Err(err) => return Err(Error::Io(err)),
};
// Validate the uncompressed size.
if actual_uncompressed_size != expected_uncompressed_size {
if !(expected_compressed_size == 0 && expected_data_descriptor) {
if !skip_validation {
return Err(Error::BadUncompressedSize {
path: relpath.clone(),
computed: actual_uncompressed_size,
expected: expected_uncompressed_size,
});
}
}
}
// Validate the compressed size.
let actual_compressed_size = reader.bytes_read();
if actual_compressed_size != expected_compressed_size {
if !(expected_compressed_size == 0 && expected_data_descriptor) {
if !skip_validation {
return Err(Error::BadCompressedSize {
path: relpath.clone(),
computed: actual_compressed_size,
expected: expected_compressed_size,
});
}
}
}
// Validate the CRC of any file we unpack
// (It would be nice if async_zip made it harder to Not do this...)
let actual_crc32 = reader.compute_hash();
let expected_crc32 = reader.entry().crc32();
if actual_crc32 != expected_crc32 {
if !(expected_crc32 == 0 && expected_data_descriptor) {
if !skip_validation {
return Err(Error::BadCrc32 {
path: relpath.clone(),
computed: actual_crc32,
expected: expected_crc32,
});
}
}
}
ComputedEntry {
crc32: actual_crc32,
uncompressed_size: actual_uncompressed_size,
compressed_size: actual_compressed_size,
}
};
// Close current file prior to proceeding, as per:
// https://docs.rs/async_zip/0.0.16/async_zip/base/read/stream/
let (descriptor, next) = entry.skip().await?;
// Verify that the data descriptor field is consistent with the presence (or absence) of a
// data descriptor in the local file header.
if expected_data_descriptor && descriptor.is_none() {
if !skip_validation {
return Err(Error::MissingDataDescriptor {
path: relpath.clone(),
});
}
}
if !expected_data_descriptor && descriptor.is_some() {
if !skip_validation {
return Err(Error::UnexpectedDataDescriptor {
path: relpath.clone(),
});
}
}
// If we have a data descriptor, validate it.
if let Some(descriptor) = descriptor {
if descriptor.crc != computed.crc32 {
if !skip_validation {
return Err(Error::BadCrc32 {
path: relpath.clone(),
computed: computed.crc32,
expected: descriptor.crc,
});
}
}
if descriptor.uncompressed_size != computed.uncompressed_size {
if !skip_validation {
return Err(Error::BadUncompressedSize {
path: relpath.clone(),
computed: computed.uncompressed_size,
expected: descriptor.uncompressed_size,
});
}
}
if descriptor.compressed_size != computed.compressed_size {
if !skip_validation {
return Err(Error::BadCompressedSize {
path: relpath.clone(),
computed: computed.compressed_size,
expected: descriptor.compressed_size,
});
}
}
}
// Store the offset, for validation, and error if we see a duplicate file.
match local_headers.entry(file_offset) {
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(LocalHeaderEntry {
relpath,
crc32: computed.crc32,
uncompressed_size: computed.uncompressed_size,
compressed_size: expected_compressed_size,
data_descriptor: expected_data_descriptor,
});
}
std::collections::hash_map::Entry::Occupied(..) => {
if !skip_validation {
return Err(Error::DuplicateLocalFileHeader {
path: relpath.clone(),
});
}
}
}
// Advance the reader to the next entry.
zip = next;
// Store the current offset.
offset = zip.offset();
}
// Record the actual number of entries in the central directory.
let mut num_entries = 0;
// Track the file modes on Unix, to ensure that they're consistent across duplicates.
#[cfg(unix)]
let mut modes =
FxHashMap::with_capacity_and_hasher(local_headers.len(), rustc_hash::FxBuildHasher);
let mut directory = async_zip::base::read::cd::CentralDirectoryReader::new(&mut reader, offset);
loop {
match directory.next().await? {
Entry::CentralDirectoryEntry(entry) => {
// Count the number of entries in the central directory.
num_entries += 1;
// Construct the (expected) path to the file on-disk.
let path = match entry.filename().as_str() {
Ok(path) => path,
Err(ZipError::StringNotUtf8) => {
return Err(Error::CentralDirectoryEntryNotUtf8 {
index: num_entries - 1,
});
}
Err(err) => return Err(err.into()),
};
// Apply sanity checks to the file names in CD headers.
if let Err(e) = validate_archive_member_name(path) {
if !skip_validation {
return Err(e);
}
}
// Sanitize the file name to prevent directory traversal attacks.
let Some(relpath) = enclosed_name(path) else {
continue;
};
// Validate that various fields are consistent between the local file header and the
// central directory entry.
match local_headers.remove(&entry.file_offset()) {
Some(local_header) => {
if local_header.relpath != relpath {
if !skip_validation {
return Err(Error::ConflictingPaths {
offset: entry.file_offset(),
local_path: local_header.relpath.clone(),
central_directory_path: relpath.clone(),
});
}
}
if local_header.crc32 != entry.crc32() {
if !skip_validation {
return Err(Error::ConflictingChecksums {
path: relpath.clone(),
offset: entry.file_offset(),
local_crc32: local_header.crc32,
central_directory_crc32: entry.crc32(),
});
}
}
if local_header.uncompressed_size != entry.uncompressed_size() {
if !skip_validation {
return Err(Error::ConflictingUncompressedSizes {
path: relpath.clone(),
offset: entry.file_offset(),
local_uncompressed_size: local_header.uncompressed_size,
central_directory_uncompressed_size: entry.uncompressed_size(),
});
}
}
if local_header.compressed_size != entry.compressed_size() {
if !local_header.data_descriptor {
if !skip_validation {
return Err(Error::ConflictingCompressedSizes {
path: relpath.clone(),
offset: entry.file_offset(),
local_compressed_size: local_header.compressed_size,
central_directory_compressed_size: entry.compressed_size(),
});
}
}
}
}
None => {
if !skip_validation {
return Err(Error::MissingLocalFileHeader {
path: relpath.clone(),
offset: entry.file_offset(),
});
}
}
}
// On Unix, we need to set file permissions, which are stored in the central directory, at the
// end of the archive. The `ZipFileReader` reads until it sees a central directory signature,
// which indicates the first entry in the central directory. So we continue reading from there.
#[cfg(unix)]
{
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
if entry.dir()? {
continue;
}
let Some(mode) = entry.unix_permissions() else {
continue;
};
// If the file is included multiple times, ensure that the mode is consistent.
match modes.entry(relpath.clone()) {
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(mode);
}
std::collections::hash_map::Entry::Occupied(entry) => {
if mode != *entry.get() {
if !skip_validation {
return Err(Error::DuplicateExecutableFileHeader {
path: relpath.clone(),
});
}
}
}
}
// The executable bit is the only permission we preserve, otherwise we use the OS defaults.
// https://github.com/pypa/pip/blob/3898741e29b7279e7bffe044ecfbe20f6a438b1e/src/pip/_internal/utils/unpacking.py#L88-L100
let has_any_executable_bit = mode & 0o111;
if has_any_executable_bit != 0 {
let path = target.join(relpath);
let permissions = fs_err::tokio::metadata(&path)
.await
.map_err(Error::Io)?
.permissions();
if permissions.mode() & 0o111 != 0o111 {
fs_err::tokio::set_permissions(
&path,
Permissions::from_mode(permissions.mode() | 0o111),
)
.await
.map_err(Error::Io)?;
}
}
}
}
Entry::EndOfCentralDirectoryRecord {
record,
comment,
extensible,
} => {
// Reject ZIP64 end-of-central-directory records with extensible data, as the safety
// tradeoffs don't outweigh the usefulness. We don't ever expect to encounter wheels
// that leverage this feature anyway.
if extensible {
if !skip_validation {
return Err(Error::ExtensibleData);
}
}
// Sanitize the comment by rejecting bytes `01` to `08`. If the comment contains an
// embedded ZIP file, it _must_ contain one of these bytes, which are otherwise
// very rare (non-printing) characters.
if comment.as_bytes().iter().any(|&b| (1..=8).contains(&b)) {
if !skip_validation {
return Err(Error::ZipInZip);
}
}
// Validate that the reported number of entries match what we experienced while
// reading the local file headers.
if record.num_entries() != num_entries {
if !skip_validation {
return Err(Error::ConflictingNumberOfEntries {
expected: num_entries,
actual: record.num_entries(),
});
}
}
break;
}
}
}
// If we didn't see the file in the central directory, it means it was not present in the
// archive.
if !skip_validation {
if let Some((key, value)) = local_headers.iter().next() {
return Err(Error::MissingCentralDirectoryEntry {
offset: *key,
path: value.relpath.clone(),
});
}
}
// Determine whether the reader is exhausted, but allow trailing null bytes, which some zip
// implementations incorrectly include.
if !skip_validation {
let mut has_trailing_bytes = false;
let mut buf = [0u8; 256];
loop {
let n = reader.read(&mut buf).await.map_err(Error::Io)?;
if n == 0 {
if has_trailing_bytes {
warn!("Ignoring trailing null bytes in ZIP archive");
}
break;
}
for &b in &buf[..n] {
if b == 0 {
has_trailing_bytes = true;
} else {
return Err(Error::TrailingContents);
}
}
}
}
Ok(())
}
/// Unpack the given tar archive into the destination directory.
///
/// This is equivalent to `archive.unpack_in(dst)`, but it also preserves the executable bit.
async fn untar_in(
mut archive: tokio_tar::Archive<&'_ mut (dyn tokio::io::AsyncRead + Unpin)>,
dst: &Path,
) -> std::io::Result<()> {
// Like `tokio-tar`, canonicalize the destination prior to unpacking.
let dst = fs_err::tokio::canonicalize(dst).await?;
// Memoize filesystem calls to canonicalize paths.
let mut memo = FxHashSet::default();
let mut entries = archive.entries()?;
let mut pinned = Pin::new(&mut entries);
while let Some(entry) = pinned.next().await {
// Unpack the file into the destination directory.
let mut file = entry?;
// On Windows, skip symlink entries, as they're not supported. pip recursively copies the
// symlink target instead.
if cfg!(windows) && file.header().entry_type().is_symlink() {
warn!(
"Skipping symlink in tar archive: {}",
file.path()?.display()
);
continue;
}
// Unpack the file into the destination directory.
#[cfg_attr(not(unix), allow(unused_variables))]
let unpacked_at = file.unpack_in_raw(&dst, &mut memo).await?;
// Preserve the executable bit.
#[cfg(unix)]
{
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
let entry_type = file.header().entry_type();
if entry_type.is_file() || entry_type.is_hard_link() {
let mode = file.header().mode()?;
let has_any_executable_bit = mode & 0o111;
if has_any_executable_bit != 0 {
if let Some(path) = unpacked_at.as_deref() {
let permissions = fs_err::tokio::metadata(&path).await?.permissions();
if permissions.mode() & 0o111 != 0o111 {
fs_err::tokio::set_permissions(
&path,
Permissions::from_mode(permissions.mode() | 0o111),
)
.await?;
}
}
}
}
}
}
Ok(())
}
/// Unpack a `.tar.gz` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unpacking files as they're being downloaded.
pub async fn untar_gz<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
let reader = tokio::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let mut decompressed_bytes = async_compression::tokio::bufread::GzipDecoder::new(reader);
let archive = tokio_tar::ArchiveBuilder::new(
&mut decompressed_bytes as &mut (dyn tokio::io::AsyncRead + Unpin),
)
.set_preserve_mtime(false)
.set_preserve_permissions(false)
.set_allow_external_symlinks(false)
.build();
untar_in(archive, target.as_ref())
.await
.map_err(Error::io_or_compression)
}
/// Unpack a `.tar.bz2` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unpacking files as they're being downloaded.
pub async fn untar_bz2<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
let reader = tokio::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let mut decompressed_bytes = async_compression::tokio::bufread::BzDecoder::new(reader);
let archive = tokio_tar::ArchiveBuilder::new(
&mut decompressed_bytes as &mut (dyn tokio::io::AsyncRead + Unpin),
)
.set_preserve_mtime(false)
.set_preserve_permissions(false)
.set_allow_external_symlinks(false)
.build();
untar_in(archive, target.as_ref())
.await
.map_err(Error::io_or_compression)
}
/// Unpack a `.tar.zst` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unpacking files as they're being downloaded.
pub async fn untar_zst<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
let reader = tokio::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let mut decompressed_bytes = async_compression::tokio::bufread::ZstdDecoder::new(reader);
let archive = tokio_tar::ArchiveBuilder::new(
&mut decompressed_bytes as &mut (dyn tokio::io::AsyncRead + Unpin),
)
.set_preserve_mtime(false)
.set_preserve_permissions(false)
.set_allow_external_symlinks(false)
.build();
untar_in(archive, target.as_ref())
.await
.map_err(Error::io_or_compression)
}
/// Unpack a `.tar.zst` archive from a file on disk into the target directory.
pub fn untar_zst_file<R: std::io::Read>(reader: R, target: impl AsRef<Path>) -> Result<(), Error> {
let reader = std::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let decompressed = zstd::Decoder::new(reader).map_err(Error::Io)?;
let mut archive = tar::Archive::new(decompressed);
archive.set_preserve_mtime(false);
archive.unpack(target).map_err(Error::io_or_compression)?;
Ok(())
}
/// Unpack a `.tar.xz` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unpacking files as they're being downloaded.
pub async fn untar_xz<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
let reader = tokio::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let mut decompressed_bytes = async_compression::tokio::bufread::XzDecoder::new(reader);
let archive = tokio_tar::ArchiveBuilder::new(
&mut decompressed_bytes as &mut (dyn tokio::io::AsyncRead + Unpin),
)
.set_preserve_mtime(false)
.set_preserve_permissions(false)
.set_allow_external_symlinks(false)
.build();
untar_in(archive, target.as_ref())
.await
.map_err(Error::io_or_compression)?;
Ok(())
}
/// Unpack a `.tar` archive into the target directory, without requiring `Seek`.
///
/// This is useful for unpacking files as they're being downloaded.
pub async fn untar<R: tokio::io::AsyncRead + Unpin>(
reader: R,
target: impl AsRef<Path>,
) -> Result<(), Error> {
let mut reader = tokio::io::BufReader::with_capacity(DEFAULT_BUF_SIZE, reader);
let archive =
tokio_tar::ArchiveBuilder::new(&mut reader as &mut (dyn tokio::io::AsyncRead + Unpin))
.set_preserve_mtime(false)
.set_preserve_permissions(false)
.set_allow_external_symlinks(false)
.build();
untar_in(archive, target.as_ref())
.await
.map_err(Error::io_or_compression)?;
Ok(())
}
/// Unpack a `.zip`, `.tar.gz`, `.tar.bz2`, `.tar.zst`, or `.tar.xz` archive into the target directory,
/// without requiring `Seek`.
pub async fn archive<R: tokio::io::AsyncRead + Unpin>(
reader: R,
ext: SourceDistExtension,
target: impl AsRef<Path>,
) -> Result<(), Error> {
match ext {
SourceDistExtension::Zip => {
unzip(reader, target).await?;
}
SourceDistExtension::Tar => {
untar(reader, target).await?;
}
SourceDistExtension::Tgz | SourceDistExtension::TarGz => {
untar_gz(reader, target).await?;
}
SourceDistExtension::Tbz | SourceDistExtension::TarBz2 => {
untar_bz2(reader, target).await?;
}
SourceDistExtension::Txz
| SourceDistExtension::TarXz
| SourceDistExtension::Tlz
| SourceDistExtension::TarLz
| SourceDistExtension::TarLzma => {
untar_xz(reader, target).await?;
}
SourceDistExtension::TarZst => {
untar_zst(reader, target).await?;
}
}
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-extract/src/lib.rs | crates/uv-extract/src/lib.rs | use std::sync::LazyLock;
pub use error::Error;
use regex::Regex;
pub use sync::*;
use uv_static::EnvVars;
mod error;
pub mod hash;
pub mod stream;
mod sync;
mod vendor;
static CONTROL_CHARACTERS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\p{C}").unwrap());
static REPLACEMENT_CHARACTER: &str = "\u{FFFD}";
/// Validate that a given filename (e.g. reported by a ZIP archive's
/// local file entries or central directory entries) is "safe" to use.
///
/// "Safe" in this context doesn't refer to directory traversal
/// risk, but whether we believe that other ZIP implementations
/// handle the name correctly and consistently.
///
/// Specifically, we want to avoid names that:
///
/// - Contain *any* non-printable characters
/// - Are empty
///
/// In the future, we may also want to check for names that contain
/// leading/trailing whitespace, or names that are exceedingly long.
pub(crate) fn validate_archive_member_name(name: &str) -> Result<(), Error> {
if name.is_empty() {
return Err(Error::EmptyFilename);
}
match CONTROL_CHARACTERS_RE.replace_all(name, REPLACEMENT_CHARACTER) {
// No replacements mean no control characters.
std::borrow::Cow::Borrowed(_) => Ok(()),
std::borrow::Cow::Owned(sanitized) => Err(Error::UnacceptableFilename {
filename: sanitized,
}),
}
}
/// Returns `true` if ZIP validation is disabled.
pub(crate) fn insecure_no_validate() -> bool {
// TODO(charlie) Parse this in `EnvironmentOptions`.
let Some(value) = std::env::var_os(EnvVars::UV_INSECURE_NO_ZIP_VALIDATION) else {
return false;
};
let Some(value) = value.to_str() else {
return false;
};
matches!(
value.to_lowercase().as_str(),
"y" | "yes" | "t" | "true" | "on" | "1"
)
}
#[cfg(test)]
mod tests {
#[test]
fn test_validate_archive_member_name() {
for (testcase, ok) in &[
// Valid cases.
("normal.txt", true),
("__init__.py", true),
("fine i guess.py", true),
("π.py", true),
// Invalid cases.
("", false),
("new\nline.py", false),
("carriage\rreturn.py", false),
("tab\tcharacter.py", false),
("null\0byte.py", false),
("control\x01code.py", false),
("control\x02code.py", false),
("control\x03code.py", false),
("control\x04code.py", false),
("backspace\x08code.py", false),
("delete\x7fcode.py", false),
] {
assert_eq!(
super::validate_archive_member_name(testcase).is_ok(),
*ok,
"testcase: {testcase}"
);
}
}
#[test]
fn test_unacceptable_filename_error_replaces_control_characters() {
let err = super::validate_archive_member_name("bad\nname").unwrap_err();
match err {
super::Error::UnacceptableFilename { filename } => {
assert_eq!(filename, "badοΏ½name");
}
_ => panic!("expected UnacceptableFilename error"),
}
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-extract/src/sync.rs | crates/uv-extract/src/sync.rs | use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use crate::vendor::{CloneableSeekableReader, HasLength};
use crate::{Error, insecure_no_validate, validate_archive_member_name};
use rayon::prelude::*;
use rustc_hash::FxHashSet;
use tracing::warn;
use uv_configuration::RAYON_INITIALIZE;
use zip::ZipArchive;
/// Unzip a `.zip` archive into the target directory.
pub fn unzip<R: Send + std::io::Read + std::io::Seek + HasLength>(
reader: R,
target: &Path,
) -> Result<(), Error> {
// Unzip in parallel.
let reader = std::io::BufReader::new(reader);
let archive = ZipArchive::new(CloneableSeekableReader::new(reader))?;
let directories = Mutex::new(FxHashSet::default());
let skip_validation = insecure_no_validate();
// Initialize the threadpool with the user settings.
LazyLock::force(&RAYON_INITIALIZE);
(0..archive.len())
.into_par_iter()
.map(|file_number| {
let mut archive = archive.clone();
let mut file = archive.by_index(file_number)?;
if let Err(e) = validate_archive_member_name(file.name()) {
if !skip_validation {
return Err(e);
}
}
// Determine the path of the file within the wheel.
let Some(enclosed_name) = file.enclosed_name() else {
warn!("Skipping unsafe file name: {}", file.name());
return Ok(());
};
// Create necessary parent directories.
let path = target.join(enclosed_name);
if file.is_dir() {
let mut directories = directories.lock().unwrap();
if directories.insert(path.clone()) {
fs_err::create_dir_all(path).map_err(Error::Io)?;
}
return Ok(());
}
if let Some(parent) = path.parent() {
let mut directories = directories.lock().unwrap();
if directories.insert(parent.to_path_buf()) {
fs_err::create_dir_all(parent).map_err(Error::Io)?;
}
}
// Copy the file contents.
let outfile = fs_err::File::create(&path).map_err(Error::Io)?;
let size = file.size();
if size > 0 {
let mut writer = if let Ok(size) = usize::try_from(size) {
std::io::BufWriter::with_capacity(std::cmp::min(size, 1024 * 1024), outfile)
} else {
std::io::BufWriter::new(outfile)
};
std::io::copy(&mut file, &mut writer).map_err(Error::io_or_compression)?;
}
// See `uv_extract::stream::unzip`. For simplicity, this is identical with the code there except for being
// sync.
#[cfg(unix)]
{
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
if let Some(mode) = file.unix_mode() {
// https://github.com/pypa/pip/blob/3898741e29b7279e7bffe044ecfbe20f6a438b1e/src/pip/_internal/utils/unpacking.py#L88-L100
let has_any_executable_bit = mode & 0o111;
if has_any_executable_bit != 0 {
let permissions = fs_err::metadata(&path).map_err(Error::Io)?.permissions();
if permissions.mode() & 0o111 != 0o111 {
fs_err::set_permissions(
&path,
Permissions::from_mode(permissions.mode() | 0o111),
)
.map_err(Error::Io)?;
}
}
}
}
Ok(())
})
.collect::<Result<_, Error>>()
}
/// Extract the top-level directory from an unpacked archive.
///
/// The specification says:
/// > A .tar.gz source distribution (sdist) contains a single top-level directory called
/// > `{name}-{version}` (e.g. foo-1.0), containing the source files of the package.
///
/// This function returns the path to that top-level directory.
pub fn strip_component(source: impl AsRef<Path>) -> Result<PathBuf, Error> {
// TODO(konstin): Verify the name of the directory.
let top_level = fs_err::read_dir(source.as_ref())
.map_err(Error::Io)?
.collect::<std::io::Result<Vec<fs_err::DirEntry>>>()
.map_err(Error::Io)?;
match top_level.as_slice() {
[root] => Ok(root.path()),
[] => Err(Error::EmptyArchive),
_ => Err(Error::NonSingularArchive(
top_level
.into_iter()
.map(|entry| entry.file_name())
.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-extract/src/error.rs | crates/uv-extract/src/error.rs | use std::{ffi::OsString, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("I/O operation failed during extraction")]
Io(#[source] std::io::Error),
#[error("Invalid zip file")]
Zip(#[from] zip::result::ZipError),
#[error("Invalid zip file structure")]
AsyncZip(#[from] async_zip::error::ZipError),
#[error("Invalid tar file")]
Tar(#[from] tokio_tar::TarError),
#[error(
"The top-level of the archive must only contain a list directory, but it contains: {0:?}"
)]
NonSingularArchive(Vec<OsString>),
#[error("The top-level of the archive must only contain a list directory, but it's empty")]
EmptyArchive,
#[error("ZIP local header filename at offset {offset} does not use UTF-8 encoding")]
LocalHeaderNotUtf8 { offset: u64 },
#[error("ZIP central directory entry filename at index {index} does not use UTF-8 encoding")]
CentralDirectoryEntryNotUtf8 { index: u64 },
#[error("Bad CRC (got {computed:08x}, expected {expected:08x}) for file: {}", path.display())]
BadCrc32 {
path: PathBuf,
computed: u32,
expected: u32,
},
#[error("Bad uncompressed size (got {computed:08x}, expected {expected:08x}) for file: {}", path.display())]
BadUncompressedSize {
path: PathBuf,
computed: u64,
expected: u64,
},
#[error("Bad compressed size (got {computed:08x}, expected {expected:08x}) for file: {}", path.display())]
BadCompressedSize {
path: PathBuf,
computed: u64,
expected: u64,
},
#[error("ZIP file contains multiple entries with different contents for: {}", path.display())]
DuplicateLocalFileHeader { path: PathBuf },
#[error("ZIP file contains a local file header without a corresponding central-directory record entry for: {} ({offset})", path.display())]
MissingCentralDirectoryEntry { path: PathBuf, offset: u64 },
#[error("ZIP file contains an end-of-central-directory record entry, but no local file header for: {} ({offset}", path.display())]
MissingLocalFileHeader { path: PathBuf, offset: u64 },
#[error("ZIP file uses conflicting paths for the local file header at {} (got {}, expected {})", offset, local_path.display(), central_directory_path.display())]
ConflictingPaths {
offset: u64,
local_path: PathBuf,
central_directory_path: PathBuf,
},
#[error("ZIP file uses conflicting checksums for the local file header and central-directory record (got {local_crc32}, expected {central_directory_crc32}) for: {} ({offset})", path.display())]
ConflictingChecksums {
path: PathBuf,
offset: u64,
local_crc32: u32,
central_directory_crc32: u32,
},
#[error("ZIP file uses conflicting compressed sizes for the local file header and central-directory record (got {local_compressed_size}, expected {central_directory_compressed_size}) for: {} ({offset})", path.display())]
ConflictingCompressedSizes {
path: PathBuf,
offset: u64,
local_compressed_size: u64,
central_directory_compressed_size: u64,
},
#[error("ZIP file uses conflicting uncompressed sizes for the local file header and central-directory record (got {local_uncompressed_size}, expected {central_directory_uncompressed_size}) for: {} ({offset})", path.display())]
ConflictingUncompressedSizes {
path: PathBuf,
offset: u64,
local_uncompressed_size: u64,
central_directory_uncompressed_size: u64,
},
#[error("ZIP file contains trailing contents after the end-of-central-directory record")]
TrailingContents,
#[error(
"ZIP file reports a number of entries in the central directory that conflicts with the actual number of entries (got {actual}, expected {expected})"
)]
ConflictingNumberOfEntries { actual: u64, expected: u64 },
#[error("Data descriptor is missing for file: {}", path.display())]
MissingDataDescriptor { path: PathBuf },
#[error("File contains an unexpected data descriptor: {}", path.display())]
UnexpectedDataDescriptor { path: PathBuf },
#[error(
"ZIP file end-of-central-directory record contains a comment that appears to be an embedded ZIP file"
)]
ZipInZip,
#[error("ZIP64 end-of-central-directory record contains unsupported extensible data")]
ExtensibleData,
#[error("ZIP file end-of-central-directory record contains multiple entries with the same path, but conflicting modes: {}", path.display())]
DuplicateExecutableFileHeader { path: PathBuf },
#[error("Archive contains a file with an empty filename")]
EmptyFilename,
#[error("Archive contains unacceptable filename: {filename}")]
UnacceptableFilename { filename: String },
}
impl Error {
/// When reading from an archive, the error can either be an IO error from the underlying
/// operating system, or an error with the archive. Both get wrapper into an IO error through
/// e.g., `io::copy`. This method extracts zip and tar errors, to distinguish them from invalid
/// archives.
pub(crate) fn io_or_compression(err: std::io::Error) -> Self {
if err.kind() != std::io::ErrorKind::Other {
return Self::Io(err);
}
let err = match err.downcast::<tokio_tar::TarError>() {
Ok(tar_err) => return Self::Tar(tar_err),
Err(err) => err,
};
let err = match err.downcast::<async_zip::error::ZipError>() {
Ok(zip_err) => return Self::AsyncZip(zip_err),
Err(err) => err,
};
let err = match err.downcast::<zip::result::ZipError>() {
Ok(zip_err) => return Self::Zip(zip_err),
Err(err) => err,
};
Self::Io(err)
}
/// Returns `true` if the error is due to the server not supporting HTTP streaming. Most
/// commonly, this is due to serving ZIP files with features that are incompatible with
/// streaming, like data descriptors.
pub fn is_http_streaming_unsupported(&self) -> bool {
matches!(
self,
Self::AsyncZip(async_zip::error::ZipError::FeatureNotSupported(_))
)
}
/// Returns `true` if the error is due to HTTP streaming request failed.
pub fn is_http_streaming_failed(&self) -> bool {
match self {
Self::AsyncZip(async_zip::error::ZipError::UpstreamReadError(_)) => true,
Self::Io(err) => {
if let Some(inner) = err.get_ref() {
inner.downcast_ref::<reqwest::Error>().is_some()
} else {
false
}
}
_ => 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-extract/src/hash.rs | crates/uv-extract/src/hash.rs | use blake2::digest::consts::U32;
use sha2::Digest;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncReadExt, ReadBuf};
use uv_pypi_types::{HashAlgorithm, HashDigest};
#[derive(Debug)]
pub enum Hasher {
Md5(md5::Md5),
Sha256(sha2::Sha256),
Sha384(sha2::Sha384),
Sha512(sha2::Sha512),
Blake2b(blake2::Blake2b<U32>),
}
impl Hasher {
pub fn update(&mut self, data: &[u8]) {
match self {
Self::Md5(hasher) => hasher.update(data),
Self::Sha256(hasher) => hasher.update(data),
Self::Sha384(hasher) => hasher.update(data),
Self::Sha512(hasher) => hasher.update(data),
Self::Blake2b(hasher) => hasher.update(data),
}
}
}
impl From<HashAlgorithm> for Hasher {
fn from(algorithm: HashAlgorithm) -> Self {
match algorithm {
HashAlgorithm::Md5 => Self::Md5(md5::Md5::new()),
HashAlgorithm::Sha256 => Self::Sha256(sha2::Sha256::new()),
HashAlgorithm::Sha384 => Self::Sha384(sha2::Sha384::new()),
HashAlgorithm::Sha512 => Self::Sha512(sha2::Sha512::new()),
HashAlgorithm::Blake2b => Self::Blake2b(blake2::Blake2b::new()),
}
}
}
impl From<Hasher> for HashDigest {
fn from(hasher: Hasher) -> Self {
match hasher {
Hasher::Md5(hasher) => Self {
algorithm: HashAlgorithm::Md5,
digest: format!("{:x}", hasher.finalize()).into(),
},
Hasher::Sha256(hasher) => Self {
algorithm: HashAlgorithm::Sha256,
digest: format!("{:x}", hasher.finalize()).into(),
},
Hasher::Sha384(hasher) => Self {
algorithm: HashAlgorithm::Sha384,
digest: format!("{:x}", hasher.finalize()).into(),
},
Hasher::Sha512(hasher) => Self {
algorithm: HashAlgorithm::Sha512,
digest: format!("{:x}", hasher.finalize()).into(),
},
Hasher::Blake2b(hasher) => Self {
algorithm: HashAlgorithm::Blake2b,
digest: format!("{:x}", hasher.finalize()).into(),
},
}
}
}
pub struct HashReader<'a, R> {
reader: R,
hashers: &'a mut [Hasher],
}
impl<'a, R> HashReader<'a, R>
where
R: tokio::io::AsyncRead + Unpin,
{
pub fn new(reader: R, hashers: &'a mut [Hasher]) -> Self {
HashReader { reader, hashers }
}
/// Exhaust the underlying reader.
pub async fn finish(&mut self) -> Result<(), std::io::Error> {
while self.read(&mut vec![0; 8192]).await? > 0 {}
Ok(())
}
}
impl<R> tokio::io::AsyncRead for HashReader<'_, R>
where
R: tokio::io::AsyncRead + Unpin,
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
let reader = Pin::new(&mut self.reader);
match reader.poll_read(cx, buf) {
Poll::Ready(Ok(())) => {
for hasher in self.hashers.iter_mut() {
hasher.update(buf.filled());
}
Poll::Ready(Ok(()))
}
other => other,
}
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-extract/src/vendor/cloneable_seekable_reader.rs | crates/uv-extract/src/vendor/cloneable_seekable_reader.rs | // Copyright 2022 Google LLC
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(clippy::cast_sign_loss)]
use std::{
io::{BufReader, Cursor, Read, Seek, SeekFrom},
sync::{Arc, Mutex},
};
/// A trait to represent some reader which has a total length known in
/// advance. This is roughly equivalent to the nightly
/// [`Seek::stream_len`] API.
#[allow(clippy::len_without_is_empty)]
pub trait HasLength {
/// Return the current total length of this stream.
fn len(&self) -> u64;
}
/// A [`Read`] which refers to its underlying stream by reference count,
/// and thus can be cloned cheaply. It supports seeking; each cloned instance
/// maintains its own pointer into the file, and the underlying instance
/// is seeked prior to each read.
pub(crate) struct CloneableSeekableReader<R: Read + Seek + HasLength> {
file: Arc<Mutex<R>>,
pos: u64,
// TODO determine and store this once instead of per cloneable file
file_length: Option<u64>,
}
impl<R: Read + Seek + HasLength> Clone for CloneableSeekableReader<R> {
fn clone(&self) -> Self {
Self {
file: self.file.clone(),
pos: self.pos,
file_length: self.file_length,
}
}
}
impl<R: Read + Seek + HasLength> CloneableSeekableReader<R> {
/// Constructor. Takes ownership of the underlying `Read`.
/// You should pass in only streams whose total length you expect
/// to be fixed and unchanging. Odd behavior may occur if the length
/// of the stream changes; any subsequent seeks will not take account
/// of the changed stream length.
pub(crate) fn new(file: R) -> Self {
Self {
file: Arc::new(Mutex::new(file)),
pos: 0u64,
file_length: None,
}
}
/// Determine the length of the underlying stream.
fn ascertain_file_length(&mut self) -> u64 {
self.file_length.unwrap_or_else(|| {
let len = self.file.lock().unwrap().len();
self.file_length = Some(len);
len
})
}
}
impl<R: Read + Seek + HasLength> Read for CloneableSeekableReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut underlying_file = self.file.lock().expect("Unable to get underlying file");
// TODO share an object which knows current position to avoid unnecessary
// seeks
underlying_file.seek(SeekFrom::Start(self.pos))?;
let read_result = underlying_file.read(buf);
if let Ok(bytes_read) = read_result {
// TODO, once stabilised, use checked_add_signed
self.pos += bytes_read as u64;
}
read_result
}
}
impl<R: Read + Seek + HasLength> Seek for CloneableSeekableReader<R> {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
let new_pos = match pos {
SeekFrom::Start(pos) => pos,
SeekFrom::End(offset_from_end) => {
let file_len = self.ascertain_file_length();
if -offset_from_end as u64 > file_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Seek too far backwards",
));
}
// TODO, once stabilised, use checked_add_signed
file_len - (-offset_from_end as u64)
}
// TODO, once stabilised, use checked_add_signed
SeekFrom::Current(offset_from_pos) => {
if offset_from_pos > 0 {
self.pos + (offset_from_pos as u64)
} else {
self.pos - ((-offset_from_pos) as u64)
}
}
};
self.pos = new_pos;
Ok(new_pos)
}
}
impl<R: HasLength> HasLength for BufReader<R> {
fn len(&self) -> u64 {
self.get_ref().len()
}
}
#[allow(clippy::disallowed_types)]
impl HasLength for std::fs::File {
fn len(&self) -> u64 {
self.metadata().unwrap().len()
}
}
impl HasLength for fs_err::File {
fn len(&self) -> u64 {
self.metadata().unwrap().len()
}
}
impl HasLength for Cursor<Vec<u8>> {
fn len(&self) -> u64 {
self.get_ref().len() as u64
}
}
impl HasLength for Cursor<&Vec<u8>> {
fn len(&self) -> u64 {
self.get_ref().len() as u64
}
}
#[cfg(test)]
mod test {
use std::io::{Cursor, Read, Seek, SeekFrom};
use super::CloneableSeekableReader;
#[test]
fn test_cloneable_seekable_reader() {
let buf: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let buf = Cursor::new(buf);
let mut reader = CloneableSeekableReader::new(buf);
let mut out = vec![0; 2];
assert!(reader.read_exact(&mut out).is_ok());
assert_eq!(out[0], 0);
assert_eq!(out[1], 1);
assert!(reader.seek(SeekFrom::Start(0)).is_ok());
assert!(reader.read_exact(&mut out).is_ok());
assert_eq!(out[0], 0);
assert_eq!(out[1], 1);
assert!(reader.stream_position().is_ok());
assert!(reader.read_exact(&mut out).is_ok());
assert_eq!(out[0], 2);
assert_eq!(out[1], 3);
assert!(reader.seek(SeekFrom::End(-2)).is_ok());
assert!(reader.read_exact(&mut out).is_ok());
assert_eq!(out[0], 8);
assert_eq!(out[1], 9);
assert!(reader.read_exact(&mut out).is_err());
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-extract/src/vendor/mod.rs | crates/uv-extract/src/vendor/mod.rs | pub(crate) use cloneable_seekable_reader::{CloneableSeekableReader, HasLength};
mod cloneable_seekable_reader;
| 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-bench/src/lib.rs | crates/uv-bench/src/lib.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-bench/benches/uv.rs | crates/uv-bench/benches/uv.rs | use std::hint::black_box;
use std::str::FromStr;
use criterion::{Criterion, criterion_group, criterion_main, measurement::WallTime};
use uv_cache::Cache;
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
use uv_distribution_types::Requirement;
use uv_python::PythonEnvironment;
use uv_resolver::Manifest;
fn resolve_warm_jupyter(c: &mut Criterion<WallTime>) {
let run = setup(Manifest::simple(vec![Requirement::from(
uv_pep508::Requirement::from_str("jupyter==1.0.0").unwrap(),
)]));
c.bench_function("resolve_warm_jupyter", |b| b.iter(|| run(false)));
}
fn resolve_warm_jupyter_universal(c: &mut Criterion<WallTime>) {
let run = setup(Manifest::simple(vec![Requirement::from(
uv_pep508::Requirement::from_str("jupyter==1.0.0").unwrap(),
)]));
c.bench_function("resolve_warm_jupyter_universal", |b| b.iter(|| run(true)));
}
fn resolve_warm_airflow(c: &mut Criterion<WallTime>) {
let run = setup(Manifest::simple(vec![
Requirement::from(uv_pep508::Requirement::from_str("apache-airflow[all]==2.9.3").unwrap()),
Requirement::from(
uv_pep508::Requirement::from_str("apache-airflow-providers-apache-beam>3.0.0").unwrap(),
),
]));
c.bench_function("resolve_warm_airflow", |b| b.iter(|| run(false)));
}
// This takes >5m to run in CodSpeed.
// fn resolve_warm_airflow_universal(c: &mut Criterion<WallTime>) {
// let run = setup(Manifest::simple(vec![
// Requirement::from(uv_pep508::Requirement::from_str("apache-airflow[all]").unwrap()),
// Requirement::from(
// uv_pep508::Requirement::from_str("apache-airflow-providers-apache-beam>3.0.0").unwrap(),
// ),
// ]));
// c.bench_function("resolve_warm_airflow_universal", |b| b.iter(|| run(true)));
// }
criterion_group!(
uv,
resolve_warm_jupyter,
resolve_warm_jupyter_universal,
resolve_warm_airflow
);
criterion_main!(uv);
fn setup(manifest: Manifest) -> impl Fn(bool) {
let runtime = tokio::runtime::Builder::new_current_thread()
// CodSpeed limits the total number of threads to 500
.max_blocking_threads(256)
.enable_all()
.build()
.unwrap();
let cache = Cache::from_path("../../.cache")
.init_no_wait()
.expect("No cache contention when running benchmarks")
.unwrap();
let interpreter = PythonEnvironment::from_root("../../.venv", &cache)
.unwrap()
.into_interpreter();
let client = RegistryClientBuilder::new(BaseClientBuilder::default(), cache.clone()).build();
move |universal| {
runtime
.block_on(resolver::resolve(
black_box(manifest.clone()),
black_box(cache.clone()),
black_box(&client),
&interpreter,
universal,
))
.unwrap();
}
}
mod resolver {
use std::sync::LazyLock;
use anyhow::Result;
use uv_cache::Cache;
use uv_client::RegistryClient;
use uv_configuration::{BuildOptions, Concurrency, Constraints, IndexStrategy, SourceStrategy};
use uv_dispatch::{BuildDispatch, SharedState};
use uv_distribution::DistributionDatabase;
use uv_distribution_types::{
ConfigSettings, DependencyMetadata, ExtraBuildRequires, ExtraBuildVariables,
IndexLocations, PackageConfigSettings, RequiresPython,
};
use uv_install_wheel::LinkMode;
use uv_pep440::Version;
use uv_pep508::{MarkerEnvironment, MarkerEnvironmentBuilder};
use uv_platform_tags::{Arch, Os, Platform, Tags};
use uv_preview::Preview;
use uv_pypi_types::{Conflicts, ResolverMarkerEnvironment};
use uv_python::Interpreter;
use uv_resolver::{
ExcludeNewer, FlatIndex, InMemoryIndex, Manifest, OptionsBuilder, PythonRequirement,
Resolver, ResolverEnvironment, ResolverOutput,
};
use uv_types::{BuildIsolation, EmptyInstalledPackages, HashStrategy};
use uv_workspace::WorkspaceCache;
static MARKERS: LazyLock<MarkerEnvironment> = LazyLock::new(|| {
MarkerEnvironment::try_from(MarkerEnvironmentBuilder {
implementation_name: "cpython",
implementation_version: "3.11.5",
os_name: "posix",
platform_machine: "arm64",
platform_python_implementation: "CPython",
platform_release: "21.6.0",
platform_system: "Darwin",
platform_version: "Darwin Kernel Version 21.6.0: Mon Aug 22 20:19:52 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T6000",
python_full_version: "3.11.5",
python_version: "3.11",
sys_platform: "darwin",
}).unwrap()
});
static PLATFORM: Platform = Platform::new(
Os::Macos {
major: 21,
minor: 6,
},
Arch::Aarch64,
);
static TAGS: LazyLock<Tags> = LazyLock::new(|| {
Tags::from_env(&PLATFORM, (3, 11), "cpython", (3, 11), false, false, false).unwrap()
});
pub(crate) async fn resolve(
manifest: Manifest,
cache: Cache,
client: &RegistryClient,
interpreter: &Interpreter,
universal: bool,
) -> Result<ResolverOutput> {
let build_isolation = BuildIsolation::default();
let extra_build_requires = ExtraBuildRequires::default();
let extra_build_variables = ExtraBuildVariables::default();
let build_options = BuildOptions::default();
let concurrency = Concurrency::default();
let config_settings = ConfigSettings::default();
let config_settings_package = PackageConfigSettings::default();
let exclude_newer = ExcludeNewer::global(
jiff::civil::date(2024, 9, 1)
.to_zoned(jiff::tz::TimeZone::UTC)
.unwrap()
.timestamp()
.into(),
);
let build_constraints = Constraints::default();
let flat_index = FlatIndex::default();
let hashes = HashStrategy::default();
let state = SharedState::default();
let index = InMemoryIndex::default();
let index_locations = IndexLocations::default();
let installed_packages = EmptyInstalledPackages;
let options = OptionsBuilder::new()
.exclude_newer(exclude_newer.clone())
.build();
let sources = SourceStrategy::default();
let dependency_metadata = DependencyMetadata::default();
let conflicts = Conflicts::empty();
let workspace_cache = WorkspaceCache::default();
let python_requirement = if universal {
PythonRequirement::from_requires_python(
interpreter,
RequiresPython::greater_than_equal_version(&Version::new([3, 11])),
)
} else {
PythonRequirement::from_interpreter(interpreter)
};
let build_context = BuildDispatch::new(
client,
&cache,
&build_constraints,
interpreter,
&index_locations,
&flat_index,
&dependency_metadata,
state,
IndexStrategy::default(),
&config_settings,
&config_settings_package,
build_isolation,
&extra_build_requires,
&extra_build_variables,
LinkMode::default(),
&build_options,
&hashes,
exclude_newer,
sources,
workspace_cache,
concurrency,
Preview::default(),
);
let markers = if universal {
ResolverEnvironment::universal(vec![])
} else {
ResolverEnvironment::specific(ResolverMarkerEnvironment::from(MARKERS.clone()))
};
let resolver = Resolver::new(
manifest,
options,
&python_requirement,
markers,
interpreter.markers(),
conflicts,
Some(&TAGS),
&flat_index,
&index,
&hashes,
&build_context,
installed_packages,
DistributionDatabase::new(client, &build_context, concurrency.downloads),
)?;
Ok(resolver.resolve().await?)
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-bench/inputs/platform_tags.rs | crates/uv-bench/inputs/platform_tags.rs | &[("cp310", "abi3", "linux_x86_64"), ("cp310", "abi3", "manylinux1_x86_64"), ("cp310", "abi3", "manylinux2010_x86_64"), ("cp310", "abi3", "manylinux2014_x86_64"), ("cp310", "abi3", "manylinux_2_10_x86_64"), ("cp310", "abi3", "manylinux_2_11_x86_64"), ("cp310", "abi3", "manylinux_2_12_x86_64"), ("cp310", "abi3", "manylinux_2_13_x86_64"), ("cp310", "abi3", "manylinux_2_14_x86_64"), ("cp310", "abi3", "manylinux_2_15_x86_64"), ("cp310", "abi3", "manylinux_2_16_x86_64"), ("cp310", "abi3", "manylinux_2_17_x86_64"), ("cp310", "abi3", "manylinux_2_18_x86_64"), ("cp310", "abi3", "manylinux_2_19_x86_64"), ("cp310", "abi3", "manylinux_2_20_x86_64"), ("cp310", "abi3", "manylinux_2_21_x86_64"), ("cp310", "abi3", "manylinux_2_22_x86_64"), ("cp310", "abi3", "manylinux_2_23_x86_64"), ("cp310", "abi3", "manylinux_2_24_x86_64"), ("cp310", "abi3", "manylinux_2_25_x86_64"), ("cp310", "abi3", "manylinux_2_26_x86_64"), ("cp310", "abi3", "manylinux_2_27_x86_64"), ("cp310", "abi3", "manylinux_2_28_x86_64"), ("cp310", "abi3", "manylinux_2_29_x86_64"), ("cp310", "abi3", "manylinux_2_30_x86_64"), ("cp310", "abi3", "manylinux_2_31_x86_64"), ("cp310", "abi3", "manylinux_2_32_x86_64"), ("cp310", "abi3", "manylinux_2_33_x86_64"), ("cp310", "abi3", "manylinux_2_34_x86_64"), ("cp310", "abi3", "manylinux_2_35_x86_64"), ("cp310", "abi3", "manylinux_2_36_x86_64"), ("cp310", "abi3", "manylinux_2_37_x86_64"), ("cp310", "abi3", "manylinux_2_38_x86_64"), ("cp310", "abi3", "manylinux_2_5_x86_64"), ("cp310", "abi3", "manylinux_2_6_x86_64"), ("cp310", "abi3", "manylinux_2_7_x86_64"), ("cp310", "abi3", "manylinux_2_8_x86_64"), ("cp310", "abi3", "manylinux_2_9_x86_64"), ("cp311", "abi3", "linux_x86_64"), ("cp311", "abi3", "manylinux1_x86_64"), ("cp311", "abi3", "manylinux2010_x86_64"), ("cp311", "abi3", "manylinux2014_x86_64"), ("cp311", "abi3", "manylinux_2_10_x86_64"), ("cp311", "abi3", "manylinux_2_11_x86_64"), ("cp311", "abi3", "manylinux_2_12_x86_64"), ("cp311", "abi3", "manylinux_2_13_x86_64"), ("cp311", "abi3", "manylinux_2_14_x86_64"), ("cp311", "abi3", "manylinux_2_15_x86_64"), ("cp311", "abi3", "manylinux_2_16_x86_64"), ("cp311", "abi3", "manylinux_2_17_x86_64"), ("cp311", "abi3", "manylinux_2_18_x86_64"), ("cp311", "abi3", "manylinux_2_19_x86_64"), ("cp311", "abi3", "manylinux_2_20_x86_64"), ("cp311", "abi3", "manylinux_2_21_x86_64"), ("cp311", "abi3", "manylinux_2_22_x86_64"), ("cp311", "abi3", "manylinux_2_23_x86_64"), ("cp311", "abi3", "manylinux_2_24_x86_64"), ("cp311", "abi3", "manylinux_2_25_x86_64"), ("cp311", "abi3", "manylinux_2_26_x86_64"), ("cp311", "abi3", "manylinux_2_27_x86_64"), ("cp311", "abi3", "manylinux_2_28_x86_64"), ("cp311", "abi3", "manylinux_2_29_x86_64"), ("cp311", "abi3", "manylinux_2_30_x86_64"), ("cp311", "abi3", "manylinux_2_31_x86_64"), ("cp311", "abi3", "manylinux_2_32_x86_64"), ("cp311", "abi3", "manylinux_2_33_x86_64"), ("cp311", "abi3", "manylinux_2_34_x86_64"), ("cp311", "abi3", "manylinux_2_35_x86_64"), ("cp311", "abi3", "manylinux_2_36_x86_64"), ("cp311", "abi3", "manylinux_2_37_x86_64"), ("cp311", "abi3", "manylinux_2_38_x86_64"), ("cp311", "abi3", "manylinux_2_5_x86_64"), ("cp311", "abi3", "manylinux_2_6_x86_64"), ("cp311", "abi3", "manylinux_2_7_x86_64"), ("cp311", "abi3", "manylinux_2_8_x86_64"), ("cp311", "abi3", "manylinux_2_9_x86_64"), ("cp311", "cp311", "linux_x86_64"), ("cp311", "cp311", "manylinux1_x86_64"), ("cp311", "cp311", "manylinux2010_x86_64"), ("cp311", "cp311", "manylinux2014_x86_64"), ("cp311", "cp311", "manylinux_2_10_x86_64"), ("cp311", "cp311", "manylinux_2_11_x86_64"), ("cp311", "cp311", "manylinux_2_12_x86_64"), ("cp311", "cp311", "manylinux_2_13_x86_64"), ("cp311", "cp311", "manylinux_2_14_x86_64"), ("cp311", "cp311", "manylinux_2_15_x86_64"), ("cp311", "cp311", "manylinux_2_16_x86_64"), ("cp311", "cp311", "manylinux_2_17_x86_64"), ("cp311", "cp311", "manylinux_2_18_x86_64"), ("cp311", "cp311", "manylinux_2_19_x86_64"), ("cp311", "cp311", "manylinux_2_20_x86_64"), ("cp311", "cp311", "manylinux_2_21_x86_64"), ("cp311", "cp311", "manylinux_2_22_x86_64"), ("cp311", "cp311", "manylinux_2_23_x86_64"), ("cp311", "cp311", "manylinux_2_24_x86_64"), ("cp311", "cp311", "manylinux_2_25_x86_64"), ("cp311", "cp311", "manylinux_2_26_x86_64"), ("cp311", "cp311", "manylinux_2_27_x86_64"), ("cp311", "cp311", "manylinux_2_28_x86_64"), ("cp311", "cp311", "manylinux_2_29_x86_64"), ("cp311", "cp311", "manylinux_2_30_x86_64"), ("cp311", "cp311", "manylinux_2_31_x86_64"), ("cp311", "cp311", "manylinux_2_32_x86_64"), ("cp311", "cp311", "manylinux_2_33_x86_64"), ("cp311", "cp311", "manylinux_2_34_x86_64"), ("cp311", "cp311", "manylinux_2_35_x86_64"), ("cp311", "cp311", "manylinux_2_36_x86_64"), ("cp311", "cp311", "manylinux_2_37_x86_64"), ("cp311", "cp311", "manylinux_2_38_x86_64"), ("cp311", "cp311", "manylinux_2_5_x86_64"), ("cp311", "cp311", "manylinux_2_6_x86_64"), ("cp311", "cp311", "manylinux_2_7_x86_64"), ("cp311", "cp311", "manylinux_2_8_x86_64"), ("cp311", "cp311", "manylinux_2_9_x86_64"), ("cp311", "none", "linux_x86_64"), ("cp311", "none", "manylinux1_x86_64"), ("cp311", "none", "manylinux2010_x86_64"), ("cp311", "none", "manylinux2014_x86_64"), ("cp311", "none", "manylinux_2_10_x86_64"), ("cp311", "none", "manylinux_2_11_x86_64"), ("cp311", "none", "manylinux_2_12_x86_64"), ("cp311", "none", "manylinux_2_13_x86_64"), ("cp311", "none", "manylinux_2_14_x86_64"), ("cp311", "none", "manylinux_2_15_x86_64"), ("cp311", "none", "manylinux_2_16_x86_64"), ("cp311", "none", "manylinux_2_17_x86_64"), ("cp311", "none", "manylinux_2_18_x86_64"), ("cp311", "none", "manylinux_2_19_x86_64"), ("cp311", "none", "manylinux_2_20_x86_64"), ("cp311", "none", "manylinux_2_21_x86_64"), ("cp311", "none", "manylinux_2_22_x86_64"), ("cp311", "none", "manylinux_2_23_x86_64"), ("cp311", "none", "manylinux_2_24_x86_64"), ("cp311", "none", "manylinux_2_25_x86_64"), ("cp311", "none", "manylinux_2_26_x86_64"), ("cp311", "none", "manylinux_2_27_x86_64"), ("cp311", "none", "manylinux_2_28_x86_64"), ("cp311", "none", "manylinux_2_29_x86_64"), ("cp311", "none", "manylinux_2_30_x86_64"), ("cp311", "none", "manylinux_2_31_x86_64"), ("cp311", "none", "manylinux_2_32_x86_64"), ("cp311", "none", "manylinux_2_33_x86_64"), ("cp311", "none", "manylinux_2_34_x86_64"), ("cp311", "none", "manylinux_2_35_x86_64"), ("cp311", "none", "manylinux_2_36_x86_64"), ("cp311", "none", "manylinux_2_37_x86_64"), ("cp311", "none", "manylinux_2_38_x86_64"), ("cp311", "none", "manylinux_2_5_x86_64"), ("cp311", "none", "manylinux_2_6_x86_64"), ("cp311", "none", "manylinux_2_7_x86_64"), ("cp311", "none", "manylinux_2_8_x86_64"), ("cp311", "none", "manylinux_2_9_x86_64"), ("cp32", "abi3", "linux_x86_64"), ("cp32", "abi3", "manylinux1_x86_64"), ("cp32", "abi3", "manylinux2010_x86_64"), ("cp32", "abi3", "manylinux2014_x86_64"), ("cp32", "abi3", "manylinux_2_10_x86_64"), ("cp32", "abi3", "manylinux_2_11_x86_64"), ("cp32", "abi3", "manylinux_2_12_x86_64"), ("cp32", "abi3", "manylinux_2_13_x86_64"), ("cp32", "abi3", "manylinux_2_14_x86_64"), ("cp32", "abi3", "manylinux_2_15_x86_64"), ("cp32", "abi3", "manylinux_2_16_x86_64"), ("cp32", "abi3", "manylinux_2_17_x86_64"), ("cp32", "abi3", "manylinux_2_18_x86_64"), ("cp32", "abi3", "manylinux_2_19_x86_64"), ("cp32", "abi3", "manylinux_2_20_x86_64"), ("cp32", "abi3", "manylinux_2_21_x86_64"), ("cp32", "abi3", "manylinux_2_22_x86_64"), ("cp32", "abi3", "manylinux_2_23_x86_64"), ("cp32", "abi3", "manylinux_2_24_x86_64"), ("cp32", "abi3", "manylinux_2_25_x86_64"), ("cp32", "abi3", "manylinux_2_26_x86_64"), ("cp32", "abi3", "manylinux_2_27_x86_64"), ("cp32", "abi3", "manylinux_2_28_x86_64"), ("cp32", "abi3", "manylinux_2_29_x86_64"), ("cp32", "abi3", "manylinux_2_30_x86_64"), ("cp32", "abi3", "manylinux_2_31_x86_64"), ("cp32", "abi3", "manylinux_2_32_x86_64"), ("cp32", "abi3", "manylinux_2_33_x86_64"), ("cp32", "abi3", "manylinux_2_34_x86_64"), ("cp32", "abi3", "manylinux_2_35_x86_64"), ("cp32", "abi3", "manylinux_2_36_x86_64"), ("cp32", "abi3", "manylinux_2_37_x86_64"), ("cp32", "abi3", "manylinux_2_38_x86_64"), ("cp32", "abi3", "manylinux_2_5_x86_64"), ("cp32", "abi3", "manylinux_2_6_x86_64"), ("cp32", "abi3", "manylinux_2_7_x86_64"), ("cp32", "abi3", "manylinux_2_8_x86_64"), ("cp32", "abi3", "manylinux_2_9_x86_64"), ("cp33", "abi3", "linux_x86_64"), ("cp33", "abi3", "manylinux1_x86_64"), ("cp33", "abi3", "manylinux2010_x86_64"), ("cp33", "abi3", "manylinux2014_x86_64"), ("cp33", "abi3", "manylinux_2_10_x86_64"), ("cp33", "abi3", "manylinux_2_11_x86_64"), ("cp33", "abi3", "manylinux_2_12_x86_64"), ("cp33", "abi3", "manylinux_2_13_x86_64"), ("cp33", "abi3", "manylinux_2_14_x86_64"), ("cp33", "abi3", "manylinux_2_15_x86_64"), ("cp33", "abi3", "manylinux_2_16_x86_64"), ("cp33", "abi3", "manylinux_2_17_x86_64"), ("cp33", "abi3", "manylinux_2_18_x86_64"), ("cp33", "abi3", "manylinux_2_19_x86_64"), ("cp33", "abi3", "manylinux_2_20_x86_64"), ("cp33", "abi3", "manylinux_2_21_x86_64"), ("cp33", "abi3", "manylinux_2_22_x86_64"), ("cp33", "abi3", "manylinux_2_23_x86_64"), ("cp33", "abi3", "manylinux_2_24_x86_64"), ("cp33", "abi3", "manylinux_2_25_x86_64"), ("cp33", "abi3", "manylinux_2_26_x86_64"), ("cp33", "abi3", "manylinux_2_27_x86_64"), ("cp33", "abi3", "manylinux_2_28_x86_64"), ("cp33", "abi3", "manylinux_2_29_x86_64"), ("cp33", "abi3", "manylinux_2_30_x86_64"), ("cp33", "abi3", "manylinux_2_31_x86_64"), ("cp33", "abi3", "manylinux_2_32_x86_64"), ("cp33", "abi3", "manylinux_2_33_x86_64"), ("cp33", "abi3", "manylinux_2_34_x86_64"), ("cp33", "abi3", "manylinux_2_35_x86_64"), ("cp33", "abi3", "manylinux_2_36_x86_64"), ("cp33", "abi3", "manylinux_2_37_x86_64"), ("cp33", "abi3", "manylinux_2_38_x86_64"), ("cp33", "abi3", "manylinux_2_5_x86_64"), ("cp33", "abi3", "manylinux_2_6_x86_64"), ("cp33", "abi3", "manylinux_2_7_x86_64"), ("cp33", "abi3", "manylinux_2_8_x86_64"), ("cp33", "abi3", "manylinux_2_9_x86_64"), ("cp34", "abi3", "linux_x86_64"), ("cp34", "abi3", "manylinux1_x86_64"), ("cp34", "abi3", "manylinux2010_x86_64"), ("cp34", "abi3", "manylinux2014_x86_64"), ("cp34", "abi3", "manylinux_2_10_x86_64"), ("cp34", "abi3", "manylinux_2_11_x86_64"), ("cp34", "abi3", "manylinux_2_12_x86_64"), ("cp34", "abi3", "manylinux_2_13_x86_64"), ("cp34", "abi3", "manylinux_2_14_x86_64"), ("cp34", "abi3", "manylinux_2_15_x86_64"), ("cp34", "abi3", "manylinux_2_16_x86_64"), ("cp34", "abi3", "manylinux_2_17_x86_64"), ("cp34", "abi3", "manylinux_2_18_x86_64"), ("cp34", "abi3", "manylinux_2_19_x86_64"), ("cp34", "abi3", "manylinux_2_20_x86_64"), ("cp34", "abi3", "manylinux_2_21_x86_64"), ("cp34", "abi3", "manylinux_2_22_x86_64"), ("cp34", "abi3", "manylinux_2_23_x86_64"), ("cp34", "abi3", "manylinux_2_24_x86_64"), ("cp34", "abi3", "manylinux_2_25_x86_64"), ("cp34", "abi3", "manylinux_2_26_x86_64"), ("cp34", "abi3", "manylinux_2_27_x86_64"), ("cp34", "abi3", "manylinux_2_28_x86_64"), ("cp34", "abi3", "manylinux_2_29_x86_64"), ("cp34", "abi3", "manylinux_2_30_x86_64"), ("cp34", "abi3", "manylinux_2_31_x86_64"), ("cp34", "abi3", "manylinux_2_32_x86_64"), ("cp34", "abi3", "manylinux_2_33_x86_64"), ("cp34", "abi3", "manylinux_2_34_x86_64"), ("cp34", "abi3", "manylinux_2_35_x86_64"), ("cp34", "abi3", "manylinux_2_36_x86_64"), ("cp34", "abi3", "manylinux_2_37_x86_64"), ("cp34", "abi3", "manylinux_2_38_x86_64"), ("cp34", "abi3", "manylinux_2_5_x86_64"), ("cp34", "abi3", "manylinux_2_6_x86_64"), ("cp34", "abi3", "manylinux_2_7_x86_64"), ("cp34", "abi3", "manylinux_2_8_x86_64"), ("cp34", "abi3", "manylinux_2_9_x86_64"), ("cp35", "abi3", "linux_x86_64"), ("cp35", "abi3", "manylinux1_x86_64"), ("cp35", "abi3", "manylinux2010_x86_64"), ("cp35", "abi3", "manylinux2014_x86_64"), ("cp35", "abi3", "manylinux_2_10_x86_64"), ("cp35", "abi3", "manylinux_2_11_x86_64"), ("cp35", "abi3", "manylinux_2_12_x86_64"), ("cp35", "abi3", "manylinux_2_13_x86_64"), ("cp35", "abi3", "manylinux_2_14_x86_64"), ("cp35", "abi3", "manylinux_2_15_x86_64"), ("cp35", "abi3", "manylinux_2_16_x86_64"), ("cp35", "abi3", "manylinux_2_17_x86_64"), ("cp35", "abi3", "manylinux_2_18_x86_64"), ("cp35", "abi3", "manylinux_2_19_x86_64"), ("cp35", "abi3", "manylinux_2_20_x86_64"), ("cp35", "abi3", "manylinux_2_21_x86_64"), ("cp35", "abi3", "manylinux_2_22_x86_64"), ("cp35", "abi3", "manylinux_2_23_x86_64"), ("cp35", "abi3", "manylinux_2_24_x86_64"), ("cp35", "abi3", "manylinux_2_25_x86_64"), ("cp35", "abi3", "manylinux_2_26_x86_64"), ("cp35", "abi3", "manylinux_2_27_x86_64"), ("cp35", "abi3", "manylinux_2_28_x86_64"), ("cp35", "abi3", "manylinux_2_29_x86_64"), ("cp35", "abi3", "manylinux_2_30_x86_64"), ("cp35", "abi3", "manylinux_2_31_x86_64"), ("cp35", "abi3", "manylinux_2_32_x86_64"), ("cp35", "abi3", "manylinux_2_33_x86_64"), ("cp35", "abi3", "manylinux_2_34_x86_64"), ("cp35", "abi3", "manylinux_2_35_x86_64"), ("cp35", "abi3", "manylinux_2_36_x86_64"), ("cp35", "abi3", "manylinux_2_37_x86_64"), ("cp35", "abi3", "manylinux_2_38_x86_64"), ("cp35", "abi3", "manylinux_2_5_x86_64"), ("cp35", "abi3", "manylinux_2_6_x86_64"), ("cp35", "abi3", "manylinux_2_7_x86_64"), ("cp35", "abi3", "manylinux_2_8_x86_64"), ("cp35", "abi3", "manylinux_2_9_x86_64"), ("cp36", "abi3", "linux_x86_64"), ("cp36", "abi3", "manylinux1_x86_64"), ("cp36", "abi3", "manylinux2010_x86_64"), ("cp36", "abi3", "manylinux2014_x86_64"), ("cp36", "abi3", "manylinux_2_10_x86_64"), ("cp36", "abi3", "manylinux_2_11_x86_64"), ("cp36", "abi3", "manylinux_2_12_x86_64"), ("cp36", "abi3", "manylinux_2_13_x86_64"), ("cp36", "abi3", "manylinux_2_14_x86_64"), ("cp36", "abi3", "manylinux_2_15_x86_64"), ("cp36", "abi3", "manylinux_2_16_x86_64"), ("cp36", "abi3", "manylinux_2_17_x86_64"), ("cp36", "abi3", "manylinux_2_18_x86_64"), ("cp36", "abi3", "manylinux_2_19_x86_64"), ("cp36", "abi3", "manylinux_2_20_x86_64"), ("cp36", "abi3", "manylinux_2_21_x86_64"), ("cp36", "abi3", "manylinux_2_22_x86_64"), ("cp36", "abi3", "manylinux_2_23_x86_64"), ("cp36", "abi3", "manylinux_2_24_x86_64"), ("cp36", "abi3", "manylinux_2_25_x86_64"), ("cp36", "abi3", "manylinux_2_26_x86_64"), ("cp36", "abi3", "manylinux_2_27_x86_64"), ("cp36", "abi3", "manylinux_2_28_x86_64"), ("cp36", "abi3", "manylinux_2_29_x86_64"), ("cp36", "abi3", "manylinux_2_30_x86_64"), ("cp36", "abi3", "manylinux_2_31_x86_64"), ("cp36", "abi3", "manylinux_2_32_x86_64"), ("cp36", "abi3", "manylinux_2_33_x86_64"), ("cp36", "abi3", "manylinux_2_34_x86_64"), ("cp36", "abi3", "manylinux_2_35_x86_64"), ("cp36", "abi3", "manylinux_2_36_x86_64"), ("cp36", "abi3", "manylinux_2_37_x86_64"), ("cp36", "abi3", "manylinux_2_38_x86_64"), ("cp36", "abi3", "manylinux_2_5_x86_64"), ("cp36", "abi3", "manylinux_2_6_x86_64"), ("cp36", "abi3", "manylinux_2_7_x86_64"), ("cp36", "abi3", "manylinux_2_8_x86_64"), ("cp36", "abi3", "manylinux_2_9_x86_64"), ("cp37", "abi3", "linux_x86_64"), ("cp37", "abi3", "manylinux1_x86_64"), ("cp37", "abi3", "manylinux2010_x86_64"), ("cp37", "abi3", "manylinux2014_x86_64"), ("cp37", "abi3", "manylinux_2_10_x86_64"), ("cp37", "abi3", "manylinux_2_11_x86_64"), ("cp37", "abi3", "manylinux_2_12_x86_64"), ("cp37", "abi3", "manylinux_2_13_x86_64"), ("cp37", "abi3", "manylinux_2_14_x86_64"), ("cp37", "abi3", "manylinux_2_15_x86_64"), ("cp37", "abi3", "manylinux_2_16_x86_64"), ("cp37", "abi3", "manylinux_2_17_x86_64"), ("cp37", "abi3", "manylinux_2_18_x86_64"), ("cp37", "abi3", "manylinux_2_19_x86_64"), ("cp37", "abi3", "manylinux_2_20_x86_64"), ("cp37", "abi3", "manylinux_2_21_x86_64"), ("cp37", "abi3", "manylinux_2_22_x86_64"), ("cp37", "abi3", "manylinux_2_23_x86_64"), ("cp37", "abi3", "manylinux_2_24_x86_64"), ("cp37", "abi3", "manylinux_2_25_x86_64"), ("cp37", "abi3", "manylinux_2_26_x86_64"), ("cp37", "abi3", "manylinux_2_27_x86_64"), ("cp37", "abi3", "manylinux_2_28_x86_64"), ("cp37", "abi3", "manylinux_2_29_x86_64"), ("cp37", "abi3", "manylinux_2_30_x86_64"), ("cp37", "abi3", "manylinux_2_31_x86_64"), ("cp37", "abi3", "manylinux_2_32_x86_64"), ("cp37", "abi3", "manylinux_2_33_x86_64"), ("cp37", "abi3", "manylinux_2_34_x86_64"), ("cp37", "abi3", "manylinux_2_35_x86_64"), ("cp37", "abi3", "manylinux_2_36_x86_64"), ("cp37", "abi3", "manylinux_2_37_x86_64"), ("cp37", "abi3", "manylinux_2_38_x86_64"), ("cp37", "abi3", "manylinux_2_5_x86_64"), ("cp37", "abi3", "manylinux_2_6_x86_64"), ("cp37", "abi3", "manylinux_2_7_x86_64"), ("cp37", "abi3", "manylinux_2_8_x86_64"), ("cp37", "abi3", "manylinux_2_9_x86_64"), ("cp38", "abi3", "linux_x86_64"), ("cp38", "abi3", "manylinux1_x86_64"), ("cp38", "abi3", "manylinux2010_x86_64"), ("cp38", "abi3", "manylinux2014_x86_64"), ("cp38", "abi3", "manylinux_2_10_x86_64"), ("cp38", "abi3", "manylinux_2_11_x86_64"), ("cp38", "abi3", "manylinux_2_12_x86_64"), ("cp38", "abi3", "manylinux_2_13_x86_64"), ("cp38", "abi3", "manylinux_2_14_x86_64"), ("cp38", "abi3", "manylinux_2_15_x86_64"), ("cp38", "abi3", "manylinux_2_16_x86_64"), ("cp38", "abi3", "manylinux_2_17_x86_64"), ("cp38", "abi3", "manylinux_2_18_x86_64"), ("cp38", "abi3", "manylinux_2_19_x86_64"), ("cp38", "abi3", "manylinux_2_20_x86_64"), ("cp38", "abi3", "manylinux_2_21_x86_64"), ("cp38", "abi3", "manylinux_2_22_x86_64"), ("cp38", "abi3", "manylinux_2_23_x86_64"), ("cp38", "abi3", "manylinux_2_24_x86_64"), ("cp38", "abi3", "manylinux_2_25_x86_64"), ("cp38", "abi3", "manylinux_2_26_x86_64"), ("cp38", "abi3", "manylinux_2_27_x86_64"), ("cp38", "abi3", "manylinux_2_28_x86_64"), ("cp38", "abi3", "manylinux_2_29_x86_64"), ("cp38", "abi3", "manylinux_2_30_x86_64"), ("cp38", "abi3", "manylinux_2_31_x86_64"), ("cp38", "abi3", "manylinux_2_32_x86_64"), ("cp38", "abi3", "manylinux_2_33_x86_64"), ("cp38", "abi3", "manylinux_2_34_x86_64"), ("cp38", "abi3", "manylinux_2_35_x86_64"), ("cp38", "abi3", "manylinux_2_36_x86_64"), ("cp38", "abi3", "manylinux_2_37_x86_64"), ("cp38", "abi3", "manylinux_2_38_x86_64"), ("cp38", "abi3", "manylinux_2_5_x86_64"), ("cp38", "abi3", "manylinux_2_6_x86_64"), ("cp38", "abi3", "manylinux_2_7_x86_64"), ("cp38", "abi3", "manylinux_2_8_x86_64"), ("cp38", "abi3", "manylinux_2_9_x86_64"), ("cp39", "abi3", "linux_x86_64"), ("cp39", "abi3", "manylinux1_x86_64"), ("cp39", "abi3", "manylinux2010_x86_64"), ("cp39", "abi3", "manylinux2014_x86_64"), ("cp39", "abi3", "manylinux_2_10_x86_64"), ("cp39", "abi3", "manylinux_2_11_x86_64"), ("cp39", "abi3", "manylinux_2_12_x86_64"), ("cp39", "abi3", "manylinux_2_13_x86_64"), ("cp39", "abi3", "manylinux_2_14_x86_64"), ("cp39", "abi3", "manylinux_2_15_x86_64"), ("cp39", "abi3", "manylinux_2_16_x86_64"), ("cp39", "abi3", "manylinux_2_17_x86_64"), ("cp39", "abi3", "manylinux_2_18_x86_64"), ("cp39", "abi3", "manylinux_2_19_x86_64"), ("cp39", "abi3", "manylinux_2_20_x86_64"), ("cp39", "abi3", "manylinux_2_21_x86_64"), ("cp39", "abi3", "manylinux_2_22_x86_64"), ("cp39", "abi3", "manylinux_2_23_x86_64"), ("cp39", "abi3", "manylinux_2_24_x86_64"), ("cp39", "abi3", "manylinux_2_25_x86_64"), ("cp39", "abi3", "manylinux_2_26_x86_64"), ("cp39", "abi3", "manylinux_2_27_x86_64"), ("cp39", "abi3", "manylinux_2_28_x86_64"), ("cp39", "abi3", "manylinux_2_29_x86_64"), ("cp39", "abi3", "manylinux_2_30_x86_64"), ("cp39", "abi3", "manylinux_2_31_x86_64"), ("cp39", "abi3", "manylinux_2_32_x86_64"), ("cp39", "abi3", "manylinux_2_33_x86_64"), ("cp39", "abi3", "manylinux_2_34_x86_64"), ("cp39", "abi3", "manylinux_2_35_x86_64"), ("cp39", "abi3", "manylinux_2_36_x86_64"), ("cp39", "abi3", "manylinux_2_37_x86_64"), ("cp39", "abi3", "manylinux_2_38_x86_64"), ("cp39", "abi3", "manylinux_2_5_x86_64"), ("cp39", "abi3", "manylinux_2_6_x86_64"), ("cp39", "abi3", "manylinux_2_7_x86_64"), ("cp39", "abi3", "manylinux_2_8_x86_64"), ("cp39", "abi3", "manylinux_2_9_x86_64"), ("py3", "none", "any"), ("py3", "none", "linux_x86_64"), ("py3", "none", "manylinux1_x86_64"), ("py3", "none", "manylinux2010_x86_64"), ("py3", "none", "manylinux2014_x86_64"), ("py3", "none", "manylinux_2_10_x86_64"), ("py3", "none", "manylinux_2_11_x86_64"), ("py3", "none", "manylinux_2_12_x86_64"), ("py3", "none", "manylinux_2_13_x86_64"), ("py3", "none", "manylinux_2_14_x86_64"), ("py3", "none", "manylinux_2_15_x86_64"), ("py3", "none", "manylinux_2_16_x86_64"), ("py3", "none", "manylinux_2_17_x86_64"), ("py3", "none", "manylinux_2_18_x86_64"), ("py3", "none", "manylinux_2_19_x86_64"), ("py3", "none", "manylinux_2_20_x86_64"), ("py3", "none", "manylinux_2_21_x86_64"), ("py3", "none", "manylinux_2_22_x86_64"), ("py3", "none", "manylinux_2_23_x86_64"), ("py3", "none", "manylinux_2_24_x86_64"), ("py3", "none", "manylinux_2_25_x86_64"), ("py3", "none", "manylinux_2_26_x86_64"), ("py3", "none", "manylinux_2_27_x86_64"), ("py3", "none", "manylinux_2_28_x86_64"), ("py3", "none", "manylinux_2_29_x86_64"), ("py3", "none", "manylinux_2_30_x86_64"), ("py3", "none", "manylinux_2_31_x86_64"), ("py3", "none", "manylinux_2_32_x86_64"), ("py3", "none", "manylinux_2_33_x86_64"), ("py3", "none", "manylinux_2_34_x86_64"), ("py3", "none", "manylinux_2_35_x86_64"), ("py3", "none", "manylinux_2_36_x86_64"), ("py3", "none", "manylinux_2_37_x86_64"), ("py3", "none", "manylinux_2_38_x86_64"), ("py3", "none", "manylinux_2_5_x86_64"), ("py3", "none", "manylinux_2_6_x86_64"), ("py3", "none", "manylinux_2_7_x86_64"), ("py3", "none", "manylinux_2_8_x86_64"), ("py3", "none", "manylinux_2_9_x86_64"), ("py30", "none", "any"), ("py30", "none", "linux_x86_64"), ("py30", "none", "manylinux1_x86_64"), ("py30", "none", "manylinux2010_x86_64"), ("py30", "none", "manylinux2014_x86_64"), ("py30", "none", "manylinux_2_10_x86_64"), ("py30", "none", "manylinux_2_11_x86_64"), ("py30", "none", "manylinux_2_12_x86_64"), ("py30", "none", "manylinux_2_13_x86_64"), ("py30", "none", "manylinux_2_14_x86_64"), ("py30", "none", "manylinux_2_15_x86_64"), ("py30", "none", "manylinux_2_16_x86_64"), ("py30", "none", "manylinux_2_17_x86_64"), ("py30", "none", "manylinux_2_18_x86_64"), ("py30", "none", "manylinux_2_19_x86_64"), ("py30", "none", "manylinux_2_20_x86_64"), ("py30", "none", "manylinux_2_21_x86_64"), ("py30", "none", "manylinux_2_22_x86_64"), ("py30", "none", "manylinux_2_23_x86_64"), ("py30", "none", "manylinux_2_24_x86_64"), ("py30", "none", "manylinux_2_25_x86_64"), ("py30", "none", "manylinux_2_26_x86_64"), ("py30", "none", "manylinux_2_27_x86_64"), ("py30", "none", "manylinux_2_28_x86_64"), ("py30", "none", "manylinux_2_29_x86_64"), ("py30", "none", "manylinux_2_30_x86_64"), ("py30", "none", "manylinux_2_31_x86_64"), ("py30", "none", "manylinux_2_32_x86_64"), ("py30", "none", "manylinux_2_33_x86_64"), ("py30", "none", "manylinux_2_34_x86_64"), ("py30", "none", "manylinux_2_35_x86_64"), ("py30", "none", "manylinux_2_36_x86_64"), ("py30", "none", "manylinux_2_37_x86_64"), ("py30", "none", "manylinux_2_38_x86_64"), ("py30", "none", "manylinux_2_5_x86_64"), ("py30", "none", "manylinux_2_6_x86_64"), ("py30", "none", "manylinux_2_7_x86_64"), ("py30", "none", "manylinux_2_8_x86_64"), ("py30", "none", "manylinux_2_9_x86_64"), ("py31", "none", "any"), ("py31", "none", "linux_x86_64"), ("py31", "none", "manylinux1_x86_64"), ("py31", "none", "manylinux2010_x86_64"), ("py31", "none", "manylinux2014_x86_64"), ("py31", "none", "manylinux_2_10_x86_64"), ("py31", "none", "manylinux_2_11_x86_64"), ("py31", "none", "manylinux_2_12_x86_64"), ("py31", "none", "manylinux_2_13_x86_64"), ("py31", "none", "manylinux_2_14_x86_64"), ("py31", "none", "manylinux_2_15_x86_64"), ("py31", "none", "manylinux_2_16_x86_64"), ("py31", "none", "manylinux_2_17_x86_64"), ("py31", "none", "manylinux_2_18_x86_64"), ("py31", "none", "manylinux_2_19_x86_64"), ("py31", "none", "manylinux_2_20_x86_64"), ("py31", "none", "manylinux_2_21_x86_64"), ("py31", "none", "manylinux_2_22_x86_64"), ("py31", "none", "manylinux_2_23_x86_64"), ("py31", "none", "manylinux_2_24_x86_64"), ("py31", "none", "manylinux_2_25_x86_64"), ("py31", "none", "manylinux_2_26_x86_64"), ("py31", "none", "manylinux_2_27_x86_64"), ("py31", "none", "manylinux_2_28_x86_64"), ("py31", "none", "manylinux_2_29_x86_64"), ("py31", "none", "manylinux_2_30_x86_64"), ("py31", "none", "manylinux_2_31_x86_64"), ("py31", "none", "manylinux_2_32_x86_64"), ("py31", "none", "manylinux_2_33_x86_64"), ("py31", "none", "manylinux_2_34_x86_64"), ("py31", "none", "manylinux_2_35_x86_64"), ("py31", "none", "manylinux_2_36_x86_64"), ("py31", "none", "manylinux_2_37_x86_64"), ("py31", "none", "manylinux_2_38_x86_64"), ("py31", "none", "manylinux_2_5_x86_64"), ("py31", "none", "manylinux_2_6_x86_64"), ("py31", "none", "manylinux_2_7_x86_64"), ("py31", "none", "manylinux_2_8_x86_64"), ("py31", "none", "manylinux_2_9_x86_64"), ("py310", "none", "any"), ("py310", "none", "linux_x86_64"), ("py310", "none", "manylinux1_x86_64"), ("py310", "none", "manylinux2010_x86_64"), ("py310", "none", "manylinux2014_x86_64"), ("py310", "none", "manylinux_2_10_x86_64"), ("py310", "none", "manylinux_2_11_x86_64"), ("py310", "none", "manylinux_2_12_x86_64"), ("py310", "none", "manylinux_2_13_x86_64"), ("py310", "none", "manylinux_2_14_x86_64"), ("py310", "none", "manylinux_2_15_x86_64"), ("py310", "none", "manylinux_2_16_x86_64"), ("py310", "none", "manylinux_2_17_x86_64"), ("py310", "none", "manylinux_2_18_x86_64"), ("py310", "none", "manylinux_2_19_x86_64"), ("py310", "none", "manylinux_2_20_x86_64"), ("py310", "none", "manylinux_2_21_x86_64"), ("py310", "none", "manylinux_2_22_x86_64"), ("py310", "none", "manylinux_2_23_x86_64"), ("py310", "none", "manylinux_2_24_x86_64"), ("py310", "none", "manylinux_2_25_x86_64"), ("py310", "none", "manylinux_2_26_x86_64"), ("py310", "none", "manylinux_2_27_x86_64"), ("py310", "none", "manylinux_2_28_x86_64"), ("py310", "none", "manylinux_2_29_x86_64"), ("py310", "none", "manylinux_2_30_x86_64"), ("py310", "none", "manylinux_2_31_x86_64"), ("py310", "none", "manylinux_2_32_x86_64"), ("py310", "none", "manylinux_2_33_x86_64"), ("py310", "none", "manylinux_2_34_x86_64"), ("py310", "none", "manylinux_2_35_x86_64"), ("py310", "none", "manylinux_2_36_x86_64"), ("py310", "none", "manylinux_2_37_x86_64"), ("py310", "none", "manylinux_2_38_x86_64"), ("py310", "none", "manylinux_2_5_x86_64"), ("py310", "none", "manylinux_2_6_x86_64"), ("py310", "none", "manylinux_2_7_x86_64"), ("py310", "none", "manylinux_2_8_x86_64"), ("py310", "none", "manylinux_2_9_x86_64"), ("py311", "none", "any"), ("py311", "none", "linux_x86_64"), ("py311", "none", "manylinux1_x86_64"), ("py311", "none", "manylinux2010_x86_64"), ("py311", "none", "manylinux2014_x86_64"), ("py311", "none", "manylinux_2_10_x86_64"), ("py311", "none", "manylinux_2_11_x86_64"), ("py311", "none", "manylinux_2_12_x86_64"), ("py311", "none", "manylinux_2_13_x86_64"), ("py311", "none", "manylinux_2_14_x86_64"), ("py311", "none", "manylinux_2_15_x86_64"), ("py311", "none", "manylinux_2_16_x86_64"), ("py311", "none", "manylinux_2_17_x86_64"), ("py311", "none", "manylinux_2_18_x86_64"), ("py311", "none", "manylinux_2_19_x86_64"), ("py311", "none", "manylinux_2_20_x86_64"), ("py311", "none", "manylinux_2_21_x86_64"), ("py311", "none", "manylinux_2_22_x86_64"), ("py311", "none", "manylinux_2_23_x86_64"), ("py311", "none", "manylinux_2_24_x86_64"), ("py311", "none", "manylinux_2_25_x86_64"), ("py311", "none", "manylinux_2_26_x86_64"), ("py311", "none", "manylinux_2_27_x86_64"), ("py311", "none", "manylinux_2_28_x86_64"), ("py311", "none", "manylinux_2_29_x86_64"), ("py311", "none", "manylinux_2_30_x86_64"), ("py311", "none", "manylinux_2_31_x86_64"), ("py311", "none", "manylinux_2_32_x86_64"), ("py311", "none", "manylinux_2_33_x86_64"), ("py311", "none", "manylinux_2_34_x86_64"), ("py311", "none", "manylinux_2_35_x86_64"), ("py311", "none", "manylinux_2_36_x86_64"), ("py311", "none", "manylinux_2_37_x86_64"), ("py311", "none", "manylinux_2_38_x86_64"), ("py311", "none", "manylinux_2_5_x86_64"), ("py311", "none", "manylinux_2_6_x86_64"), ("py311", "none", "manylinux_2_7_x86_64"), ("py311", "none", "manylinux_2_8_x86_64"), ("py311", "none", "manylinux_2_9_x86_64"), ("py32", "none", "any"), ("py32", "none", "linux_x86_64"), ("py32", "none", "manylinux1_x86_64"), ("py32", "none", "manylinux2010_x86_64"), ("py32", "none", "manylinux2014_x86_64"), ("py32", "none", "manylinux_2_10_x86_64"), ("py32", "none", "manylinux_2_11_x86_64"), ("py32", "none", "manylinux_2_12_x86_64"), ("py32", "none", "manylinux_2_13_x86_64"), ("py32", "none", "manylinux_2_14_x86_64"), ("py32", "none", "manylinux_2_15_x86_64"), ("py32", "none", "manylinux_2_16_x86_64"), ("py32", "none", "manylinux_2_17_x86_64"), ("py32", "none", "manylinux_2_18_x86_64"), ("py32", "none", "manylinux_2_19_x86_64"), ("py32", "none", "manylinux_2_20_x86_64"), ("py32", "none", "manylinux_2_21_x86_64"), ("py32", "none", "manylinux_2_22_x86_64"), ("py32", "none", "manylinux_2_23_x86_64"), ("py32", "none", "manylinux_2_24_x86_64"), ("py32", "none", "manylinux_2_25_x86_64"), ("py32", "none", "manylinux_2_26_x86_64"), ("py32", "none", "manylinux_2_27_x86_64"), ("py32", "none", "manylinux_2_28_x86_64"), ("py32", "none", "manylinux_2_29_x86_64"), ("py32", "none", "manylinux_2_30_x86_64"), ("py32", "none", "manylinux_2_31_x86_64"), ("py32", "none", "manylinux_2_32_x86_64"), ("py32", "none", "manylinux_2_33_x86_64"), ("py32", "none", "manylinux_2_34_x86_64"), ("py32", "none", "manylinux_2_35_x86_64"), ("py32", "none", "manylinux_2_36_x86_64"), ("py32", "none", "manylinux_2_37_x86_64"), ("py32", "none", "manylinux_2_38_x86_64"), ("py32", "none", "manylinux_2_5_x86_64"), ("py32", "none", "manylinux_2_6_x86_64"), ("py32", "none", "manylinux_2_7_x86_64"), ("py32", "none", "manylinux_2_8_x86_64"), ("py32", "none", "manylinux_2_9_x86_64"), ("py33", "none", "any"), ("py33", "none", "linux_x86_64"), ("py33", "none", "manylinux1_x86_64"), ("py33", "none", "manylinux2010_x86_64"), ("py33", "none", "manylinux2014_x86_64"), ("py33", "none", "manylinux_2_10_x86_64"), ("py33", "none", "manylinux_2_11_x86_64"), ("py33", "none", "manylinux_2_12_x86_64"), ("py33", "none", "manylinux_2_13_x86_64"), ("py33", "none", "manylinux_2_14_x86_64"), ("py33", "none", "manylinux_2_15_x86_64"), ("py33", "none", "manylinux_2_16_x86_64"), ("py33", "none", "manylinux_2_17_x86_64"), ("py33", "none", "manylinux_2_18_x86_64"), ("py33", "none", "manylinux_2_19_x86_64"), ("py33", "none", "manylinux_2_20_x86_64"), ("py33", "none", "manylinux_2_21_x86_64"), ("py33", "none", "manylinux_2_22_x86_64"), ("py33", "none", "manylinux_2_23_x86_64"), ("py33", "none", "manylinux_2_24_x86_64"), ("py33", "none", "manylinux_2_25_x86_64"), ("py33", "none", "manylinux_2_26_x86_64"), ("py33", "none", "manylinux_2_27_x86_64"), ("py33", "none", "manylinux_2_28_x86_64"), ("py33", "none", "manylinux_2_29_x86_64"), ("py33", "none", "manylinux_2_30_x86_64"), ("py33", "none", "manylinux_2_31_x86_64"), ("py33", "none", "manylinux_2_32_x86_64"), ("py33", "none", "manylinux_2_33_x86_64"), ("py33", "none", "manylinux_2_34_x86_64"), ("py33", "none", "manylinux_2_35_x86_64"), ("py33", "none", "manylinux_2_36_x86_64"), ("py33", "none", "manylinux_2_37_x86_64"), ("py33", "none", "manylinux_2_38_x86_64"), ("py33", "none", "manylinux_2_5_x86_64"), ("py33", "none", "manylinux_2_6_x86_64"), ("py33", "none", "manylinux_2_7_x86_64"), ("py33", "none", "manylinux_2_8_x86_64"), ("py33", "none", "manylinux_2_9_x86_64"), ("py34", "none", "any"), ("py34", "none", "linux_x86_64"), ("py34", "none", "manylinux1_x86_64"), ("py34", "none", "manylinux2010_x86_64"), ("py34", "none", "manylinux2014_x86_64"), ("py34", "none", "manylinux_2_10_x86_64"), ("py34", "none", "manylinux_2_11_x86_64"), ("py34", "none", "manylinux_2_12_x86_64"), ("py34", "none", "manylinux_2_13_x86_64"), ("py34", "none", "manylinux_2_14_x86_64"), ("py34", "none", "manylinux_2_15_x86_64"), ("py34", "none", "manylinux_2_16_x86_64"), ("py34", "none", "manylinux_2_17_x86_64"), ("py34", "none", "manylinux_2_18_x86_64"), ("py34", "none", "manylinux_2_19_x86_64"), ("py34", "none", "manylinux_2_20_x86_64"), ("py34", "none", "manylinux_2_21_x86_64"), ("py34", "none", "manylinux_2_22_x86_64"), ("py34", "none", "manylinux_2_23_x86_64"), ("py34", "none", "manylinux_2_24_x86_64"), ("py34", "none", "manylinux_2_25_x86_64"), ("py34", "none", "manylinux_2_26_x86_64"), ("py34", "none", "manylinux_2_27_x86_64"), ("py34", "none", "manylinux_2_28_x86_64"), ("py34", "none", "manylinux_2_29_x86_64"), ("py34", "none", "manylinux_2_30_x86_64"), ("py34", "none", "manylinux_2_31_x86_64"), ("py34", "none", "manylinux_2_32_x86_64"), ("py34", "none", "manylinux_2_33_x86_64"), ("py34", "none", "manylinux_2_34_x86_64"), ("py34", "none", "manylinux_2_35_x86_64"), ("py34", "none", "manylinux_2_36_x86_64"), ("py34", "none", "manylinux_2_37_x86_64"), ("py34", "none", "manylinux_2_38_x86_64"), ("py34", "none", "manylinux_2_5_x86_64"), ("py34", "none", "manylinux_2_6_x86_64"), ("py34", "none", "manylinux_2_7_x86_64"), ("py34", "none", "manylinux_2_8_x86_64"), ("py34", "none", "manylinux_2_9_x86_64"), ("py35", "none", "any"), ("py35", "none", "linux_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-platform/src/lib.rs | crates/uv-platform/src/lib.rs | //! Platform detection for operating system, architecture, and libc.
use std::cmp;
use std::fmt;
use std::str::FromStr;
use target_lexicon::Architecture;
use thiserror::Error;
use tracing::trace;
pub use crate::arch::{Arch, ArchVariant};
pub use crate::libc::{Libc, LibcDetectionError, LibcVersion};
pub use crate::os::Os;
mod arch;
mod cpuinfo;
mod libc;
mod os;
#[derive(Error, Debug)]
pub enum Error {
#[error("Unknown operating system: {0}")]
UnknownOs(String),
#[error("Unknown architecture: {0}")]
UnknownArch(String),
#[error("Unknown libc environment: {0}")]
UnknownLibc(String),
#[error("Unsupported variant `{0}` for architecture `{1}`")]
UnsupportedVariant(String, String),
#[error(transparent)]
LibcDetectionError(#[from] crate::libc::LibcDetectionError),
#[error("Invalid platform format: {0}")]
InvalidPlatformFormat(String),
}
/// A platform identifier that combines operating system, architecture, and libc.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Platform {
pub os: Os,
pub arch: Arch,
pub libc: Libc,
}
impl Platform {
/// Create a new platform with the given components.
pub fn new(os: Os, arch: Arch, libc: Libc) -> Self {
Self { os, arch, libc }
}
/// Create a platform from string parts (os, arch, libc).
pub fn from_parts(os: &str, arch: &str, libc: &str) -> Result<Self, Error> {
Ok(Self {
os: Os::from_str(os)?,
arch: Arch::from_str(arch)?,
libc: Libc::from_str(libc)?,
})
}
/// Detect the platform from the current environment.
pub fn from_env() -> Result<Self, Error> {
let os = Os::from_env();
let arch = Arch::from_env();
let libc = Libc::from_env()?;
Ok(Self { os, arch, libc })
}
/// Check if this platform supports running another platform.
pub fn supports(&self, other: &Self) -> bool {
// If platforms are exactly equal, they're compatible
if self == other {
return true;
}
if !self.os.supports(other.os) {
trace!(
"Operating system `{}` is not compatible with `{}`",
self.os, other.os
);
return false;
}
// Libc must match exactly, unless we're on emscripten β in which case it doesn't matter
if self.libc != other.libc && !(other.os.is_emscripten() || self.os.is_emscripten()) {
trace!(
"Libc `{}` is not compatible with `{}`",
self.libc, other.libc
);
return false;
}
// Check architecture compatibility
if self.arch == other.arch {
return true;
}
#[allow(clippy::unnested_or_patterns)]
if self.os.is_windows()
&& matches!(
(self.arch.family(), other.arch.family()),
// 32-bit x86 binaries work fine on 64-bit x86 windows
(Architecture::X86_64, Architecture::X86_32(_)) |
// Both 32-bit and 64-bit binaries are transparently emulated on aarch64 windows
(Architecture::Aarch64(_), Architecture::X86_64) |
(Architecture::Aarch64(_), Architecture::X86_32(_))
)
{
return true;
}
if self.os.is_macos()
&& matches!(
(self.arch.family(), other.arch.family()),
// macOS aarch64 runs emulated x86_64 binaries transparently if you have Rosetta
// installed. We don't try to be clever and check if that's the case here,
// we just assume that if x86_64 distributions are available, they're usable.
(Architecture::Aarch64(_), Architecture::X86_64)
)
{
return true;
}
// Wasm32 can run on any architecture
if other.arch.is_wasm() {
return true;
}
// TODO: Allow inequal variants, as we don't implement variant support checks yet.
// See https://github.com/astral-sh/uv/pull/9788
// For now, allow same architecture family as a fallback
if self.arch.family() != other.arch.family() {
return false;
}
true
}
/// Convert this platform to a `cargo-dist` style triple string.
pub fn as_cargo_dist_triple(&self) -> String {
use target_lexicon::{
Architecture, ArmArchitecture, OperatingSystem, Riscv64Architecture, X86_32Architecture,
};
let Self { os, arch, libc } = &self;
let arch_name = match arch.family() {
// Special cases where Display doesn't match target triple
Architecture::X86_32(X86_32Architecture::I686) => "i686".to_string(),
Architecture::Riscv64(Riscv64Architecture::Riscv64) => "riscv64gc".to_string(),
_ => arch.to_string(),
};
let vendor = match &**os {
OperatingSystem::Darwin(_) => "apple",
OperatingSystem::Windows => "pc",
_ => "unknown",
};
let os_name = match &**os {
OperatingSystem::Darwin(_) => "darwin",
_ => &os.to_string(),
};
let abi = match (&**os, libc) {
(OperatingSystem::Windows, _) => Some("msvc".to_string()),
(OperatingSystem::Linux, Libc::Some(env)) => Some({
// Special suffix for ARM with hardware float
if matches!(arch.family(), Architecture::Arm(ArmArchitecture::Armv7)) {
format!("{env}eabihf")
} else {
env.to_string()
}
}),
_ => None,
};
format!(
"{arch_name}-{vendor}-{os_name}{abi}",
abi = abi.map(|abi| format!("-{abi}")).unwrap_or_default()
)
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{}", self.os, self.arch, self.libc)
}
}
impl FromStr for Platform {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 3 {
return Err(Error::InvalidPlatformFormat(format!(
"expected exactly 3 parts separated by '-', got {}",
parts.len()
)));
}
Self::from_parts(parts[0], parts[1], parts[2])
}
}
impl Ord for Platform {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.os
.to_string()
.cmp(&other.os.to_string())
// Then architecture
.then_with(|| {
if self.arch.family == other.arch.family {
return self.arch.variant.cmp(&other.arch.variant);
}
// For the time being, manually make aarch64 windows disfavored on its own host
// platform, because most packages don't have wheels for aarch64 windows, making
// emulation more useful than native execution!
//
// The reason we do this in "sorting" and not "supports" is so that we don't
// *refuse* to use an aarch64 windows pythons if they happen to be installed and
// nothing else is available.
//
// Similarly if someone manually requests an aarch64 windows install, we should
// respect that request (this is the way users should "override" this behaviour).
let preferred = if self.os.is_windows() {
Arch {
family: target_lexicon::Architecture::X86_64,
variant: None,
}
} else {
// Prefer native architectures
Arch::from_env()
};
match (
self.arch.family == preferred.family,
other.arch.family == preferred.family,
) {
(true, true) => unreachable!(),
(true, false) => cmp::Ordering::Less,
(false, true) => cmp::Ordering::Greater,
(false, false) => {
// Both non-preferred, fallback to lexicographic order
self.arch
.family
.to_string()
.cmp(&other.arch.family.to_string())
}
}
})
// Finally compare libc
.then_with(|| self.libc.to_string().cmp(&other.libc.to_string()))
}
}
impl PartialOrd for Platform {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl From<&uv_platform_tags::Platform> for Platform {
fn from(value: &uv_platform_tags::Platform) -> Self {
Self {
os: Os::from(value.os()),
arch: Arch::from(&value.arch()),
libc: Libc::from(value.os()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_platform_display() {
let platform = Platform {
os: Os::from_str("linux").unwrap(),
arch: Arch::from_str("x86_64").unwrap(),
libc: Libc::from_str("gnu").unwrap(),
};
assert_eq!(platform.to_string(), "linux-x86_64-gnu");
}
#[test]
fn test_platform_from_str() {
let platform = Platform::from_str("macos-aarch64-none").unwrap();
assert_eq!(platform.os.to_string(), "macos");
assert_eq!(platform.arch.to_string(), "aarch64");
assert_eq!(platform.libc.to_string(), "none");
}
#[test]
fn test_platform_from_parts() {
let platform = Platform::from_parts("linux", "x86_64", "gnu").unwrap();
assert_eq!(platform.os.to_string(), "linux");
assert_eq!(platform.arch.to_string(), "x86_64");
assert_eq!(platform.libc.to_string(), "gnu");
// Test with arch variant
let platform = Platform::from_parts("linux", "x86_64_v3", "musl").unwrap();
assert_eq!(platform.os.to_string(), "linux");
assert_eq!(platform.arch.to_string(), "x86_64_v3");
assert_eq!(platform.libc.to_string(), "musl");
// Test error cases
assert!(Platform::from_parts("invalid_os", "x86_64", "gnu").is_err());
assert!(Platform::from_parts("linux", "invalid_arch", "gnu").is_err());
assert!(Platform::from_parts("linux", "x86_64", "invalid_libc").is_err());
}
#[test]
fn test_platform_from_str_with_arch_variant() {
let platform = Platform::from_str("linux-x86_64_v3-gnu").unwrap();
assert_eq!(platform.os.to_string(), "linux");
assert_eq!(platform.arch.to_string(), "x86_64_v3");
assert_eq!(platform.libc.to_string(), "gnu");
}
#[test]
fn test_platform_from_str_error() {
// Too few parts
assert!(Platform::from_str("linux-x86_64").is_err());
assert!(Platform::from_str("invalid").is_err());
// Too many parts (would have been accepted by the old code)
assert!(Platform::from_str("linux-x86-64-gnu").is_err());
assert!(Platform::from_str("linux-x86_64-gnu-extra").is_err());
}
#[test]
fn test_platform_sorting_os_precedence() {
let linux = Platform::from_str("linux-x86_64-gnu").unwrap();
let macos = Platform::from_str("macos-x86_64-none").unwrap();
let windows = Platform::from_str("windows-x86_64-none").unwrap();
// OS sorting takes precedence (alphabetical)
assert!(linux < macos);
assert!(macos < windows);
}
#[test]
fn test_platform_sorting_libc() {
let gnu = Platform::from_str("linux-x86_64-gnu").unwrap();
let musl = Platform::from_str("linux-x86_64-musl").unwrap();
// Same OS and arch, libc comparison (alphabetical)
assert!(gnu < musl);
}
#[test]
fn test_platform_sorting_arch_linux() {
// Test that Linux prefers the native architecture
use crate::arch::test_support::{aarch64, run_with_arch, x86_64};
let linux_x86_64 = Platform::from_str("linux-x86_64-gnu").unwrap();
let linux_aarch64 = Platform::from_str("linux-aarch64-gnu").unwrap();
// On x86_64 Linux, x86_64 should be preferred over aarch64
run_with_arch(x86_64(), || {
assert!(linux_x86_64 < linux_aarch64);
});
// On aarch64 Linux, aarch64 should be preferred over x86_64
run_with_arch(aarch64(), || {
assert!(linux_aarch64 < linux_x86_64);
});
}
#[test]
fn test_platform_sorting_arch_macos() {
use crate::arch::test_support::{aarch64, run_with_arch, x86_64};
let macos_x86_64 = Platform::from_str("macos-x86_64-none").unwrap();
let macos_aarch64 = Platform::from_str("macos-aarch64-none").unwrap();
// On x86_64 macOS, x86_64 should be preferred over aarch64
run_with_arch(x86_64(), || {
assert!(macos_x86_64 < macos_aarch64);
});
// On aarch64 macOS, aarch64 should be preferred over x86_64
run_with_arch(aarch64(), || {
assert!(macos_aarch64 < macos_x86_64);
});
}
#[test]
fn test_platform_supports() {
let native = Platform::from_str("linux-x86_64-gnu").unwrap();
let same = Platform::from_str("linux-x86_64-gnu").unwrap();
let different_arch = Platform::from_str("linux-aarch64-gnu").unwrap();
let different_os = Platform::from_str("macos-x86_64-none").unwrap();
let different_libc = Platform::from_str("linux-x86_64-musl").unwrap();
// Exact match
assert!(native.supports(&same));
// Different OS - not supported
assert!(!native.supports(&different_os));
// Different libc - not supported
assert!(!native.supports(&different_libc));
// Different architecture but same family
// x86_64 doesn't support aarch64 on Linux
assert!(!native.supports(&different_arch));
// Test architecture family support
let x86_64_v2 = Platform::from_str("linux-x86_64_v2-gnu").unwrap();
let x86_64_v3 = Platform::from_str("linux-x86_64_v3-gnu").unwrap();
// These have the same architecture family (both x86_64)
assert_eq!(native.arch.family(), x86_64_v2.arch.family());
assert_eq!(native.arch.family(), x86_64_v3.arch.family());
// Due to the family check, these should support each other
assert!(native.supports(&x86_64_v2));
assert!(native.supports(&x86_64_v3));
}
#[test]
fn test_windows_aarch64_platform_sorting() {
// Test that on Windows, x86_64 is preferred over aarch64
let windows_x86_64 = Platform::from_str("windows-x86_64-none").unwrap();
let windows_aarch64 = Platform::from_str("windows-aarch64-none").unwrap();
// x86_64 should sort before aarch64 on Windows (preferred)
assert!(windows_x86_64 < windows_aarch64);
// Test with multiple Windows platforms
let mut platforms = [
Platform::from_str("windows-aarch64-none").unwrap(),
Platform::from_str("windows-x86_64-none").unwrap(),
Platform::from_str("windows-x86-none").unwrap(),
];
platforms.sort();
// After sorting on Windows, the order should be: x86_64 (preferred), aarch64, x86
// x86_64 is preferred on Windows regardless of native architecture
assert_eq!(platforms[0].arch.to_string(), "x86_64");
assert_eq!(platforms[1].arch.to_string(), "aarch64");
assert_eq!(platforms[2].arch.to_string(), "x86");
}
#[test]
fn test_windows_sorting_always_prefers_x86_64() {
// Test that Windows always prefers x86_64 regardless of host architecture
use crate::arch::test_support::{aarch64, run_with_arch, x86_64};
let windows_x86_64 = Platform::from_str("windows-x86_64-none").unwrap();
let windows_aarch64 = Platform::from_str("windows-aarch64-none").unwrap();
// Even with aarch64 as host, Windows should still prefer x86_64
run_with_arch(aarch64(), || {
assert!(windows_x86_64 < windows_aarch64);
});
// With x86_64 as host, Windows should still prefer x86_64
run_with_arch(x86_64(), || {
assert!(windows_x86_64 < windows_aarch64);
});
}
#[test]
fn test_windows_aarch64_supports() {
// Test that Windows aarch64 can run x86_64 binaries through emulation
let windows_aarch64 = Platform::from_str("windows-aarch64-none").unwrap();
let windows_x86_64 = Platform::from_str("windows-x86_64-none").unwrap();
// aarch64 Windows supports x86_64 through transparent emulation
assert!(windows_aarch64.supports(&windows_x86_64));
// But x86_64 doesn't support aarch64
assert!(!windows_x86_64.supports(&windows_aarch64));
// Self-support should always work
assert!(windows_aarch64.supports(&windows_aarch64));
assert!(windows_x86_64.supports(&windows_x86_64));
}
#[test]
fn test_from_platform_tags_platform() {
// Test conversion from uv_platform_tags::Platform to uv_platform::Platform
let tags_platform = uv_platform_tags::Platform::new(
uv_platform_tags::Os::Windows,
uv_platform_tags::Arch::X86_64,
);
let platform = Platform::from(&tags_platform);
assert_eq!(platform.os.to_string(), "windows");
assert_eq!(platform.arch.to_string(), "x86_64");
assert_eq!(platform.libc.to_string(), "none");
// Test with manylinux
let tags_platform_linux = uv_platform_tags::Platform::new(
uv_platform_tags::Os::Manylinux {
major: 2,
minor: 17,
},
uv_platform_tags::Arch::Aarch64,
);
let platform_linux = Platform::from(&tags_platform_linux);
assert_eq!(platform_linux.os.to_string(), "linux");
assert_eq!(platform_linux.arch.to_string(), "aarch64");
assert_eq!(platform_linux.libc.to_string(), "gnu");
}
}
| 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/src/os.rs | crates/uv-platform/src/os.rs | use crate::Error;
use std::fmt;
use std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub struct Os(pub(crate) target_lexicon::OperatingSystem);
impl Os {
pub fn new(os: target_lexicon::OperatingSystem) -> Self {
Self(os)
}
pub fn from_env() -> Self {
Self(target_lexicon::HOST.operating_system)
}
pub fn is_windows(&self) -> bool {
matches!(self.0, target_lexicon::OperatingSystem::Windows)
}
pub fn is_emscripten(&self) -> bool {
matches!(self.0, target_lexicon::OperatingSystem::Emscripten)
}
pub fn is_macos(&self) -> bool {
matches!(self.0, target_lexicon::OperatingSystem::Darwin(_))
}
/// Whether this OS can run the other OS.
pub fn supports(&self, other: Self) -> bool {
// Emscripten cannot run on Windows, but all other OSes can run Emscripten.
if other.is_emscripten() {
return !self.is_windows();
}
if self.is_windows() && other.is_emscripten() {
return false;
}
// Otherwise, we require an exact match
*self == other
}
}
impl Display for Os {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &**self {
target_lexicon::OperatingSystem::Darwin(_) => write!(f, "macos"),
inner => write!(f, "{inner}"),
}
}
}
impl FromStr for Os {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let inner = match s {
"macos" => target_lexicon::OperatingSystem::Darwin(None),
_ => target_lexicon::OperatingSystem::from_str(s)
.map_err(|()| Error::UnknownOs(s.to_string()))?,
};
if matches!(inner, target_lexicon::OperatingSystem::Unknown) {
return Err(Error::UnknownOs(s.to_string()));
}
Ok(Self(inner))
}
}
impl Deref for Os {
type Target = target_lexicon::OperatingSystem;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<&uv_platform_tags::Os> for Os {
fn from(value: &uv_platform_tags::Os) -> Self {
match value {
uv_platform_tags::Os::Dragonfly { .. } => {
Self::new(target_lexicon::OperatingSystem::Dragonfly)
}
uv_platform_tags::Os::FreeBsd { .. } => {
Self::new(target_lexicon::OperatingSystem::Freebsd)
}
uv_platform_tags::Os::Haiku { .. } => Self::new(target_lexicon::OperatingSystem::Haiku),
uv_platform_tags::Os::Illumos { .. } => {
Self::new(target_lexicon::OperatingSystem::Illumos)
}
uv_platform_tags::Os::Macos { .. } => {
Self::new(target_lexicon::OperatingSystem::Darwin(None))
}
uv_platform_tags::Os::Manylinux { .. }
| uv_platform_tags::Os::Musllinux { .. }
| uv_platform_tags::Os::Android { .. } => {
Self::new(target_lexicon::OperatingSystem::Linux)
}
uv_platform_tags::Os::NetBsd { .. } => {
Self::new(target_lexicon::OperatingSystem::Netbsd)
}
uv_platform_tags::Os::OpenBsd { .. } => {
Self::new(target_lexicon::OperatingSystem::Openbsd)
}
uv_platform_tags::Os::Windows => Self::new(target_lexicon::OperatingSystem::Windows),
uv_platform_tags::Os::Pyodide { .. } => {
Self::new(target_lexicon::OperatingSystem::Emscripten)
}
uv_platform_tags::Os::Ios { .. } => {
Self::new(target_lexicon::OperatingSystem::IOS(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-platform/src/cpuinfo.rs | crates/uv-platform/src/cpuinfo.rs | //! Fetches CPU information.
use std::io::Error;
#[cfg(target_os = "linux")]
use procfs::{CpuInfo, Current};
/// Detects whether the hardware supports floating-point operations using ARM's Vector Floating Point (VFP) hardware.
///
/// This function is relevant specifically for ARM architectures, where the presence of the "vfp" flag in `/proc/cpuinfo`
/// indicates that the CPU supports hardware floating-point operations.
/// This helps determine whether the system is using the `gnueabihf` (hard-float) ABI or `gnueabi` (soft-float) ABI.
///
/// More information on this can be found in the [Debian ARM Hard Float Port documentation](https://wiki.debian.org/ArmHardFloatPort#VFP).
#[cfg(target_os = "linux")]
pub(crate) fn detect_hardware_floating_point_support() -> Result<bool, Error> {
let cpu_info = CpuInfo::current().map_err(Error::other)?;
if let Some(features) = cpu_info.fields.get("Features") {
if features.contains("vfp") {
return Ok(true); // "vfp" found: hard-float (gnueabihf) detected
}
}
Ok(false) // Default to soft-float (gnueabi) if no "vfp" flag is found
}
/// For non-Linux systems or architectures, the function will return `false` as hardware floating-point detection
/// is not applicable outside of Linux ARM architectures.
#[cfg(not(target_os = "linux"))]
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn detect_hardware_floating_point_support() -> Result<bool, Error> {
Ok(false) // Non-Linux or non-ARM systems: hardware floating-point detection is not applicable
}
| 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/src/libc.rs | crates/uv-platform/src/libc.rs | //! Determine the libc (glibc or musl) on linux.
//!
//! Taken from `glibc_version` (<https://github.com/delta-incubator/glibc-version-rs>),
//! which used the Apache 2.0 license (but not the MIT license)
use crate::cpuinfo::detect_hardware_floating_point_support;
use fs_err as fs;
use goblin::elf::Elf;
use regex::Regex;
use std::fmt::Display;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::sync::LazyLock;
use std::{env, fmt};
use tracing::trace;
use uv_fs::Simplified;
use uv_static::EnvVars;
#[derive(Debug, thiserror::Error)]
pub enum LibcDetectionError {
#[error(
"Could not detect either glibc version nor musl libc version, at least one of which is required"
)]
NoLibcFound,
#[error("Failed to get base name of symbolic link path {0}")]
MissingBasePath(PathBuf),
#[error("Failed to find glibc version in the filename of linker: `{0}`")]
GlibcExtractionMismatch(PathBuf),
#[error("Failed to determine {libc} version by running: `{program}`")]
FailedToRun {
libc: &'static str,
program: String,
#[source]
err: io::Error,
},
#[error("Could not find glibc version in output of: `{0} --version`")]
InvalidLdSoOutputGnu(PathBuf),
#[error("Could not find musl version in output of: `{0}`")]
InvalidLdSoOutputMusl(PathBuf),
#[error("Could not read ELF interpreter from any of the following paths: {0}")]
CoreBinaryParsing(String),
#[error("Failed to find any common binaries to determine libc from: {0}")]
NoCommonBinariesFound(String),
#[error("Failed to determine libc")]
Io(#[from] io::Error),
}
/// We support glibc (manylinux) and musl (musllinux) on linux.
#[derive(Debug, PartialEq, Eq)]
pub enum LibcVersion {
Manylinux { major: u32, minor: u32 },
Musllinux { major: u32, minor: u32 },
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub enum Libc {
Some(target_lexicon::Environment),
None,
}
impl Libc {
pub fn from_env() -> Result<Self, crate::Error> {
match env::consts::OS {
"linux" => {
if let Ok(libc) = env::var(EnvVars::UV_LIBC) {
if !libc.is_empty() {
return Self::from_str(&libc);
}
}
Ok(Self::Some(match detect_linux_libc()? {
LibcVersion::Manylinux { .. } => match env::consts::ARCH {
// Checks if the CPU supports hardware floating-point operations.
// Depending on the result, it selects either the `gnueabihf` (hard-float) or `gnueabi` (soft-float) environment.
// download-metadata.json only includes armv7.
"arm" | "armv5te" | "armv7" => {
match detect_hardware_floating_point_support() {
Ok(true) => target_lexicon::Environment::Gnueabihf,
Ok(false) => target_lexicon::Environment::Gnueabi,
Err(_) => target_lexicon::Environment::Gnu,
}
}
_ => target_lexicon::Environment::Gnu,
},
LibcVersion::Musllinux { .. } => target_lexicon::Environment::Musl,
}))
}
"windows" | "macos" => Ok(Self::None),
// Use `None` on platforms without explicit support.
_ => Ok(Self::None),
}
}
pub fn is_musl(&self) -> bool {
matches!(self, Self::Some(target_lexicon::Environment::Musl))
}
}
impl FromStr for Libc {
type Err = crate::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"gnu" => Ok(Self::Some(target_lexicon::Environment::Gnu)),
"gnueabi" => Ok(Self::Some(target_lexicon::Environment::Gnueabi)),
"gnueabihf" => Ok(Self::Some(target_lexicon::Environment::Gnueabihf)),
"musl" => Ok(Self::Some(target_lexicon::Environment::Musl)),
"none" => Ok(Self::None),
_ => Err(crate::Error::UnknownLibc(s.to_string())),
}
}
}
impl Display for Libc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Some(env) => write!(f, "{env}"),
Self::None => write!(f, "none"),
}
}
}
impl From<&uv_platform_tags::Os> for Libc {
fn from(value: &uv_platform_tags::Os) -> Self {
match value {
uv_platform_tags::Os::Manylinux { .. } => Self::Some(target_lexicon::Environment::Gnu),
uv_platform_tags::Os::Musllinux { .. } => Self::Some(target_lexicon::Environment::Musl),
uv_platform_tags::Os::Pyodide { .. } => Self::Some(target_lexicon::Environment::Musl),
_ => Self::None,
}
}
}
/// Determine whether we're running glibc or musl and in which version, given we are on linux.
///
/// Normally, we determine this from the python interpreter, which is more accurate, but when
/// deciding which python interpreter to download, we need to figure this out from the environment.
///
/// A platform can have both musl and glibc installed. We determine the preferred platform by
/// inspecting core binaries.
pub(crate) fn detect_linux_libc() -> Result<LibcVersion, LibcDetectionError> {
let ld_path = find_ld_path()?;
trace!("Found `ld` path: {}", ld_path.user_display());
match detect_musl_version(&ld_path) {
Ok(os) => return Ok(os),
Err(err) => {
trace!("Tried to find musl version by running `{ld_path:?}`, but failed: {err}");
}
}
match detect_linux_libc_from_ld_symlink(&ld_path) {
Ok(os) => return Ok(os),
Err(err) => {
trace!(
"Tried to find libc version from possible symlink at {ld_path:?}, but failed: {err}"
);
}
}
match detect_glibc_version_from_ld(&ld_path) {
Ok(os_version) => return Ok(os_version),
Err(err) => {
trace!(
"Tried to find glibc version from `{} --version`, but failed: {}",
ld_path.simplified_display(),
err
);
}
}
Err(LibcDetectionError::NoLibcFound)
}
// glibc version is taken from `std/sys/unix/os.rs`.
fn detect_glibc_version_from_ld(ld_so: &Path) -> Result<LibcVersion, LibcDetectionError> {
let output = Command::new(ld_so)
.args(["--version"])
.output()
.map_err(|err| LibcDetectionError::FailedToRun {
libc: "glibc",
program: format!("{} --version", ld_so.user_display()),
err,
})?;
if let Some(os) = glibc_ld_output_to_version("stdout", &output.stdout) {
return Ok(os);
}
if let Some(os) = glibc_ld_output_to_version("stderr", &output.stderr) {
return Ok(os);
}
Err(LibcDetectionError::InvalidLdSoOutputGnu(
ld_so.to_path_buf(),
))
}
/// Parse output `/lib64/ld-linux-x86-64.so.2 --version` and equivalent ld.so files.
///
/// Example: `ld.so (Ubuntu GLIBC 2.39-0ubuntu8.3) stable release version 2.39.`.
fn glibc_ld_output_to_version(kind: &str, output: &[u8]) -> Option<LibcVersion> {
static RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"ld.so \(.+\) .* ([0-9]+\.[0-9]+)").unwrap());
let output = String::from_utf8_lossy(output);
trace!("{kind} output from `ld.so --version`: {output:?}");
let (_, [version]) = RE.captures(output.as_ref()).map(|c| c.extract())?;
// Parse the input as "x.y" glibc version.
let mut parsed_ints = version.split('.').map(str::parse).fuse();
let major = parsed_ints.next()?.ok()?;
let minor = parsed_ints.next()?.ok()?;
trace!("Found manylinux {major}.{minor} in {kind} of ld.so version");
Some(LibcVersion::Manylinux { major, minor })
}
fn detect_linux_libc_from_ld_symlink(path: &Path) -> Result<LibcVersion, LibcDetectionError> {
static RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^ld-([0-9]{1,3})\.([0-9]{1,3})\.so$").unwrap());
let ld_path = fs::read_link(path)?;
let filename = ld_path
.file_name()
.ok_or_else(|| LibcDetectionError::MissingBasePath(ld_path.clone()))?
.to_string_lossy();
let (_, [major, minor]) = RE
.captures(&filename)
.map(|c| c.extract())
.ok_or_else(|| LibcDetectionError::GlibcExtractionMismatch(ld_path.clone()))?;
// OK since we are guaranteed to have between 1 and 3 ASCII digits and the
// maximum possible value, 999, fits into a u16.
let major = major.parse().expect("valid major version");
let minor = minor.parse().expect("valid minor version");
Ok(LibcVersion::Manylinux { major, minor })
}
/// Read the musl version from libc library's output. Taken from maturin.
///
/// The libc library should output something like this to `stderr`:
///
/// ```text
/// musl libc (`x86_64`)
/// Version 1.2.2
/// Dynamic Program Loader
/// ```
fn detect_musl_version(ld_path: impl AsRef<Path>) -> Result<LibcVersion, LibcDetectionError> {
let ld_path = ld_path.as_ref();
let output = Command::new(ld_path)
.stdout(Stdio::null())
.stderr(Stdio::piped())
.output()
.map_err(|err| LibcDetectionError::FailedToRun {
libc: "musl",
program: ld_path.to_string_lossy().to_string(),
err,
})?;
if let Some(os) = musl_ld_output_to_version("stdout", &output.stdout) {
return Ok(os);
}
if let Some(os) = musl_ld_output_to_version("stderr", &output.stderr) {
return Ok(os);
}
Err(LibcDetectionError::InvalidLdSoOutputMusl(
ld_path.to_path_buf(),
))
}
/// Parse the musl version from ld output.
///
/// Example: `Version 1.2.5`.
fn musl_ld_output_to_version(kind: &str, output: &[u8]) -> Option<LibcVersion> {
static RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"Version ([0-9]{1,4})\.([0-9]{1,4})").unwrap());
let output = String::from_utf8_lossy(output);
trace!("{kind} output from `ld`: {output:?}");
let (_, [major, minor]) = RE.captures(output.as_ref()).map(|c| c.extract())?;
// unwrap-safety: Since we are guaranteed to have between 1 and 4 ASCII digits and the
// maximum possible value, 9999, fits into a u16.
let major = major.parse().expect("valid major version");
let minor = minor.parse().expect("valid minor version");
trace!("Found musllinux {major}.{minor} in {kind} of `ld`");
Some(LibcVersion::Musllinux { major, minor })
}
/// Find musl ld path from executable's ELF header.
fn find_ld_path() -> Result<PathBuf, LibcDetectionError> {
// At first, we just looked for /bin/ls. But on some Linux distros, /bin/ls
// is a shell script that just calls /usr/bin/ls. So we switched to looking
// at /bin/sh. But apparently in some environments, /bin/sh is itself just
// a shell script that calls /bin/dash. So... We just try a few different
// paths. In most cases, /bin/sh should work.
//
// See: https://github.com/astral-sh/uv/pull/1493
// See: https://github.com/astral-sh/uv/issues/1810
// See: https://github.com/astral-sh/uv/issues/4242#issuecomment-2306164449
let attempts = ["/bin/sh", "/usr/bin/env", "/bin/dash", "/bin/ls"];
let mut found_anything = false;
for path in attempts {
if std::fs::exists(path).ok() == Some(true) {
found_anything = true;
if let Some(ld_path) = find_ld_path_at(path) {
return Ok(ld_path);
}
}
}
let attempts_string = attempts.join(", ");
if !found_anything {
// Known failure cases here include running the distroless Docker images directly
// (depending on what subcommand you use) and certain Nix setups. See:
// https://github.com/astral-sh/uv/issues/8635
Err(LibcDetectionError::NoCommonBinariesFound(attempts_string))
} else {
Err(LibcDetectionError::CoreBinaryParsing(attempts_string))
}
}
/// Attempt to find the path to the `ld` executable by
/// ELF parsing the given path. If this fails for any
/// reason, then an error is returned.
fn find_ld_path_at(path: impl AsRef<Path>) -> Option<PathBuf> {
let path = path.as_ref();
// Not all linux distributions have all of these paths.
let buffer = fs::read(path).ok()?;
let elf = match Elf::parse(&buffer) {
Ok(elf) => elf,
Err(err) => {
trace!(
"Could not parse ELF file at `{}`: `{}`",
path.user_display(),
err
);
return None;
}
};
let Some(elf_interpreter) = elf.interpreter else {
trace!(
"Couldn't find ELF interpreter path from {}",
path.user_display()
);
return None;
};
Some(PathBuf::from(elf_interpreter))
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
#[test]
fn parse_ld_so_output() {
let ver_str = glibc_ld_output_to_version(
"stdout",
indoc! {br"ld.so (Ubuntu GLIBC 2.39-0ubuntu8.3) stable release version 2.39.
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
"},
)
.unwrap();
assert_eq!(
ver_str,
LibcVersion::Manylinux {
major: 2,
minor: 39
}
);
}
#[test]
fn parse_musl_ld_output() {
// This output was generated by running `/lib/ld-musl-x86_64.so.1`
// in an Alpine Docker image. The Alpine version:
//
// # cat /etc/alpine-release
// 3.19.1
let output = b"\
musl libc (x86_64)
Version 1.2.4_git20230717
Dynamic Program Loader
Usage: /lib/ld-musl-x86_64.so.1 [options] [--] pathname [args]\
";
let got = musl_ld_output_to_version("stderr", output).unwrap();
assert_eq!(got, LibcVersion::Musllinux { major: 1, minor: 2 });
}
}
| 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/src/arch.rs | crates/uv-platform/src/arch.rs | use crate::Error;
use std::str::FromStr;
/// Architecture variants, e.g., with support for different instruction sets
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd)]
pub enum ArchVariant {
/// Targets 64-bit Intel/AMD CPUs newer than Nehalem (2008).
/// Includes SSE3, SSE4 and other post-2003 CPU instructions.
V2,
/// Targets 64-bit Intel/AMD CPUs newer than Haswell (2013) and Excavator (2015).
/// Includes AVX, AVX2, MOVBE and other newer CPU instructions.
V3,
/// Targets 64-bit Intel/AMD CPUs with AVX-512 instructions (post-2017 Intel CPUs).
/// Many post-2017 Intel CPUs do not support AVX-512.
V4,
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub struct Arch {
pub(crate) family: target_lexicon::Architecture,
pub(crate) variant: Option<ArchVariant>,
}
impl Ord for Arch {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.family == other.family {
return self.variant.cmp(&other.variant);
}
// For the time being, manually make aarch64 windows disfavored
// on its own host platform, because most packages don't have wheels for
// aarch64 windows, making emulation more useful than native execution!
//
// The reason we do this in "sorting" and not "supports" is so that we don't
// *refuse* to use an aarch64 windows pythons if they happen to be installed
// and nothing else is available.
//
// Similarly if someone manually requests an aarch64 windows install, we
// should respect that request (this is the way users should "override"
// this behaviour).
let preferred = if cfg!(all(windows, target_arch = "aarch64")) {
Self {
family: target_lexicon::Architecture::X86_64,
variant: None,
}
} else {
// Prefer native architectures
Self::from_env()
};
match (
self.family == preferred.family,
other.family == preferred.family,
) {
(true, true) => unreachable!(),
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
(false, false) => {
// Both non-preferred, fallback to lexicographic order
self.family.to_string().cmp(&other.family.to_string())
}
}
}
}
impl PartialOrd for Arch {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Arch {
pub fn new(family: target_lexicon::Architecture, variant: Option<ArchVariant>) -> Self {
Self { family, variant }
}
pub fn from_env() -> Self {
#[cfg(test)]
{
if let Some(arch) = test_support::get_mock_arch() {
return arch;
}
}
Self {
family: target_lexicon::HOST.architecture,
variant: None,
}
}
pub fn family(&self) -> target_lexicon::Architecture {
self.family
}
pub fn is_arm(&self) -> bool {
matches!(self.family, target_lexicon::Architecture::Arm(_))
}
pub fn is_wasm(&self) -> bool {
matches!(self.family, target_lexicon::Architecture::Wasm32)
}
}
impl std::fmt::Display for Arch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.family {
target_lexicon::Architecture::X86_32(target_lexicon::X86_32Architecture::I686) => {
write!(f, "x86")?;
}
inner => write!(f, "{inner}")?,
}
if let Some(variant) = self.variant {
write!(f, "_{variant}")?;
}
Ok(())
}
}
impl FromStr for Arch {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
fn parse_family(s: &str) -> Result<target_lexicon::Architecture, Error> {
let inner = match s {
// Allow users to specify "x86" as a shorthand for the "i686" variant, they should not need
// to specify the exact architecture and this variant is what we have downloads for.
"x86" => {
target_lexicon::Architecture::X86_32(target_lexicon::X86_32Architecture::I686)
}
_ => target_lexicon::Architecture::from_str(s)
.map_err(|()| Error::UnknownArch(s.to_string()))?,
};
if matches!(inner, target_lexicon::Architecture::Unknown) {
return Err(Error::UnknownArch(s.to_string()));
}
Ok(inner)
}
// First check for a variant
if let Some((Ok(family), Ok(variant))) = s
.rsplit_once('_')
.map(|(family, variant)| (parse_family(family), ArchVariant::from_str(variant)))
{
// We only support variants for `x86_64` right now
if !matches!(family, target_lexicon::Architecture::X86_64) {
return Err(Error::UnsupportedVariant(
variant.to_string(),
family.to_string(),
));
}
return Ok(Self {
family,
variant: Some(variant),
});
}
let family = parse_family(s)?;
Ok(Self {
family,
variant: None,
})
}
}
impl FromStr for ArchVariant {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"v2" => Ok(Self::V2),
"v3" => Ok(Self::V3),
"v4" => Ok(Self::V4),
_ => Err(()),
}
}
}
impl std::fmt::Display for ArchVariant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::V2 => write!(f, "v2"),
Self::V3 => write!(f, "v3"),
Self::V4 => write!(f, "v4"),
}
}
}
impl From<&uv_platform_tags::Arch> for Arch {
fn from(value: &uv_platform_tags::Arch) -> Self {
match value {
uv_platform_tags::Arch::Aarch64 => Self::new(
target_lexicon::Architecture::Aarch64(target_lexicon::Aarch64Architecture::Aarch64),
None,
),
uv_platform_tags::Arch::Armv5TEL => Self::new(
target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv5te),
None,
),
uv_platform_tags::Arch::Armv6L => Self::new(
target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv6),
None,
),
uv_platform_tags::Arch::Armv7L => Self::new(
target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv7),
None,
),
uv_platform_tags::Arch::S390X => Self::new(target_lexicon::Architecture::S390x, None),
uv_platform_tags::Arch::Powerpc => {
Self::new(target_lexicon::Architecture::Powerpc, None)
}
uv_platform_tags::Arch::Powerpc64 => {
Self::new(target_lexicon::Architecture::Powerpc64, None)
}
uv_platform_tags::Arch::Powerpc64Le => {
Self::new(target_lexicon::Architecture::Powerpc64le, None)
}
uv_platform_tags::Arch::X86 => Self::new(
target_lexicon::Architecture::X86_32(target_lexicon::X86_32Architecture::I686),
None,
),
uv_platform_tags::Arch::X86_64 => Self::new(target_lexicon::Architecture::X86_64, None),
uv_platform_tags::Arch::LoongArch64 => {
Self::new(target_lexicon::Architecture::LoongArch64, None)
}
uv_platform_tags::Arch::Riscv64 => Self::new(
target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64),
None,
),
uv_platform_tags::Arch::Wasm32 => Self::new(target_lexicon::Architecture::Wasm32, None),
}
}
}
#[cfg(test)]
pub(crate) mod test_support {
use super::*;
use std::cell::RefCell;
thread_local! {
static MOCK_ARCH: RefCell<Option<Arch>> = const { RefCell::new(None) };
}
pub(crate) fn get_mock_arch() -> Option<Arch> {
MOCK_ARCH.with(|arch| *arch.borrow())
}
fn set_mock_arch(arch: Option<Arch>) {
MOCK_ARCH.with(|mock| *mock.borrow_mut() = arch);
}
pub(crate) struct MockArchGuard {
previous: Option<Arch>,
}
impl MockArchGuard {
pub(crate) fn new(arch: Arch) -> Self {
let previous = get_mock_arch();
set_mock_arch(Some(arch));
Self { previous }
}
}
impl Drop for MockArchGuard {
fn drop(&mut self) {
set_mock_arch(self.previous);
}
}
/// Run a function with a mocked architecture.
/// The mock is automatically cleaned up after the function returns.
pub(crate) fn run_with_arch<F, R>(arch: Arch, f: F) -> R
where
F: FnOnce() -> R,
{
let _guard = MockArchGuard::new(arch);
f()
}
pub(crate) fn x86_64() -> Arch {
Arch::new(target_lexicon::Architecture::X86_64, None)
}
pub(crate) fn aarch64() -> Arch {
Arch::new(
target_lexicon::Architecture::Aarch64(target_lexicon::Aarch64Architecture::Aarch64),
None,
)
}
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git/src/rate_limit.rs | crates/uv-git/src/rate_limit.rs | use reqwest::{Response, StatusCode};
use std::sync::atomic::{AtomicBool, Ordering};
/// A global state on whether we are being rate-limited by GitHub's REST API.
/// If we are, avoid "fast-path" attempts.
pub(crate) static GITHUB_RATE_LIMIT_STATUS: GitHubRateLimitStatus = GitHubRateLimitStatus::new();
/// GitHub REST API rate limit status tracker.
///
/// ## Assumptions
///
/// The rate limit timeout duration is much longer than the runtime of a `uv` command.
/// And so we do not need to invalidate this state based on `x-ratelimit-reset`.
#[derive(Debug)]
pub(crate) struct GitHubRateLimitStatus(AtomicBool);
impl GitHubRateLimitStatus {
const fn new() -> Self {
Self(AtomicBool::new(false))
}
pub(crate) fn activate(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub(crate) fn is_active(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
/// Determine if GitHub is applying rate-limiting based on the response
pub(crate) fn is_github_rate_limited(response: &Response) -> bool {
// HTTP 403 and 429 are possible status codes in the event of a primary or secondary rate limit.
// Source: https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api?apiVersion=2022-11-28#rate-limit-errors
let status_code = response.status();
status_code == StatusCode::FORBIDDEN || status_code == StatusCode::TOO_MANY_REQUESTS
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git/src/source.rs | crates/uv-git/src/source.rs | //! Git support is derived from Cargo's implementation.
//! Cargo is dual-licensed under either Apache 2.0 or MIT, at the user's choice.
//! Source: <https://github.com/rust-lang/cargo/blob/23eb492cf920ce051abfc56bbaf838514dc8365c/src/cargo/sources/git/source.rs>
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Result;
use tracing::{debug, instrument};
use uv_cache_key::{RepositoryUrl, cache_digest};
use uv_git_types::{GitOid, GitReference, GitUrl};
use uv_redacted::DisplaySafeUrl;
use crate::GIT_STORE;
use crate::git::{GitDatabase, GitRemote};
/// A remote Git source that can be checked out locally.
pub struct GitSource {
/// The Git reference from the manifest file.
git: GitUrl,
/// Whether to disable SSL verification.
disable_ssl: bool,
/// Whether to operate without network connectivity.
offline: bool,
/// The path to the Git source database.
cache: PathBuf,
/// The reporter to use for this source.
reporter: Option<Arc<dyn Reporter>>,
}
impl GitSource {
/// Initialize a [`GitSource`] with the given Git URL, HTTP client, and cache path.
pub fn new(git: GitUrl, cache: impl Into<PathBuf>, offline: bool) -> Self {
Self {
git,
disable_ssl: false,
offline,
cache: cache.into(),
reporter: None,
}
}
/// Disable SSL verification for this [`GitSource`].
#[must_use]
pub fn dangerous(self) -> Self {
Self {
disable_ssl: true,
..self
}
}
/// Set the [`Reporter`] to use for the [`GitSource`].
#[must_use]
pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
reporter: Some(reporter),
..self
}
}
/// Fetch the underlying Git repository at the given revision.
#[instrument(skip(self), fields(repository = %self.git.repository(), rev = ?self.git.precise()))]
pub fn fetch(self) -> Result<Fetch> {
let lfs_requested = self.git.lfs().enabled();
// Compute the canonical URL for the repository.
let canonical = RepositoryUrl::new(self.git.repository());
// The path to the repo, within the Git database.
let ident = cache_digest(&canonical);
let db_path = self.cache.join("db").join(&ident);
// Authenticate the URL, if necessary.
let remote = if let Some(credentials) = GIT_STORE.get(&canonical) {
Cow::Owned(credentials.apply(self.git.repository().clone()))
} else {
Cow::Borrowed(self.git.repository())
};
// Fetch the commit, if we don't already have it. Wrapping this section in a closure makes
// it easier to short-circuit this in the cases where we do have the commit.
let (db, actual_rev, maybe_task) = || -> Result<(GitDatabase, GitOid, Option<usize>)> {
let git_remote = GitRemote::new(&remote);
let maybe_db = git_remote.db_at(&db_path).ok();
// If we have a locked revision, and we have a pre-existing database which has that
// revision, then no update needs to happen.
// When requested, we also check if LFS artifacts have been fetched and validated.
if let (Some(rev), Some(db)) = (self.git.precise(), &maybe_db) {
if db.contains(rev) && (!lfs_requested || db.contains_lfs_artifacts(rev)) {
debug!("Using existing Git source `{}`", self.git.repository());
return Ok((
maybe_db
.unwrap()
.with_lfs_ready(lfs_requested.then_some(true)),
rev,
None,
));
}
}
// If the revision isn't locked, but it looks like it might be an exact commit hash,
// and we do have a pre-existing database, then check whether it is, in fact, a commit
// hash. If so, treat it like it's locked.
// When requested, we also check if LFS artifacts have been fetched and validated.
if let Some(db) = &maybe_db {
if let GitReference::BranchOrTagOrCommit(maybe_commit) = self.git.reference() {
if let Ok(oid) = maybe_commit.parse::<GitOid>() {
if db.contains(oid) && (!lfs_requested || db.contains_lfs_artifacts(oid)) {
// This reference is an exact commit. Treat it like it's locked.
debug!("Using existing Git source `{}`", self.git.repository());
return Ok((
maybe_db
.unwrap()
.with_lfs_ready(lfs_requested.then_some(true)),
oid,
None,
));
}
}
}
}
// ... otherwise, we use this state to update the Git database. Note that we still check
// for being offline here, for example in the situation that we have a locked revision
// but the database doesn't have it.
debug!("Updating Git source `{}`", self.git.repository());
// Report the checkout operation to the reporter.
let task = self.reporter.as_ref().map(|reporter| {
reporter.on_checkout_start(git_remote.url(), self.git.reference().as_rev())
});
let (db, actual_rev) = git_remote.checkout(
&db_path,
maybe_db,
self.git.reference(),
self.git.precise(),
self.disable_ssl,
self.offline,
lfs_requested,
)?;
Ok((db, actual_rev, task))
}()?;
// Donβt use the full hash, in order to contribute less to reaching the
// path length limit on Windows.
let short_id = db.to_short_id(actual_rev)?;
// Compute the canonical URL for the repository checkout.
let canonical = canonical.with_lfs(Some(lfs_requested));
// Recompute the checkout hash when Git LFS is enabled as we want
// to distinctly differentiate between LFS vs non-LFS source trees.
let ident = if lfs_requested {
cache_digest(&canonical)
} else {
ident
};
let checkout_path = self
.cache
.join("checkouts")
.join(&ident)
.join(short_id.as_str());
// Check out `actual_rev` from the database to a scoped location on the
// filesystem. This will use hard links and such to ideally make the
// checkout operation here pretty fast.
let checkout = db.copy_to(actual_rev, &checkout_path)?;
// Report the checkout operation to the reporter.
if let Some(task) = maybe_task {
if let Some(reporter) = self.reporter.as_ref() {
reporter.on_checkout_complete(remote.as_ref(), actual_rev.as_str(), task);
}
}
Ok(Fetch {
git: self.git.with_precise(actual_rev),
path: checkout_path,
lfs_ready: checkout.lfs_ready().unwrap_or(false),
})
}
}
pub struct Fetch {
/// The [`GitUrl`] reference that was fetched.
git: GitUrl,
/// The path to the checked out repository.
path: PathBuf,
/// Git LFS artifacts have been initialized (if requested).
lfs_ready: bool,
}
impl Fetch {
pub fn git(&self) -> &GitUrl {
&self.git
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn lfs_ready(&self) -> &bool {
&self.lfs_ready
}
pub fn into_git(self) -> GitUrl {
self.git
}
pub fn into_path(self) -> PathBuf {
self.path
}
}
pub trait Reporter: Send + Sync {
/// 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, index: usize);
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git/src/lib.rs | crates/uv-git/src/lib.rs | pub use crate::credentials::{GIT_STORE, store_credentials_from_url};
pub use crate::git::{GIT, GIT_LFS, GitError};
pub use crate::resolver::{
GitResolver, GitResolverError, RepositoryReference, ResolvedRepositoryReference,
};
pub use crate::source::{Fetch, GitSource, Reporter};
mod credentials;
mod git;
mod rate_limit;
mod resolver;
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-git/src/git.rs | crates/uv-git/src/git.rs | //! Git support is derived from Cargo's implementation.
//! Cargo is dual-licensed under either Apache 2.0 or MIT, at the user's choice.
//! Source: <https://github.com/rust-lang/cargo/blob/23eb492cf920ce051abfc56bbaf838514dc8365c/src/cargo/sources/git/utils.rs>
use std::fmt::Display;
use std::path::{Path, PathBuf};
use std::str::{self};
use std::sync::LazyLock;
use anyhow::{Context, Result, anyhow};
use cargo_util::{ProcessBuilder, paths};
use owo_colors::OwoColorize;
use tracing::{debug, instrument, warn};
use url::Url;
use uv_fs::Simplified;
use uv_git_types::{GitOid, GitReference};
use uv_redacted::DisplaySafeUrl;
use uv_static::EnvVars;
use uv_warnings::warn_user_once;
/// A file indicates that if present, `git reset` has been done and a repo
/// checkout is ready to go. See [`GitCheckout::reset`] for why we need this.
const CHECKOUT_READY_LOCK: &str = ".ok";
#[derive(Debug, thiserror::Error)]
pub enum GitError {
#[error("Git executable not found. Ensure that Git is installed and available.")]
GitNotFound,
#[error("Git LFS extension not found. Ensure that Git LFS is installed and available.")]
GitLfsNotFound,
#[error("Is Git LFS configured? Run `{}` to initialize Git LFS.", "git lfs install".green())]
GitLfsNotConfigured,
#[error(transparent)]
Other(#[from] which::Error),
#[error(
"Remote Git fetches are not allowed because network connectivity is disabled (i.e., with `--offline`)"
)]
TransportNotAllowed,
}
/// A global cache of the result of `which git`.
pub static GIT: LazyLock<Result<PathBuf, GitError>> = LazyLock::new(|| {
which::which("git").map_err(|err| match err {
which::Error::CannotFindBinaryPath => GitError::GitNotFound,
err => GitError::Other(err),
})
});
/// Strategy when fetching refspecs for a [`GitReference`]
enum RefspecStrategy {
/// All refspecs should be fetched, if any fail then the fetch will fail.
All,
/// Stop after the first successful fetch, if none succeed then the fetch will fail.
First,
}
/// A Git reference (like a tag or branch) or a specific commit.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum ReferenceOrOid<'reference> {
/// A Git reference, like a tag or branch.
Reference(&'reference GitReference),
/// A specific commit.
Oid(GitOid),
}
impl ReferenceOrOid<'_> {
/// Resolves the [`ReferenceOrOid`] to an object ID with objects the `repo` currently has.
fn resolve(&self, repo: &GitRepository) -> Result<GitOid> {
let refkind = self.kind_str();
let result = match self {
// Resolve the commit pointed to by the tag.
//
// `^0` recursively peels away from the revision to the underlying commit object.
// This also verifies that the tag indeed refers to a commit.
Self::Reference(GitReference::Tag(s)) => {
repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0"))
}
// Resolve the commit pointed to by the branch.
Self::Reference(GitReference::Branch(s)) => repo.rev_parse(&format!("origin/{s}^0")),
// Attempt to resolve the branch, then the tag.
Self::Reference(GitReference::BranchOrTag(s)) => repo
.rev_parse(&format!("origin/{s}^0"))
.or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0"))),
// Attempt to resolve the branch, then the tag, then the commit.
Self::Reference(GitReference::BranchOrTagOrCommit(s)) => repo
.rev_parse(&format!("origin/{s}^0"))
.or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0")))
.or_else(|_| repo.rev_parse(&format!("{s}^0"))),
// We'll be using the HEAD commit.
Self::Reference(GitReference::DefaultBranch) => {
repo.rev_parse("refs/remotes/origin/HEAD")
}
// Resolve a named reference.
Self::Reference(GitReference::NamedRef(s)) => repo.rev_parse(&format!("{s}^0")),
// Resolve a specific commit.
Self::Oid(s) => repo.rev_parse(&format!("{s}^0")),
};
result.with_context(|| anyhow::format_err!("failed to find {refkind} `{self}`"))
}
/// Returns the kind of this [`ReferenceOrOid`].
fn kind_str(&self) -> &str {
match self {
Self::Reference(reference) => reference.kind_str(),
Self::Oid(_) => "commit",
}
}
/// Converts the [`ReferenceOrOid`] to a `str` that can be used as a revision.
fn as_rev(&self) -> &str {
match self {
Self::Reference(r) => r.as_rev(),
Self::Oid(rev) => rev.as_str(),
}
}
}
impl Display for ReferenceOrOid<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reference(reference) => write!(f, "{reference}"),
Self::Oid(oid) => write!(f, "{oid}"),
}
}
}
/// A remote repository. It gets cloned into a local [`GitDatabase`].
#[derive(PartialEq, Clone, Debug)]
pub(crate) struct GitRemote {
/// URL to a remote repository.
url: DisplaySafeUrl,
}
/// A local clone of a remote repository's database. Multiple [`GitCheckout`]s
/// can be cloned from a single [`GitDatabase`].
pub(crate) struct GitDatabase {
/// Underlying Git repository instance for this database.
repo: GitRepository,
/// Git LFS artifacts have been initialized (if requested).
lfs_ready: Option<bool>,
}
/// A local checkout of a particular revision from a [`GitRepository`].
pub(crate) struct GitCheckout {
/// The git revision this checkout is for.
revision: GitOid,
/// Underlying Git repository instance for this checkout.
repo: GitRepository,
/// Git LFS artifacts have been initialized (if requested).
lfs_ready: Option<bool>,
}
/// A local Git repository.
pub(crate) struct GitRepository {
/// Path to the underlying Git repository on the local filesystem.
path: PathBuf,
}
impl GitRepository {
/// Opens an existing Git repository at `path`.
pub(crate) fn open(path: &Path) -> Result<Self> {
// Make sure there is a Git repository at the specified path.
ProcessBuilder::new(GIT.as_ref()?)
.arg("rev-parse")
.cwd(path)
.exec_with_output()?;
Ok(Self {
path: path.to_path_buf(),
})
}
/// Initializes a Git repository at `path`.
fn init(path: &Path) -> Result<Self> {
// TODO(ibraheem): see if this still necessary now that we no longer use libgit2
// Skip anything related to templates, they just call all sorts of issues as
// we really don't want to use them yet they insist on being used. See #6240
// for an example issue that comes up.
// opts.external_template(false);
// Initialize the repository.
ProcessBuilder::new(GIT.as_ref()?)
.arg("init")
.cwd(path)
.exec_with_output()?;
Ok(Self {
path: path.to_path_buf(),
})
}
/// Parses the object ID of the given `refname`.
fn rev_parse(&self, refname: &str) -> Result<GitOid> {
let result = ProcessBuilder::new(GIT.as_ref()?)
.arg("rev-parse")
.arg(refname)
.cwd(&self.path)
.exec_with_output()?;
let mut result = String::from_utf8(result.stdout)?;
result.truncate(result.trim_end().len());
Ok(result.parse()?)
}
/// Verifies LFS artifacts have been initialized for a given `refname`.
#[instrument(skip_all, fields(path = %self.path.user_display(), refname = %refname))]
fn lfs_fsck_objects(&self, refname: &str) -> bool {
let mut cmd = if let Ok(lfs) = GIT_LFS.as_ref() {
lfs.clone()
} else {
warn!("Git LFS is not available, skipping LFS fetch");
return false;
};
// Requires Git LFS 3.x (2021 release)
let result = cmd
.arg("fsck")
.arg("--objects")
.arg(refname)
.cwd(&self.path)
.exec_with_output();
match result {
Ok(_) => true,
Err(err) => {
let lfs_error = err.to_string();
if lfs_error.contains("unknown flag: --objects") {
warn_user_once!(
"Skipping Git LFS validation as Git LFS extension is outdated. \
Upgrade to `git-lfs>=3.0.2` or manually verify git-lfs objects were \
properly fetched after the current operation finishes."
);
true
} else {
debug!("Git LFS validation failed: {err}");
false
}
}
}
}
}
impl GitRemote {
/// Creates an instance for a remote repository URL.
pub(crate) fn new(url: &DisplaySafeUrl) -> Self {
Self { url: url.clone() }
}
/// Gets the remote repository URL.
pub(crate) fn url(&self) -> &DisplaySafeUrl {
&self.url
}
/// Fetches and checkouts to a reference or a revision from this remote
/// into a local path.
///
/// This ensures that it gets the up-to-date commit when a named reference
/// is given (tag, branch, refs/*). Thus, network connection is involved.
///
/// When `locked_rev` is provided, it takes precedence over `reference`.
///
/// If we have a previous instance of [`GitDatabase`] then fetch into that
/// if we can. If that can successfully load our revision then we've
/// populated the database with the latest version of `reference`, so
/// return that database and the rev we resolve to.
pub(crate) fn checkout(
&self,
into: &Path,
db: Option<GitDatabase>,
reference: &GitReference,
locked_rev: Option<GitOid>,
disable_ssl: bool,
offline: bool,
with_lfs: bool,
) -> Result<(GitDatabase, GitOid)> {
let reference = locked_rev
.map(ReferenceOrOid::Oid)
.unwrap_or(ReferenceOrOid::Reference(reference));
if let Some(mut db) = db {
fetch(&mut db.repo, &self.url, reference, disable_ssl, offline)
.with_context(|| format!("failed to fetch into: {}", into.user_display()))?;
let resolved_commit_hash = match locked_rev {
Some(rev) => db.contains(rev).then_some(rev),
None => reference.resolve(&db.repo).ok(),
};
if let Some(rev) = resolved_commit_hash {
if with_lfs {
let lfs_ready = fetch_lfs(&mut db.repo, &self.url, &rev, disable_ssl)
.with_context(|| format!("failed to fetch LFS objects at {rev}"))?;
db = db.with_lfs_ready(Some(lfs_ready));
}
return Ok((db, rev));
}
}
// Otherwise start from scratch to handle corrupt git repositories.
// After our fetch (which is interpreted as a clone now) we do the same
// resolution to figure out what we cloned.
match fs_err::remove_dir_all(into) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
fs_err::create_dir_all(into)?;
let mut repo = GitRepository::init(into)?;
fetch(&mut repo, &self.url, reference, disable_ssl, offline)
.with_context(|| format!("failed to clone into: {}", into.user_display()))?;
let rev = match locked_rev {
Some(rev) => rev,
None => reference.resolve(&repo)?,
};
let lfs_ready = with_lfs
.then(|| {
fetch_lfs(&mut repo, &self.url, &rev, disable_ssl)
.with_context(|| format!("failed to fetch LFS objects at {rev}"))
})
.transpose()?;
Ok((GitDatabase { repo, lfs_ready }, rev))
}
/// Creates a [`GitDatabase`] of this remote at `db_path`.
#[allow(clippy::unused_self)]
pub(crate) fn db_at(&self, db_path: &Path) -> Result<GitDatabase> {
let repo = GitRepository::open(db_path)?;
Ok(GitDatabase {
repo,
lfs_ready: None,
})
}
}
impl GitDatabase {
/// Checkouts to a revision at `destination` from this database.
pub(crate) fn copy_to(&self, rev: GitOid, destination: &Path) -> Result<GitCheckout> {
// If the existing checkout exists, and it is fresh, use it.
// A non-fresh checkout can happen if the checkout operation was
// interrupted. In that case, the checkout gets deleted and a new
// clone is created.
let checkout = match GitRepository::open(destination)
.ok()
.map(|repo| GitCheckout::new(rev, repo))
.filter(GitCheckout::is_fresh)
{
Some(co) => co.with_lfs_ready(self.lfs_ready),
None => GitCheckout::clone_into(destination, self, rev)?,
};
Ok(checkout)
}
/// Get a short OID for a `revision`, usually 7 chars or more if ambiguous.
pub(crate) fn to_short_id(&self, revision: GitOid) -> Result<String> {
let output = ProcessBuilder::new(GIT.as_ref()?)
.arg("rev-parse")
.arg("--short")
.arg(revision.as_str())
.cwd(&self.repo.path)
.exec_with_output()?;
let mut result = String::from_utf8(output.stdout)?;
result.truncate(result.trim_end().len());
Ok(result)
}
/// Checks if `oid` resolves to a commit in this database.
pub(crate) fn contains(&self, oid: GitOid) -> bool {
self.repo.rev_parse(&format!("{oid}^0")).is_ok()
}
/// Checks if `oid` contains necessary LFS artifacts in this database.
pub(crate) fn contains_lfs_artifacts(&self, oid: GitOid) -> bool {
self.repo.lfs_fsck_objects(&format!("{oid}^0"))
}
/// Set the Git LFS validation state (if any).
#[must_use]
pub(crate) fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
self.lfs_ready = lfs;
self
}
}
impl GitCheckout {
/// Creates an instance of [`GitCheckout`]. This doesn't imply the checkout
/// is done. Use [`GitCheckout::is_fresh`] to check.
///
/// * The `repo` will be the checked out Git repository.
fn new(revision: GitOid, repo: GitRepository) -> Self {
Self {
revision,
repo,
lfs_ready: None,
}
}
/// Clone a repo for a `revision` into a local path from a `database`.
/// This is a filesystem-to-filesystem clone.
fn clone_into(into: &Path, database: &GitDatabase, revision: GitOid) -> Result<Self> {
let dirname = into.parent().unwrap();
fs_err::create_dir_all(dirname)?;
match fs_err::remove_dir_all(into) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
// Perform a local clone of the repository, which will attempt to use
// hardlinks to set up the repository. This should speed up the clone operation
// quite a bit if it works.
let res = ProcessBuilder::new(GIT.as_ref()?)
.arg("clone")
.arg("--local")
// Make sure to pass the local file path and not a file://... url. If given a url,
// Git treats the repository as a remote origin and gets confused because we don't
// have a HEAD checked out.
.arg(database.repo.path.simplified_display().to_string())
.arg(into.simplified_display().to_string())
.exec_with_output();
if let Err(e) = res {
debug!("Cloning git repo with --local failed, retrying without hardlinks: {e}");
ProcessBuilder::new(GIT.as_ref()?)
.arg("clone")
.arg("--no-hardlinks")
.arg(database.repo.path.simplified_display().to_string())
.arg(into.simplified_display().to_string())
.exec_with_output()?;
}
let repo = GitRepository::open(into)?;
let checkout = Self::new(revision, repo);
let lfs_ready = checkout.reset(database.lfs_ready)?;
Ok(checkout.with_lfs_ready(lfs_ready))
}
/// Checks if the `HEAD` of this checkout points to the expected revision.
fn is_fresh(&self) -> bool {
match self.repo.rev_parse("HEAD") {
Ok(id) if id == self.revision => {
// See comments in reset() for why we check this
self.repo.path.join(CHECKOUT_READY_LOCK).exists()
}
_ => false,
}
}
/// Indicates Git LFS artifacts have been initialized (when requested).
pub(crate) fn lfs_ready(&self) -> Option<bool> {
self.lfs_ready
}
/// Set the Git LFS validation state (if any).
#[must_use]
pub(crate) fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
self.lfs_ready = lfs;
self
}
/// This performs `git reset --hard` to the revision of this checkout, with
/// additional interrupt protection by a dummy file [`CHECKOUT_READY_LOCK`].
///
/// If we're interrupted while performing a `git reset` (e.g., we die
/// because of a signal) uv needs to be sure to try to check out this
/// repo again on the next go-round.
///
/// To enable this we have a dummy file in our checkout, [`.ok`],
/// which if present means that the repo has been successfully reset and is
/// ready to go. Hence, if we start to do a reset, we make sure this file
/// *doesn't* exist, and then once we're done we create the file.
///
/// [`.ok`]: CHECKOUT_READY_LOCK
fn reset(&self, with_lfs: Option<bool>) -> Result<Option<bool>> {
let ok_file = self.repo.path.join(CHECKOUT_READY_LOCK);
let _ = paths::remove_file(&ok_file);
// We want to skip smudge if lfs was disabled for the repository
// as smudge filters can trigger on a reset even if lfs artifacts
// were not originally "fetched".
let lfs_skip_smudge = if with_lfs == Some(true) { "0" } else { "1" };
debug!("Reset {} to {}", self.repo.path.display(), self.revision);
// Perform the hard reset.
ProcessBuilder::new(GIT.as_ref()?)
.arg("reset")
.arg("--hard")
.arg(self.revision.as_str())
.env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
.cwd(&self.repo.path)
.exec_with_output()?;
// Update submodules (`git submodule update --recursive`).
ProcessBuilder::new(GIT.as_ref()?)
.arg("submodule")
.arg("update")
.arg("--recursive")
.arg("--init")
.env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
.cwd(&self.repo.path)
.exec_with_output()
.map(drop)?;
// Validate Git LFS objects (if needed) after the reset.
// See `fetch_lfs` why we do this.
let lfs_validation = match with_lfs {
None => None,
Some(false) => Some(false),
Some(true) => Some(self.repo.lfs_fsck_objects(self.revision.as_str())),
};
// The .ok file should be written when the reset is successful.
// When Git LFS is enabled, the objects must also be fetched and
// validated successfully as part of the corresponding db.
if with_lfs.is_none() || lfs_validation == Some(true) {
paths::create(ok_file)?;
}
Ok(lfs_validation)
}
}
/// Attempts to fetch the given git `reference` for a Git repository.
///
/// This is the main entry for git clone/fetch. It does the following:
///
/// * Turns [`GitReference`] into refspecs accordingly.
/// * Dispatches `git fetch` using the git CLI.
///
/// The `remote_url` argument is the git remote URL where we want to fetch from.
fn fetch(
repo: &mut GitRepository,
remote_url: &Url,
reference: ReferenceOrOid<'_>,
disable_ssl: bool,
offline: bool,
) -> Result<()> {
let oid_to_fetch = if let ReferenceOrOid::Oid(rev) = reference {
let local_object = reference.resolve(repo).ok();
if let Some(local_object) = local_object {
if rev == local_object {
return Ok(());
}
}
// If we know the reference is a full commit hash, we can just return it without
// querying GitHub.
Some(rev)
} else {
None
};
// Translate the reference desired here into an actual list of refspecs
// which need to get fetched. Additionally record if we're fetching tags.
let mut refspecs = Vec::new();
let mut tags = false;
let mut refspec_strategy = RefspecStrategy::All;
// The `+` symbol on the refspec means to allow a forced (fast-forward)
// update which is needed if there is ever a force push that requires a
// fast-forward.
match reference {
// For branches and tags we can fetch simply one reference and copy it
// locally, no need to fetch other branches/tags.
ReferenceOrOid::Reference(GitReference::Branch(branch)) => {
refspecs.push(format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"));
}
ReferenceOrOid::Reference(GitReference::Tag(tag)) => {
refspecs.push(format!("+refs/tags/{tag}:refs/remotes/origin/tags/{tag}"));
}
ReferenceOrOid::Reference(GitReference::BranchOrTag(branch_or_tag)) => {
refspecs.push(format!(
"+refs/heads/{branch_or_tag}:refs/remotes/origin/{branch_or_tag}"
));
refspecs.push(format!(
"+refs/tags/{branch_or_tag}:refs/remotes/origin/tags/{branch_or_tag}"
));
refspec_strategy = RefspecStrategy::First;
}
// For ambiguous references, we can fetch the exact commit (if known); otherwise,
// we fetch all branches and tags.
ReferenceOrOid::Reference(GitReference::BranchOrTagOrCommit(branch_or_tag_or_commit)) => {
// The `oid_to_fetch` is the exact commit we want to fetch. But it could be the exact
// commit of a branch or tag. We should only fetch it directly if it's the exact commit
// of a short commit hash.
if let Some(oid_to_fetch) =
oid_to_fetch.filter(|oid| is_short_hash_of(branch_or_tag_or_commit, *oid))
{
refspecs.push(format!("+{oid_to_fetch}:refs/commit/{oid_to_fetch}"));
} else {
// We don't know what the rev will point to. To handle this
// situation we fetch all branches and tags, and then we pray
// it's somewhere in there.
refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
tags = true;
}
}
ReferenceOrOid::Reference(GitReference::DefaultBranch) => {
refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
}
ReferenceOrOid::Reference(GitReference::NamedRef(rev)) => {
refspecs.push(format!("+{rev}:{rev}"));
}
ReferenceOrOid::Oid(rev) => {
refspecs.push(format!("+{rev}:refs/commit/{rev}"));
}
}
debug!("Performing a Git fetch for: {remote_url}");
let result = match refspec_strategy {
RefspecStrategy::All => fetch_with_cli(
repo,
remote_url,
refspecs.as_slice(),
tags,
disable_ssl,
offline,
),
RefspecStrategy::First => {
// Try each refspec
let mut errors = refspecs
.iter()
.map_while(|refspec| {
let fetch_result = fetch_with_cli(
repo,
remote_url,
std::slice::from_ref(refspec),
tags,
disable_ssl,
offline,
);
// Stop after the first success and log failures
match fetch_result {
Err(ref err) => {
debug!("Failed to fetch refspec `{refspec}`: {err}");
Some(fetch_result)
}
Ok(()) => None,
}
})
.collect::<Vec<_>>();
if errors.len() == refspecs.len() {
if let Some(result) = errors.pop() {
// Use the last error for the message
result
} else {
// Can only occur if there were no refspecs to fetch
Ok(())
}
} else {
Ok(())
}
}
};
match reference {
// With the default branch, adding context is confusing
ReferenceOrOid::Reference(GitReference::DefaultBranch) => result,
_ => result.with_context(|| {
format!(
"failed to fetch {} `{}`",
reference.kind_str(),
reference.as_rev()
)
}),
}
}
/// Attempts to use `git` CLI installed on the system to fetch a repository.
fn fetch_with_cli(
repo: &mut GitRepository,
url: &Url,
refspecs: &[String],
tags: bool,
disable_ssl: bool,
offline: bool,
) -> Result<()> {
let mut cmd = ProcessBuilder::new(GIT.as_ref()?);
// Disable interactive prompts in the terminal, as they'll be erased by the progress bar
// animation and the process will "hang". Interactive prompts via the GUI like `SSH_ASKPASS`
// are still usable.
cmd.env(EnvVars::GIT_TERMINAL_PROMPT, "0");
cmd.arg("fetch");
if tags {
cmd.arg("--tags");
}
if disable_ssl {
debug!("Disabling SSL verification for Git fetch via `GIT_SSL_NO_VERIFY`");
cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
}
if offline {
debug!("Disabling remote protocols for Git fetch via `GIT_ALLOW_PROTOCOL=file`");
cmd.env(EnvVars::GIT_ALLOW_PROTOCOL, "file");
}
cmd.arg("--force") // handle force pushes
.arg("--update-head-ok") // see discussion in #2078
.arg(url.as_str())
.args(refspecs)
// If cargo is run by git (for example, the `exec` command in `git
// rebase`), the GIT_DIR is set by git and will point to the wrong
// location (this takes precedence over the cwd). Make sure this is
// unset so git will look at cwd for the repo.
.env_remove(EnvVars::GIT_DIR)
// The reset of these may not be necessary, but I'm including them
// just to be extra paranoid and avoid any issues.
.env_remove(EnvVars::GIT_WORK_TREE)
.env_remove(EnvVars::GIT_INDEX_FILE)
.env_remove(EnvVars::GIT_OBJECT_DIRECTORY)
.env_remove(EnvVars::GIT_ALTERNATE_OBJECT_DIRECTORIES)
.cwd(&repo.path);
// We capture the output to avoid streaming it to the user's console during clones.
// The required `on...line` callbacks currently do nothing.
// The output appears to be included in error messages by default.
cmd.exec_with_output().map_err(|err| {
let msg = err.to_string();
if msg.contains("transport '") && msg.contains("' not allowed") && offline {
return GitError::TransportNotAllowed.into();
}
err
})?;
Ok(())
}
/// A global cache of the `git lfs` command.
///
/// Returns an error if Git LFS isn't available.
/// Caching the command allows us to only check if LFS is installed once.
///
/// We also support a helper private environment variable to allow
/// controlling the LFS extension from being loaded for testing purposes.
/// Once installed, Git will always load `git-lfs` as a built-in alias
/// which takes priority over loading from `PATH` which prevents us
/// from shadowing the extension with other means.
pub static GIT_LFS: LazyLock<Result<ProcessBuilder>> = LazyLock::new(|| {
if std::env::var_os(EnvVars::UV_INTERNAL__TEST_LFS_DISABLED).is_some() {
return Err(anyhow!("Git LFS extension has been forcefully disabled."));
}
let mut cmd = ProcessBuilder::new(GIT.as_ref()?);
cmd.arg("lfs");
// Run a simple command to verify LFS is installed
cmd.clone().arg("version").exec_with_output()?;
Ok(cmd)
});
/// Attempts to use `git-lfs` CLI to fetch required LFS objects for a given revision.
fn fetch_lfs(
repo: &mut GitRepository,
url: &Url,
revision: &GitOid,
disable_ssl: bool,
) -> Result<bool> {
let mut cmd = if let Ok(lfs) = GIT_LFS.as_ref() {
debug!("Fetching Git LFS objects");
lfs.clone()
} else {
// Since this feature is opt-in, warn if not available
warn!("Git LFS is not available, skipping LFS fetch");
return Ok(false);
};
if disable_ssl {
debug!("Disabling SSL verification for Git LFS");
cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
}
cmd.arg("fetch")
.arg(url.as_str())
.arg(revision.as_str())
// These variables are unset for the same reason as in `fetch_with_cli`.
.env_remove(EnvVars::GIT_DIR)
.env_remove(EnvVars::GIT_WORK_TREE)
.env_remove(EnvVars::GIT_INDEX_FILE)
.env_remove(EnvVars::GIT_OBJECT_DIRECTORY)
.env_remove(EnvVars::GIT_ALTERNATE_OBJECT_DIRECTORIES)
// We should not support requesting LFS artifacts with skip smudge being set.
// While this may not be necessary, it's added to avoid any potential future issues.
.env_remove(EnvVars::GIT_LFS_SKIP_SMUDGE)
.cwd(&repo.path);
cmd.exec_with_output()?;
// We now validate the Git LFS objects explicitly (if supported). This is
// needed to avoid issues with Git LFS not being installed or configured
// on the system and giving the wrong impression to the user that Git LFS
// objects were initialized correctly when installation finishes.
// We may want to allow the user to skip validation in the future via
// UV_GIT_LFS_NO_VALIDATION environment variable on rare cases where
// validation costs outweigh the benefit.
let validation_result = repo.lfs_fsck_objects(revision.as_str());
Ok(validation_result)
}
/// Whether `rev` is a shorter hash of `oid`.
fn is_short_hash_of(rev: &str, oid: GitOid) -> bool {
let long_hash = oid.to_string();
match long_hash.get(..rev.len()) {
Some(truncated_long_hash) => truncated_long_hash.eq_ignore_ascii_case(rev),
None => 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-git/src/credentials.rs | crates/uv-git/src/credentials.rs | use std::collections::HashMap;
use std::sync::{Arc, LazyLock, RwLock};
use tracing::trace;
use uv_auth::Credentials;
use uv_cache_key::RepositoryUrl;
use uv_redacted::DisplaySafeUrl;
/// Global authentication cache for a uv invocation.
///
/// This is used to share Git credentials within a single process.
pub static GIT_STORE: LazyLock<GitStore> = LazyLock::new(GitStore::default);
/// A store for Git credentials.
#[derive(Debug, Default)]
pub struct GitStore(RwLock<HashMap<RepositoryUrl, Arc<Credentials>>>);
impl GitStore {
/// Insert [`Credentials`] for the given URL into the store.
pub fn insert(&self, url: RepositoryUrl, credentials: Credentials) -> Option<Arc<Credentials>> {
self.0.write().unwrap().insert(url, Arc::new(credentials))
}
/// Get the [`Credentials`] for the given URL, if they exist.
pub fn get(&self, url: &RepositoryUrl) -> Option<Arc<Credentials>> {
self.0.read().unwrap().get(url).cloned()
}
}
/// Populate the global authentication store with credentials on a Git URL, if there are any.
///
/// Returns `true` if the store was updated.
pub fn store_credentials_from_url(url: &DisplaySafeUrl) -> bool {
if let Some(credentials) = Credentials::from_url(url) {
trace!("Caching credentials for {url}");
GIT_STORE.insert(RepositoryUrl::new(url), credentials);
true
} else {
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-git/src/resolver.rs | crates/uv-git/src/resolver.rs | use std::borrow::Cow;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use dashmap::DashMap;
use dashmap::mapref::one::Ref;
use fs_err::tokio as fs;
use reqwest_middleware::ClientWithMiddleware;
use tracing::debug;
use uv_cache_key::{RepositoryUrl, cache_digest};
use uv_fs::{LockedFile, LockedFileError, LockedFileMode};
use uv_git_types::{GitHubRepository, GitOid, GitReference, GitUrl};
use uv_static::EnvVars;
use uv_version::version;
use crate::{
Fetch, GitSource, Reporter,
rate_limit::{GITHUB_RATE_LIMIT_STATUS, is_github_rate_limited},
};
#[derive(Debug, thiserror::Error)]
pub enum GitResolverError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
LockedFile(#[from] LockedFileError),
#[error(transparent)]
Join(#[from] tokio::task::JoinError),
#[error("Git operation failed")]
Git(#[source] anyhow::Error),
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error(transparent)]
ReqwestMiddleware(#[from] reqwest_middleware::Error),
}
/// A resolver for Git repositories.
#[derive(Default, Clone)]
pub struct GitResolver(Arc<DashMap<RepositoryReference, GitOid>>);
impl GitResolver {
/// Inserts a new [`GitOid`] for the given [`RepositoryReference`].
pub fn insert(&self, reference: RepositoryReference, sha: GitOid) {
self.0.insert(reference, sha);
}
/// Returns the [`GitOid`] for the given [`RepositoryReference`], if it exists.
fn get(&self, reference: &RepositoryReference) -> Option<Ref<'_, RepositoryReference, GitOid>> {
self.0.get(reference)
}
/// Return the [`GitOid`] for the given [`GitUrl`], if it is already known.
pub fn get_precise(&self, url: &GitUrl) -> Option<GitOid> {
// If the URL is already precise, return it.
if let Some(precise) = url.precise() {
return Some(precise);
}
// If we know the precise commit already, return it.
let reference = RepositoryReference::from(url);
if let Some(precise) = self.get(&reference) {
return Some(*precise);
}
None
}
/// Resolve a Git URL to a specific commit without performing any Git operations.
///
/// Returns a [`GitOid`] if the URL has already been resolved (i.e., is available in the cache),
/// or if it can be fetched via the GitHub API. Otherwise, returns `None`.
pub async fn github_fast_path(
&self,
url: &GitUrl,
client: &ClientWithMiddleware,
) -> Result<Option<GitOid>, GitResolverError> {
if std::env::var_os(EnvVars::UV_NO_GITHUB_FAST_PATH).is_some() {
return Ok(None);
}
// If the URL is already precise or we know the precise commit, return it.
if let Some(precise) = self.get_precise(url) {
return Ok(Some(precise));
}
// If the URL is a GitHub URL, attempt to resolve it via the GitHub API.
let Some(GitHubRepository { owner, repo }) = GitHubRepository::parse(url.repository())
else {
return Ok(None);
};
// Check if we're rate-limited by GitHub, before determining the Git reference
if GITHUB_RATE_LIMIT_STATUS.is_active() {
debug!("Rate-limited by GitHub. Skipping GitHub fast path attempt for: {url}");
return Ok(None);
}
// Determine the Git reference.
let rev = url.reference().as_rev();
let github_api_base_url = std::env::var(EnvVars::UV_GITHUB_FAST_PATH_URL)
.unwrap_or("https://api.github.com/repos".to_owned());
let github_api_url = format!("{github_api_base_url}/{owner}/{repo}/commits/{rev}");
debug!("Querying GitHub for commit at: {github_api_url}");
let mut request = client.get(&github_api_url);
request = request.header("Accept", "application/vnd.github.3.sha");
request = request.header(
"User-Agent",
format!("uv/{} (+https://github.com/astral-sh/uv)", version()),
);
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
// Returns a 404 if the repository does not exist, and a 422 if GitHub is unable to
// resolve the requested rev.
debug!(
"GitHub API request failed for: {github_api_url} ({})",
response.status()
);
if is_github_rate_limited(&response) {
// Mark that we are being rate-limited by GitHub
GITHUB_RATE_LIMIT_STATUS.activate();
}
return Ok(None);
}
// Parse the response as a Git SHA.
let precise = response.text().await?;
let precise =
GitOid::from_str(&precise).map_err(|err| GitResolverError::Git(err.into()))?;
// Insert the resolved URL into the in-memory cache. This ensures that subsequent fetches
// resolve to the same precise commit.
self.insert(RepositoryReference::from(url), precise);
Ok(Some(precise))
}
/// Fetch a remote Git repository.
pub async fn fetch(
&self,
url: &GitUrl,
disable_ssl: bool,
offline: bool,
cache: PathBuf,
reporter: Option<Arc<dyn Reporter>>,
) -> Result<Fetch, GitResolverError> {
debug!("Fetching source distribution from Git: {url}");
let reference = RepositoryReference::from(url);
// If we know the precise commit already, reuse it, to ensure that all fetches within a
// single process are consistent.
let url = {
if let Some(precise) = self.get(&reference) {
Cow::Owned(url.clone().with_precise(*precise))
} else {
Cow::Borrowed(url)
}
};
// Avoid races between different processes, too.
let lock_dir = cache.join("locks");
fs::create_dir_all(&lock_dir).await?;
let repository_url = RepositoryUrl::new(url.repository());
let _lock = LockedFile::acquire(
lock_dir.join(cache_digest(&repository_url)),
LockedFileMode::Exclusive,
&repository_url,
)
.await?;
// Fetch the Git repository.
let source = if let Some(reporter) = reporter {
GitSource::new(url.as_ref().clone(), cache, offline).with_reporter(reporter)
} else {
GitSource::new(url.as_ref().clone(), cache, offline)
};
// If necessary, disable SSL.
let source = if disable_ssl {
source.dangerous()
} else {
source
};
let fetch = tokio::task::spawn_blocking(move || source.fetch())
.await?
.map_err(GitResolverError::Git)?;
// Insert the resolved URL into the in-memory cache. This ensures that subsequent fetches
// resolve to the same precise commit.
if let Some(precise) = fetch.git().precise() {
self.insert(reference, precise);
}
Ok(fetch)
}
/// Given a remote source distribution, return a precise variant, if possible.
///
/// For example, given a Git dependency with a reference to a branch or tag, return a URL
/// with a precise reference to the current commit of that branch or tag.
///
/// This method takes into account various normalizations that are independent of the Git
/// layer. For example: removing `#subdirectory=pkg_dir`-like fragments, and removing `git+`
/// prefix kinds.
///
/// This method will only return precise URLs for URLs that have already been resolved via
/// [`resolve_precise`], and will return `None` for URLs that have not been resolved _or_
/// already have a precise reference.
pub fn precise(&self, url: GitUrl) -> Option<GitUrl> {
let reference = RepositoryReference::from(&url);
let precise = self.get(&reference)?;
Some(url.with_precise(*precise))
}
/// Returns `true` if the two Git URLs refer to the same precise commit.
pub fn same_ref(&self, a: &GitUrl, b: &GitUrl) -> bool {
// Convert `a` to a repository URL.
let a_ref = RepositoryReference::from(a);
// Convert `b` to a repository URL.
let b_ref = RepositoryReference::from(b);
// The URLs must refer to the same repository.
if a_ref.url != b_ref.url {
return false;
}
// If the URLs have the same tag, they refer to the same commit.
if a_ref.reference == b_ref.reference {
return true;
}
// Otherwise, the URLs must resolve to the same precise commit.
let Some(a_precise) = a.precise().or_else(|| self.get(&a_ref).map(|sha| *sha)) else {
return false;
};
let Some(b_precise) = b.precise().or_else(|| self.get(&b_ref).map(|sha| *sha)) else {
return false;
};
a_precise == b_precise
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ResolvedRepositoryReference {
/// An abstract reference to a Git repository, including the URL and the commit (e.g., a branch,
/// tag, or revision).
pub reference: RepositoryReference,
/// The precise commit SHA of the reference.
pub sha: GitOid,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RepositoryReference {
/// The URL of the Git repository, with any query parameters and fragments removed.
pub url: RepositoryUrl,
/// The reference to the commit to use, which could be a branch, tag, or revision.
pub reference: GitReference,
}
impl From<&GitUrl> for RepositoryReference {
fn from(git: &GitUrl) -> Self {
Self {
url: RepositoryUrl::new(git.repository()),
reference: git.reference().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-shell/src/shlex.rs | crates/uv-shell/src/shlex.rs | use crate::{Shell, Simplified};
use std::path::Path;
/// Quote a path, if necessary, for safe use in a POSIX-compatible shell command.
pub fn shlex_posix(executable: impl AsRef<Path>) -> String {
// Convert to a display path.
let executable = executable.as_ref().portable_display().to_string();
// Like Python's `shlex.quote`:
// > Use single quotes, and put single quotes into double quotes
// > The string $'b is then quoted as '$'"'"'b'
if executable.contains(' ') {
format!("'{}'", escape_posix_for_single_quotes(&executable))
} else {
executable
}
}
/// Escape a string for being used in single quotes in a POSIX-compatible shell command.
///
/// We want our scripts to support any POSIX shell. There are two kinds of quotes in POSIX:
/// Single and double quotes. In bash, single quotes must not contain another single
/// quote, you can't even escape it (<https://linux.die.net/man/1/bash> under "QUOTING").
/// Double quotes have escaping rules that differ from shell to shell, which we can't handle.
/// Bash has `$'\''`, but that's not universal enough.
///
/// As a solution, use implicit string concatenations, by putting the single quote into double
/// quotes.
pub fn escape_posix_for_single_quotes(string: &str) -> String {
string.replace('\'', r#"'"'"'"#)
}
/// Quote a path, if necessary, for safe use in `PowerShell` and `cmd`.
pub fn shlex_windows(executable: impl AsRef<Path>, shell: Shell) -> String {
// Convert to a display path.
let executable = executable.as_ref().user_display().to_string();
// Wrap the executable in quotes (and a `&` invocation on PowerShell), if it contains spaces.
if executable.contains(' ') {
if shell == Shell::Powershell {
// For PowerShell, wrap in a `&` invocation.
format!("& \"{executable}\"")
} else {
// Otherwise, assume `cmd`, which doesn't need the `&`.
format!("\"{executable}\"")
}
} else {
executable
}
}
| 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-shell/src/lib.rs | crates/uv-shell/src/lib.rs | pub mod runnable;
mod shlex;
pub mod windows;
pub use shlex::{escape_posix_for_single_quotes, shlex_posix, shlex_windows};
use std::env::home_dir;
use std::path::{Path, PathBuf};
use uv_fs::Simplified;
use uv_static::EnvVars;
#[cfg(unix)]
use tracing::debug;
/// Shells for which virtualenv activation scripts are available.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[allow(clippy::doc_markdown)]
pub enum Shell {
/// Bourne Again SHell (bash)
Bash,
/// Friendly Interactive SHell (fish)
Fish,
/// PowerShell
Powershell,
/// Cmd (Command Prompt)
Cmd,
/// Z SHell (zsh)
Zsh,
/// Nushell
Nushell,
/// C SHell (csh)
Csh,
/// Korn SHell (ksh)
Ksh,
}
impl Shell {
/// Determine the user's current shell from the environment.
///
/// This will read the `SHELL` environment variable and try to determine which shell is in use
/// from that.
///
/// If `SHELL` is not set, then on windows, it will default to powershell, and on
/// other `OSes` it will return `None`.
///
/// If `SHELL` is set, but contains a value that doesn't correspond to one of the supported
/// shell types, then return `None`.
pub fn from_env() -> Option<Self> {
if std::env::var_os(EnvVars::NU_VERSION).is_some() {
Some(Self::Nushell)
} else if std::env::var_os(EnvVars::FISH_VERSION).is_some() {
Some(Self::Fish)
} else if std::env::var_os(EnvVars::BASH_VERSION).is_some() {
Some(Self::Bash)
} else if std::env::var_os(EnvVars::ZSH_VERSION).is_some() {
Some(Self::Zsh)
} else if std::env::var_os(EnvVars::KSH_VERSION).is_some() {
Some(Self::Ksh)
} else if let Some(env_shell) = std::env::var_os(EnvVars::SHELL) {
Self::from_shell_path(env_shell)
} else if cfg!(windows) {
// Command Prompt relies on PROMPT for its appearance whereas PowerShell does not.
// See: https://stackoverflow.com/a/66415037.
if std::env::var_os(EnvVars::PROMPT).is_some() {
Some(Self::Cmd)
} else {
// Fallback to PowerShell if the PROMPT environment variable is not set.
Some(Self::Powershell)
}
} else {
// Fallback to detecting the shell from the parent process
Self::from_parent_process()
}
}
/// Attempt to determine the shell from the parent process.
///
/// This is a fallback method for when environment variables don't provide
/// enough information about the current shell. It looks at the parent process
/// to try to identify which shell is running.
///
/// This method currently only works on Unix-like systems. On other platforms,
/// it returns `None`.
fn from_parent_process() -> Option<Self> {
#[cfg(unix)]
{
// Get the parent process ID
let ppid = nix::unistd::getppid();
debug!("Detected parent process ID: {ppid}");
// Try to read the parent process executable path
let proc_exe_path = format!("/proc/{ppid}/exe");
if let Ok(exe_path) = fs_err::read_link(&proc_exe_path) {
debug!("Parent process executable: {}", exe_path.display());
if let Some(shell) = Self::from_shell_path(&exe_path) {
return Some(shell);
}
}
// If reading exe fails, try reading the comm file
let proc_comm_path = format!("/proc/{ppid}/comm");
if let Ok(comm) = fs_err::read_to_string(&proc_comm_path) {
let comm = comm.trim();
debug!("Parent process comm: {comm}");
if let Some(shell) = parse_shell_from_path(Path::new(comm)) {
return Some(shell);
}
}
debug!("Could not determine shell from parent process");
None
}
#[cfg(not(unix))]
{
None
}
}
/// Parse a shell from a path to the executable for the shell.
///
/// # Examples
///
/// ```ignore
/// use crate::shells::Shell;
///
/// assert_eq!(Shell::from_shell_path("/bin/bash"), Some(Shell::Bash));
/// assert_eq!(Shell::from_shell_path("/usr/bin/zsh"), Some(Shell::Zsh));
/// assert_eq!(Shell::from_shell_path("/opt/my_custom_shell"), None);
/// ```
pub fn from_shell_path(path: impl AsRef<Path>) -> Option<Self> {
parse_shell_from_path(path.as_ref())
}
/// Returns `true` if the shell supports a `PATH` update command.
pub fn supports_update(self) -> bool {
match self {
Self::Powershell | Self::Cmd => true,
shell => !shell.configuration_files().is_empty(),
}
}
/// Return the configuration files that should be modified to append to a shell's `PATH`.
///
/// Some of the logic here is based on rustup's rc file detection.
///
/// See: <https://github.com/rust-lang/rustup/blob/fede22fea7b160868cece632bd213e6d72f8912f/src/cli/self_update/shell.rs#L197>
pub fn configuration_files(self) -> Vec<PathBuf> {
let Some(home_dir) = home_dir() else {
return vec![];
};
match self {
Self::Bash => {
// On Bash, we need to update both `.bashrc` and `.bash_profile`. The former is
// sourced for non-login shells, and the latter is sourced for login shells.
//
// In lieu of `.bash_profile`, shells will also respect `.bash_login` and
// `.profile`, if they exist. So we respect those too.
vec![
[".bash_profile", ".bash_login", ".profile"]
.iter()
.map(|rc| home_dir.join(rc))
.find(|rc| rc.is_file())
.unwrap_or_else(|| home_dir.join(".bash_profile")),
home_dir.join(".bashrc"),
]
}
Self::Ksh => {
// On Ksh it's standard POSIX `.profile` for login shells, and `.kshrc` for non-login.
vec![home_dir.join(".profile"), home_dir.join(".kshrc")]
}
Self::Zsh => {
// On Zsh, we only need to update `.zshenv`. This file is sourced for both login and
// non-login shells. However, we match rustup's logic for determining _which_
// `.zshenv` to use.
//
// See: https://github.com/rust-lang/rustup/blob/fede22fea7b160868cece632bd213e6d72f8912f/src/cli/self_update/shell.rs#L197
let zsh_dot_dir = std::env::var(EnvVars::ZDOTDIR)
.ok()
.filter(|dir| !dir.is_empty())
.map(PathBuf::from);
// Attempt to update an existing `.zshenv` file.
if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
// If `ZDOTDIR` is set, and `ZDOTDIR/.zshenv` exists, then we update that file.
let zshenv = zsh_dot_dir.join(".zshenv");
if zshenv.is_file() {
return vec![zshenv];
}
}
// Whether `ZDOTDIR` is set or not, if `~/.zshenv` exists then we update that file.
let zshenv = home_dir.join(".zshenv");
if zshenv.is_file() {
return vec![zshenv];
}
if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
// If `ZDOTDIR` is set, then we create `ZDOTDIR/.zshenv`.
vec![zsh_dot_dir.join(".zshenv")]
} else {
// If `ZDOTDIR` is _not_ set, then we create `~/.zshenv`.
vec![home_dir.join(".zshenv")]
}
}
Self::Fish => {
// On Fish, we only need to update `config.fish`. This file is sourced for both
// login and non-login shells. However, we must respect Fish's logic, which reads
// from `$XDG_CONFIG_HOME/fish/config.fish` if set, and `~/.config/fish/config.fish`
// otherwise.
if let Some(xdg_home_dir) = std::env::var(EnvVars::XDG_CONFIG_HOME)
.ok()
.filter(|dir| !dir.is_empty())
.map(PathBuf::from)
{
vec![xdg_home_dir.join("fish/config.fish")]
} else {
vec![home_dir.join(".config/fish/config.fish")]
}
}
Self::Csh => {
// On Csh, we need to update both `.cshrc` and `.login`, like Bash.
vec![home_dir.join(".cshrc"), home_dir.join(".login")]
}
// TODO(charlie): Add support for Nushell.
Self::Nushell => vec![],
// See: [`crate::windows::prepend_path`].
Self::Powershell => vec![],
// See: [`crate::windows::prepend_path`].
Self::Cmd => vec![],
}
}
/// Returns `true` if the given path is on the `PATH` in this shell.
pub fn contains_path(path: &Path) -> bool {
let home_dir = home_dir();
std::env::var_os(EnvVars::PATH)
.as_ref()
.iter()
.flat_map(std::env::split_paths)
.map(|path| {
// If the first component is `~`, expand to the home directory.
if let Some(home_dir) = home_dir.as_ref() {
if path
.components()
.next()
.map(std::path::Component::as_os_str)
== Some("~".as_ref())
{
return home_dir.join(path.components().skip(1).collect::<PathBuf>());
}
}
path
})
.any(|p| same_file::is_same_file(path, p).unwrap_or(false))
}
/// Returns the command necessary to prepend a directory to the `PATH` in this shell.
pub fn prepend_path(self, path: &Path) -> Option<String> {
match self {
Self::Nushell => None,
Self::Bash | Self::Zsh | Self::Ksh => Some(format!(
"export PATH=\"{}:$PATH\"",
backslash_escape(&path.simplified_display().to_string()),
)),
Self::Fish => Some(format!(
"fish_add_path \"{}\"",
backslash_escape(&path.simplified_display().to_string()),
)),
Self::Csh => Some(format!(
"setenv PATH \"{}:$PATH\"",
backslash_escape(&path.simplified_display().to_string()),
)),
Self::Powershell => Some(format!(
"$env:PATH = \"{};$env:PATH\"",
backtick_escape(&path.simplified_display().to_string()),
)),
Self::Cmd => Some(format!(
"set PATH=\"{};%PATH%\"",
backslash_escape(&path.simplified_display().to_string()),
)),
}
}
}
impl std::fmt::Display for Shell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bash => write!(f, "Bash"),
Self::Fish => write!(f, "Fish"),
Self::Powershell => write!(f, "PowerShell"),
Self::Cmd => write!(f, "Command Prompt"),
Self::Zsh => write!(f, "Zsh"),
Self::Nushell => write!(f, "Nushell"),
Self::Csh => write!(f, "Csh"),
Self::Ksh => write!(f, "Ksh"),
}
}
}
/// Parse the shell from the name of the shell executable.
fn parse_shell_from_path(path: &Path) -> Option<Shell> {
let name = path.file_stem()?.to_str()?;
match name {
"bash" => Some(Shell::Bash),
"zsh" => Some(Shell::Zsh),
"fish" => Some(Shell::Fish),
"csh" => Some(Shell::Csh),
"ksh" => Some(Shell::Ksh),
"powershell" | "powershell_ise" => Some(Shell::Powershell),
_ => None,
}
}
/// Escape a string for use in a shell command by inserting backslashes.
fn backslash_escape(s: &str) -> String {
let mut escaped = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' | '"' => escaped.push('\\'),
_ => {}
}
escaped.push(c);
}
escaped
}
/// Escape a string for use in a `PowerShell` command by inserting backticks.
fn backtick_escape(s: &str) -> String {
let mut escaped = String::with_capacity(s.len());
for c in s.chars() {
match c {
// Need to also escape unicode double quotes that PowerShell treats
// as the ASCII double quote.
'"' | '`' | '\u{201C}' | '\u{201D}' | '\u{201E}' | '$' => escaped.push('`'),
_ => {}
}
escaped.push(c);
}
escaped
}
#[cfg(test)]
mod tests {
use super::*;
use fs_err::File;
use temp_env::with_vars;
use tempfile::tempdir;
// First option used by std::env::home_dir.
const HOME_DIR_ENV_VAR: &str = if cfg!(windows) {
EnvVars::USERPROFILE
} else {
EnvVars::HOME
};
#[test]
fn configuration_files_zsh_no_existing_zshenv() {
let tmp_home_dir = tempdir().unwrap();
let tmp_zdotdir = tempdir().unwrap();
with_vars(
[
(EnvVars::ZDOTDIR, None),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
with_vars(
[
(EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_zdotdir.path().join(".zshenv")]
);
},
);
}
#[test]
fn configuration_files_zsh_existing_home_zshenv() {
let tmp_home_dir = tempdir().unwrap();
File::create(tmp_home_dir.path().join(".zshenv")).unwrap();
let tmp_zdotdir = tempdir().unwrap();
with_vars(
[
(EnvVars::ZDOTDIR, None),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
with_vars(
[
(EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
}
#[test]
fn configuration_files_zsh_existing_zdotdir_zshenv() {
let tmp_home_dir = tempdir().unwrap();
let tmp_zdotdir = tempdir().unwrap();
File::create(tmp_zdotdir.path().join(".zshenv")).unwrap();
with_vars(
[
(EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_zdotdir.path().join(".zshenv")]
);
},
);
}
}
| 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-shell/src/windows.rs | crates/uv-shell/src/windows.rs | //! Windows-specific utilities for manipulating the environment.
//!
//! Based on rustup's Windows implementation: <https://github.com/rust-lang/rustup/commit/bce3ed67d219a2b754857f9e231287794d8c770d>
#![cfg(windows)]
use std::path::Path;
use anyhow::Context;
use tracing::warn;
use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_INVALID_DATA};
use windows::core::HRESULT;
use windows_registry::{CURRENT_USER, HSTRING};
use uv_static::EnvVars;
/// Append the given [`Path`] to the `PATH` environment variable in the Windows registry.
///
/// Returns `Ok(true)` if the path was successfully appended, and `Ok(false)` if the path was
/// already in `PATH`.
pub fn prepend_path(path: &Path) -> anyhow::Result<bool> {
// Get the existing `PATH` variable from the registry.
let windows_path = get_windows_path_var()?;
// Add the new path to the existing `PATH` variable.
let windows_path =
windows_path.and_then(|windows_path| prepend_to_path(&windows_path, HSTRING::from(path)));
// If the path didn't change, then we don't need to do anything.
let Some(windows_path) = windows_path else {
return Ok(false);
};
// Set the `PATH` variable in the registry.
apply_windows_path_var(&windows_path)?;
Ok(true)
}
/// Set the windows `PATH` variable in the registry.
fn apply_windows_path_var(path: &HSTRING) -> anyhow::Result<()> {
let environment = CURRENT_USER.create("Environment")?;
if path.is_empty() {
environment.remove_value(EnvVars::PATH)?;
} else {
environment.set_expand_hstring(EnvVars::PATH, path)?;
}
Ok(())
}
/// Retrieve the windows `PATH` variable from the registry.
///
/// Returns `Ok(None)` if the `PATH` variable is not a string.
fn get_windows_path_var() -> anyhow::Result<Option<HSTRING>> {
let environment = CURRENT_USER
.create("Environment")
.context("Failed to open `Environment` key")?;
let reg_value = environment.get_hstring(EnvVars::PATH);
match reg_value {
Ok(reg_value) => Ok(Some(reg_value)),
Err(err) if err.code() == HRESULT::from(ERROR_INVALID_DATA) => {
warn!("`HKEY_CURRENT_USER\\Environment\\PATH` is a non-string");
Ok(None)
}
Err(err) if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) => Ok(Some(HSTRING::new())),
Err(err) => Err(err.into()),
}
}
/// Prepend a path to the `PATH` variable in the Windows registry.
///
/// Returns `Ok(None)` if the given path is already in `PATH`.
fn prepend_to_path(existing_path: &HSTRING, path: HSTRING) -> Option<HSTRING> {
if existing_path.is_empty() {
Some(path)
} else if existing_path.windows(path.len()).any(|p| *p == *path) {
None
} else {
let mut new_path = path.to_os_string();
new_path.push(";");
new_path.push(existing_path.to_os_string());
Some(HSTRING::from(new_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-shell/src/runnable.rs | crates/uv-shell/src/runnable.rs | //! Utilities for running executables and scripts. Particularly in Windows.
use std::env::consts::EXE_EXTENSION;
use std::ffi::OsStr;
use std::path::Path;
use std::process::Command;
use uv_fs::with_added_extension;
#[derive(Debug)]
pub enum WindowsRunnable {
/// Windows PE (.exe)
Executable,
/// `PowerShell` script (.ps1)
PowerShell,
/// Command Prompt NT script (.cmd)
Command,
/// Command Prompt script (.bat)
Batch,
}
impl WindowsRunnable {
/// Returns a list of all supported Windows runnable types.
fn all() -> &'static [Self] {
&[
Self::Executable,
Self::PowerShell,
Self::Command,
Self::Batch,
]
}
/// Returns the extension for a given Windows runnable type.
fn to_extension(&self) -> &'static str {
match self {
Self::Executable => EXE_EXTENSION,
Self::PowerShell => "ps1",
Self::Command => "cmd",
Self::Batch => "bat",
}
}
/// Determines the runnable type from a given Windows file extension.
fn from_extension(ext: &str) -> Option<Self> {
match ext {
EXE_EXTENSION => Some(Self::Executable),
"ps1" => Some(Self::PowerShell),
"cmd" => Some(Self::Command),
"bat" => Some(Self::Batch),
_ => None,
}
}
/// Returns a [`Command`] to run the given type under the appropriate Windows runtime.
fn as_command(&self, runnable_path: &Path) -> Command {
match self {
Self::Executable => Command::new(runnable_path),
Self::PowerShell => {
let mut cmd = Command::new("powershell");
cmd.arg("-NoLogo").arg("-File").arg(runnable_path);
cmd
}
Self::Command | Self::Batch => {
let mut cmd = Command::new("cmd");
cmd.arg("/q").arg("/c").arg(runnable_path);
cmd
}
}
}
/// Handle console and legacy setuptools scripts for Windows.
///
/// Returns [`Command`] that can be used to invoke a supported runnable on Windows
/// under the scripts path of an interpreter environment.
pub fn from_script_path(script_path: &Path, runnable_name: &OsStr) -> Command {
let script_path = script_path.join(runnable_name);
// Honor explicit extension if provided and recognized.
if let Some(script_type) = script_path
.extension()
.and_then(OsStr::to_str)
.and_then(Self::from_extension)
.filter(|_| script_path.is_file())
{
return script_type.as_command(&script_path);
}
// Guess the extension when an explicit one is not provided.
// We also add the extension when missing since for some types (e.g. PowerShell) it must be explicit.
Self::all()
.iter()
.map(|script_type| {
(
script_type,
with_added_extension(&script_path, script_type.to_extension()),
)
})
.find(|(_, script_path)| script_path.is_file())
.map(|(script_type, script_path)| script_type.as_command(&script_path))
.unwrap_or_else(|| Command::new(runnable_name))
}
}
#[cfg(test)]
mod tests {
#[cfg(target_os = "windows")]
use super::WindowsRunnable;
#[cfg(target_os = "windows")]
use fs_err as fs;
#[cfg(target_os = "windows")]
use std::ffi::OsStr;
#[cfg(target_os = "windows")]
use std::io;
/// Helper function to create a temporary directory with test files
#[cfg(target_os = "windows")]
fn create_test_environment() -> io::Result<tempfile::TempDir> {
let temp_dir = tempfile::tempdir()?;
let scripts_dir = temp_dir.path().join("Scripts");
fs::create_dir_all(&scripts_dir)?;
// Create test executable files
fs::write(scripts_dir.join("python.exe"), "")?;
fs::write(scripts_dir.join("awslabs.cdk-mcp-server.exe"), "")?;
fs::write(scripts_dir.join("org.example.tool.exe"), "")?;
fs::write(scripts_dir.join("multi.dot.package.name.exe"), "")?;
fs::write(scripts_dir.join("script.ps1"), "")?;
fs::write(scripts_dir.join("batch.bat"), "")?;
fs::write(scripts_dir.join("command.cmd"), "")?;
fs::write(scripts_dir.join("explicit.ps1"), "")?;
Ok(temp_dir)
}
#[cfg(target_os = "windows")]
#[test]
fn test_from_script_path_single_dot_package() {
let temp_dir = create_test_environment().expect("Failed to create test environment");
let scripts_dir = temp_dir.path().join("Scripts");
// Test package name with single dot (awslabs.cdk-mcp-server)
let command =
WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("awslabs.cdk-mcp-server"));
// The command should be constructed with the correct executable path
let expected_path = scripts_dir.join("awslabs.cdk-mcp-server.exe");
assert_eq!(command.get_program(), expected_path.as_os_str());
}
#[cfg(target_os = "windows")]
#[test]
fn test_from_script_path_multiple_dots_package() {
let temp_dir = create_test_environment().expect("Failed to create test environment");
let scripts_dir = temp_dir.path().join("Scripts");
// Test package name with multiple dots (org.example.tool)
let command =
WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("org.example.tool"));
let expected_path = scripts_dir.join("org.example.tool.exe");
assert_eq!(command.get_program(), expected_path.as_os_str());
// Test another multi-dot package
let command =
WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("multi.dot.package.name"));
let expected_path = scripts_dir.join("multi.dot.package.name.exe");
assert_eq!(command.get_program(), expected_path.as_os_str());
}
#[cfg(target_os = "windows")]
#[test]
fn test_from_script_path_simple_package_name() {
let temp_dir = create_test_environment().expect("Failed to create test environment");
let scripts_dir = temp_dir.path().join("Scripts");
// Test simple package name without dots
let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("python"));
let expected_path = scripts_dir.join("python.exe");
assert_eq!(command.get_program(), expected_path.as_os_str());
}
#[cfg(target_os = "windows")]
#[test]
fn test_from_script_path_explicit_extensions() {
let temp_dir = create_test_environment().expect("Failed to create test environment");
let scripts_dir = temp_dir.path().join("Scripts");
// Test explicit .ps1 extension
let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("explicit.ps1"));
let expected_path = scripts_dir.join("explicit.ps1");
assert_eq!(command.get_program(), "powershell");
// Verify the arguments contain the script path
let args: Vec<&OsStr> = command.get_args().collect();
assert!(args.contains(&OsStr::new("-File")));
assert!(args.contains(&expected_path.as_os_str()));
// Test explicit .bat extension
let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("batch.bat"));
assert_eq!(command.get_program(), "cmd");
// Test explicit .cmd extension
let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("command.cmd"));
assert_eq!(command.get_program(), "cmd");
}
}
| 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-preview/src/lib.rs | crates/uv-preview/src/lib.rs | use std::{
fmt::{Display, Formatter},
str::FromStr,
};
use thiserror::Error;
use uv_warnings::warn_user_once;
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PreviewFeatures: u32 {
const PYTHON_INSTALL_DEFAULT = 1 << 0;
const PYTHON_UPGRADE = 1 << 1;
const JSON_OUTPUT = 1 << 2;
const PYLOCK = 1 << 3;
const ADD_BOUNDS = 1 << 4;
const PACKAGE_CONFLICTS = 1 << 5;
const EXTRA_BUILD_DEPENDENCIES = 1 << 6;
const DETECT_MODULE_CONFLICTS = 1 << 7;
const FORMAT = 1 << 8;
const NATIVE_AUTH = 1 << 9;
const S3_ENDPOINT = 1 << 10;
const CACHE_SIZE = 1 << 11;
const INIT_PROJECT_FLAG = 1 << 12;
const WORKSPACE_METADATA = 1 << 13;
const WORKSPACE_DIR = 1 << 14;
const WORKSPACE_LIST = 1 << 15;
const SBOM_EXPORT = 1 << 16;
const AUTH_HELPER = 1 << 17;
}
}
impl PreviewFeatures {
/// Returns the string representation of a single preview feature flag.
///
/// Panics if given a combination of flags.
fn flag_as_str(self) -> &'static str {
match self {
Self::PYTHON_INSTALL_DEFAULT => "python-install-default",
Self::PYTHON_UPGRADE => "python-upgrade",
Self::JSON_OUTPUT => "json-output",
Self::PYLOCK => "pylock",
Self::ADD_BOUNDS => "add-bounds",
Self::PACKAGE_CONFLICTS => "package-conflicts",
Self::EXTRA_BUILD_DEPENDENCIES => "extra-build-dependencies",
Self::DETECT_MODULE_CONFLICTS => "detect-module-conflicts",
Self::FORMAT => "format",
Self::NATIVE_AUTH => "native-auth",
Self::S3_ENDPOINT => "s3-endpoint",
Self::CACHE_SIZE => "cache-size",
Self::INIT_PROJECT_FLAG => "init-project-flag",
Self::WORKSPACE_METADATA => "workspace-metadata",
Self::WORKSPACE_DIR => "workspace-dir",
Self::WORKSPACE_LIST => "workspace-list",
Self::SBOM_EXPORT => "sbom-export",
Self::AUTH_HELPER => "auth-helper",
_ => panic!("`flag_as_str` can only be used for exactly one feature flag"),
}
}
}
impl Display for PreviewFeatures {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.is_empty() {
write!(f, "none")
} else {
let features: Vec<&str> = self.iter().map(Self::flag_as_str).collect();
write!(f, "{}", features.join(","))
}
}
}
#[derive(Debug, Error, Clone)]
pub enum PreviewFeaturesParseError {
#[error("Empty string in preview features: {0}")]
Empty(String),
}
impl FromStr for PreviewFeatures {
type Err = PreviewFeaturesParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut flags = Self::empty();
for part in s.split(',') {
let part = part.trim();
if part.is_empty() {
return Err(PreviewFeaturesParseError::Empty(
"Empty string in preview features".to_string(),
));
}
let flag = match part {
"python-install-default" => Self::PYTHON_INSTALL_DEFAULT,
"python-upgrade" => Self::PYTHON_UPGRADE,
"json-output" => Self::JSON_OUTPUT,
"pylock" => Self::PYLOCK,
"add-bounds" => Self::ADD_BOUNDS,
"package-conflicts" => Self::PACKAGE_CONFLICTS,
"extra-build-dependencies" => Self::EXTRA_BUILD_DEPENDENCIES,
"detect-module-conflicts" => Self::DETECT_MODULE_CONFLICTS,
"format" => Self::FORMAT,
"native-auth" => Self::NATIVE_AUTH,
"s3-endpoint" => Self::S3_ENDPOINT,
"cache-size" => Self::CACHE_SIZE,
"init-project-flag" => Self::INIT_PROJECT_FLAG,
"workspace-metadata" => Self::WORKSPACE_METADATA,
"workspace-dir" => Self::WORKSPACE_DIR,
"workspace-list" => Self::WORKSPACE_LIST,
"sbom-export" => Self::SBOM_EXPORT,
"auth-helper" => Self::AUTH_HELPER,
_ => {
warn_user_once!("Unknown preview feature: `{part}`");
continue;
}
};
flags |= flag;
}
Ok(flags)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Preview {
flags: PreviewFeatures,
}
impl Preview {
pub fn new(flags: PreviewFeatures) -> Self {
Self { flags }
}
pub fn all() -> Self {
Self::new(PreviewFeatures::all())
}
pub fn from_args(
preview: bool,
no_preview: bool,
preview_features: &[PreviewFeatures],
) -> Self {
if no_preview {
return Self::default();
}
if preview {
return Self::all();
}
let mut flags = PreviewFeatures::empty();
for features in preview_features {
flags |= *features;
}
Self { flags }
}
pub fn is_enabled(&self, flag: PreviewFeatures) -> bool {
self.flags.contains(flag)
}
}
impl Display for Preview {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.flags.is_empty() {
write!(f, "disabled")
} else if self.flags == PreviewFeatures::all() {
write!(f, "enabled")
} else {
write!(f, "{}", self.flags)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_preview_features_from_str() {
// Test single feature
let features = PreviewFeatures::from_str("python-install-default").unwrap();
assert_eq!(features, PreviewFeatures::PYTHON_INSTALL_DEFAULT);
// Test multiple features
let features = PreviewFeatures::from_str("python-upgrade,json-output").unwrap();
assert!(features.contains(PreviewFeatures::PYTHON_UPGRADE));
assert!(features.contains(PreviewFeatures::JSON_OUTPUT));
assert!(!features.contains(PreviewFeatures::PYLOCK));
// Test with whitespace
let features = PreviewFeatures::from_str("pylock , add-bounds").unwrap();
assert!(features.contains(PreviewFeatures::PYLOCK));
assert!(features.contains(PreviewFeatures::ADD_BOUNDS));
// Test empty string error
assert!(PreviewFeatures::from_str("").is_err());
assert!(PreviewFeatures::from_str("pylock,").is_err());
assert!(PreviewFeatures::from_str(",pylock").is_err());
// Test unknown feature (should be ignored with warning)
let features = PreviewFeatures::from_str("unknown-feature,pylock").unwrap();
assert!(features.contains(PreviewFeatures::PYLOCK));
assert_eq!(features.bits().count_ones(), 1);
}
#[test]
fn test_preview_features_display() {
// Test empty
let features = PreviewFeatures::empty();
assert_eq!(features.to_string(), "none");
// Test single feature
let features = PreviewFeatures::PYTHON_INSTALL_DEFAULT;
assert_eq!(features.to_string(), "python-install-default");
// Test multiple features
let features = PreviewFeatures::PYTHON_UPGRADE | PreviewFeatures::JSON_OUTPUT;
assert_eq!(features.to_string(), "python-upgrade,json-output");
}
#[test]
fn test_preview_display() {
// Test disabled
let preview = Preview::default();
assert_eq!(preview.to_string(), "disabled");
// Test enabled (all features)
let preview = Preview::all();
assert_eq!(preview.to_string(), "enabled");
// Test specific features
let preview = Preview::new(PreviewFeatures::PYTHON_UPGRADE | PreviewFeatures::PYLOCK);
assert_eq!(preview.to_string(), "python-upgrade,pylock");
}
#[test]
fn test_preview_from_args() {
// Test no_preview
let preview = Preview::from_args(true, true, &[]);
assert_eq!(preview.to_string(), "disabled");
// Test preview (all features)
let preview = Preview::from_args(true, false, &[]);
assert_eq!(preview.to_string(), "enabled");
// Test specific features
let features = vec![
PreviewFeatures::PYTHON_UPGRADE,
PreviewFeatures::JSON_OUTPUT,
];
let preview = Preview::from_args(false, false, &features);
assert!(preview.is_enabled(PreviewFeatures::PYTHON_UPGRADE));
assert!(preview.is_enabled(PreviewFeatures::JSON_OUTPUT));
assert!(!preview.is_enabled(PreviewFeatures::PYLOCK));
}
#[test]
fn test_as_str_single_flags() {
assert_eq!(
PreviewFeatures::PYTHON_INSTALL_DEFAULT.flag_as_str(),
"python-install-default"
);
assert_eq!(
PreviewFeatures::PYTHON_UPGRADE.flag_as_str(),
"python-upgrade"
);
assert_eq!(PreviewFeatures::JSON_OUTPUT.flag_as_str(), "json-output");
assert_eq!(PreviewFeatures::PYLOCK.flag_as_str(), "pylock");
assert_eq!(PreviewFeatures::ADD_BOUNDS.flag_as_str(), "add-bounds");
assert_eq!(
PreviewFeatures::PACKAGE_CONFLICTS.flag_as_str(),
"package-conflicts"
);
assert_eq!(
PreviewFeatures::EXTRA_BUILD_DEPENDENCIES.flag_as_str(),
"extra-build-dependencies"
);
assert_eq!(
PreviewFeatures::DETECT_MODULE_CONFLICTS.flag_as_str(),
"detect-module-conflicts"
);
assert_eq!(PreviewFeatures::FORMAT.flag_as_str(), "format");
assert_eq!(PreviewFeatures::S3_ENDPOINT.flag_as_str(), "s3-endpoint");
assert_eq!(PreviewFeatures::SBOM_EXPORT.flag_as_str(), "sbom-export");
}
#[test]
#[should_panic(expected = "`flag_as_str` can only be used for exactly one feature flag")]
fn test_as_str_multiple_flags_panics() {
let features = PreviewFeatures::PYTHON_UPGRADE | PreviewFeatures::JSON_OUTPUT;
let _ = features.flag_as_str();
}
}
| 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-installer/src/uninstall.rs | crates/uv-installer/src/uninstall.rs | use uv_distribution_types::{InstalledDist, InstalledDistKind, InstalledEggInfoFile};
/// Uninstall a package from the specified Python environment.
pub async fn uninstall(
dist: &InstalledDist,
) -> Result<uv_install_wheel::Uninstall, UninstallError> {
let uninstall = tokio::task::spawn_blocking({
let dist = dist.clone();
move || match dist.kind {
InstalledDistKind::Registry(_) | InstalledDistKind::Url(_) => {
Ok(uv_install_wheel::uninstall_wheel(dist.install_path())?)
}
InstalledDistKind::EggInfoDirectory(_) => {
Ok(uv_install_wheel::uninstall_egg(dist.install_path())?)
}
InstalledDistKind::LegacyEditable(dist) => {
Ok(uv_install_wheel::uninstall_legacy_editable(&dist.egg_link)?)
}
InstalledDistKind::EggInfoFile(dist) => Err(UninstallError::Distutils(dist)),
}
})
.await??;
Ok(uninstall)
}
#[derive(thiserror::Error, Debug)]
pub enum UninstallError {
#[error(
"Unable to uninstall `{0}`. distutils-installed distributions do not include the metadata required to uninstall safely."
)]
Distutils(InstalledEggInfoFile),
#[error(transparent)]
Uninstall(#[from] uv_install_wheel::Error),
#[error(transparent)]
Join(#[from] tokio::task::JoinError),
}
| 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-installer/src/installer.rs | crates/uv-installer/src/installer.rs | use std::convert;
use std::sync::{Arc, LazyLock};
use anyhow::{Context, Error, Result};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use tokio::sync::oneshot;
use tracing::instrument;
use uv_cache::Cache;
use uv_configuration::RAYON_INITIALIZE;
use uv_distribution_types::CachedDist;
use uv_install_wheel::{Layout, LinkMode};
use uv_preview::Preview;
use uv_python::PythonEnvironment;
pub struct Installer<'a> {
venv: &'a PythonEnvironment,
link_mode: LinkMode,
cache: Option<&'a Cache>,
reporter: Option<Arc<dyn Reporter>>,
/// The name of the [`Installer`].
name: Option<String>,
/// The metadata associated with the [`Installer`].
metadata: bool,
/// Preview settings for the installer.
preview: Preview,
}
impl<'a> Installer<'a> {
/// Initialize a new installer.
pub fn new(venv: &'a PythonEnvironment, preview: Preview) -> Self {
Self {
venv,
link_mode: LinkMode::default(),
cache: None,
reporter: None,
name: Some("uv".to_string()),
metadata: true,
preview,
}
}
/// Set the [`LinkMode`][`uv_install_wheel::LinkMode`] to use for this installer.
#[must_use]
pub fn with_link_mode(self, link_mode: LinkMode) -> Self {
Self { link_mode, ..self }
}
/// Set the [`Cache`] to use for this installer.
#[must_use]
pub fn with_cache(self, cache: &'a Cache) -> Self {
Self {
cache: Some(cache),
..self
}
}
/// Set the [`Reporter`] to use for this installer.
#[must_use]
pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
reporter: Some(reporter),
..self
}
}
/// Set the `installer_name` to something other than `"uv"`.
#[must_use]
pub fn with_installer_name(self, installer_name: Option<String>) -> Self {
Self {
name: installer_name,
..self
}
}
/// Set whether to install uv-specifier files in the dist-info directory.
#[must_use]
pub fn with_installer_metadata(self, installer_metadata: bool) -> Self {
Self {
metadata: installer_metadata,
..self
}
}
/// Install a set of wheels into a Python virtual environment.
#[instrument(skip_all, fields(num_wheels = %wheels.len()))]
pub async fn install(self, wheels: Vec<CachedDist>) -> Result<Vec<CachedDist>> {
let Self {
venv,
cache,
link_mode,
reporter,
name: installer_name,
metadata: installer_metadata,
preview,
} = self;
if cache.is_some_and(Cache::is_temporary) {
if link_mode.is_symlink() {
return Err(anyhow::anyhow!(
"Symlink-based installation is not supported with `--no-cache`. The created environment will be rendered unusable by the removal of the cache."
));
}
}
let (tx, rx) = oneshot::channel();
let layout = venv.interpreter().layout();
let relocatable = venv.relocatable();
// Initialize the threadpool with the user settings.
LazyLock::force(&RAYON_INITIALIZE);
rayon::spawn(move || {
let result = install(
wheels,
&layout,
installer_name.as_deref(),
link_mode,
reporter.as_ref(),
relocatable,
installer_metadata,
preview,
);
// This may fail if the main task was cancelled.
let _ = tx.send(result);
});
rx.await
.map_err(|_| anyhow::anyhow!("`install_blocking` task panicked"))
.and_then(convert::identity)
}
/// Install a set of wheels into a Python virtual environment synchronously.
#[instrument(skip_all, fields(num_wheels = %wheels.len()))]
pub fn install_blocking(self, wheels: Vec<CachedDist>) -> Result<Vec<CachedDist>> {
if self.cache.is_some_and(Cache::is_temporary) {
if self.link_mode.is_symlink() {
return Err(anyhow::anyhow!(
"Symlink-based installation is not supported with `--no-cache`. The created environment will be rendered unusable by the removal of the cache."
));
}
}
install(
wheels,
&self.venv.interpreter().layout(),
self.name.as_deref(),
self.link_mode,
self.reporter.as_ref(),
self.venv.relocatable(),
self.metadata,
self.preview,
)
}
}
/// Install a set of wheels into a Python virtual environment synchronously.
#[instrument(skip_all, fields(num_wheels = %wheels.len()))]
fn install(
wheels: Vec<CachedDist>,
layout: &Layout,
installer_name: Option<&str>,
link_mode: LinkMode,
reporter: Option<&Arc<dyn Reporter>>,
relocatable: bool,
installer_metadata: bool,
preview: Preview,
) -> Result<Vec<CachedDist>> {
// Initialize the threadpool with the user settings.
LazyLock::force(&RAYON_INITIALIZE);
let locks = uv_install_wheel::Locks::new(preview);
wheels.par_iter().try_for_each(|wheel| {
uv_install_wheel::install_wheel(
layout,
relocatable,
wheel.path(),
wheel.filename(),
wheel
.parsed_url()
.map(uv_pypi_types::DirectUrl::from)
.as_ref(),
if wheel.cache_info().is_empty() {
None
} else {
Some(wheel.cache_info())
},
wheel.build_info(),
installer_name,
installer_metadata,
link_mode,
&locks,
)
.with_context(|| format!("Failed to install: {} ({wheel})", wheel.filename()))?;
if let Some(reporter) = reporter.as_ref() {
reporter.on_install_progress(wheel);
}
Ok::<(), Error>(())
})?;
Ok(wheels)
}
pub trait Reporter: Send + Sync {
/// Callback to invoke when a dependency is installed.
fn on_install_progress(&self, wheel: &CachedDist);
/// Callback to invoke when the resolution is complete.
fn on_install_complete(&self);
}
| rust | Apache-2.0 | 2318e48e819080f37a002551035c2b1880a81a70 | 2026-01-04T15:31:58.679374Z | false |
astral-sh/uv | https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-installer/src/lib.rs | crates/uv-installer/src/lib.rs | pub use compile::{CompileError, compile_tree};
pub use installer::{Installer, Reporter as InstallReporter};
pub use plan::{Plan, Planner};
pub use preparer::{Error as PrepareError, Preparer, Reporter as PrepareReporter};
pub use site_packages::{
InstallationStrategy, SatisfiesResult, SitePackages, SitePackagesDiagnostic,
};
pub use uninstall::{UninstallError, uninstall};
mod compile;
mod preparer;
mod installer;
mod plan;
mod satisfies;
mod site_packages;
mod uninstall;
| 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-installer/src/compile.rs | crates/uv-installer/src/compile.rs | use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use std::{env, io, panic};
use async_channel::{Receiver, SendError};
use tempfile::tempdir_in;
use thiserror::Error;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
use tokio::sync::oneshot;
use tracing::{debug, instrument};
use walkdir::WalkDir;
use uv_configuration::Concurrency;
use uv_fs::Simplified;
use uv_static::EnvVars;
use uv_warnings::warn_user;
const COMPILEALL_SCRIPT: &str = include_str!("pip_compileall.py");
/// This is longer than any compilation should ever take.
const DEFAULT_COMPILE_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Debug, Error)]
pub enum CompileError {
#[error("Failed to list files in `site-packages`")]
Walkdir(#[from] walkdir::Error),
#[error("Failed to send task to worker")]
WorkerDisappeared(SendError<PathBuf>),
#[error("The task executor is broken, did some other task panic?")]
Join,
#[error("Failed to start Python interpreter to run compile script")]
PythonSubcommand(#[source] io::Error),
#[error("Failed to create temporary script file")]
TempFile(#[source] io::Error),
#[error(r#"Bytecode compilation failed, expected "{0}", received: "{1}""#)]
WrongPath(String, String),
#[error("Failed to write to Python {device}")]
ChildStdio {
device: &'static str,
#[source]
err: io::Error,
},
#[error("Python process stderr:\n{stderr}")]
ErrorWithStderr {
stderr: String,
#[source]
err: Box<Self>,
},
#[error("Bytecode timed out ({}s) compiling file: `{}`", elapsed.as_secs_f32(), source_file)]
CompileTimeout {
elapsed: Duration,
source_file: String,
},
#[error("Python startup timed out ({}s)", _0.as_secs_f32())]
StartupTimeout(Duration),
#[error("Got invalid value from environment for {var}: {message}.")]
EnvironmentError { var: &'static str, message: String },
}
/// Bytecode compile all file in `dir` using a pool of Python interpreters running a Python script
/// that calls `compileall.compile_file`.
///
/// All compilation errors are muted (like pip). There is a 60s timeout for each file to handle
/// a broken `python`.
///
/// We only compile all files, but we don't update the RECORD, relying on PEP 491:
/// > Uninstallers should be smart enough to remove .pyc even if it is not mentioned in RECORD.
///
/// We've confirmed that both uv and pip (as of 24.0.0) remove the `__pycache__` directory.
#[instrument(skip(python_executable))]
pub async fn compile_tree(
dir: &Path,
python_executable: &Path,
concurrency: &Concurrency,
cache: &Path,
) -> Result<usize, CompileError> {
debug_assert!(
dir.is_absolute(),
"compileall doesn't work with relative paths: `{}`",
dir.display()
);
let worker_count = concurrency.installs;
// A larger buffer is significantly faster than just 1 or the worker count.
let (sender, receiver) = async_channel::bounded::<PathBuf>(worker_count * 10);
// Running Python with an actual file will produce better error messages.
let tempdir = tempdir_in(cache).map_err(CompileError::TempFile)?;
let pip_compileall_py = tempdir.path().join("pip_compileall.py");
let timeout: Option<Duration> = match env::var(EnvVars::UV_COMPILE_BYTECODE_TIMEOUT) {
Ok(value) => match value.as_str() {
"0" => None,
_ => match value.parse::<u64>().map(Duration::from_secs) {
Ok(duration) => Some(duration),
Err(_) => {
return Err(CompileError::EnvironmentError {
var: EnvVars::UV_COMPILE_BYTECODE_TIMEOUT,
message: format!("Expected an integer number of seconds, got \"{value}\""),
});
}
},
},
Err(_) => Some(DEFAULT_COMPILE_TIMEOUT),
};
if let Some(duration) = timeout {
debug!(
"Using bytecode compilation timeout of {}s",
duration.as_secs()
);
} else {
debug!("Disabling bytecode compilation timeout");
}
debug!("Starting {} bytecode compilation workers", worker_count);
let mut worker_handles = Vec::new();
for _ in 0..worker_count {
let (tx, rx) = oneshot::channel();
let worker = worker(
dir.to_path_buf(),
python_executable.to_path_buf(),
pip_compileall_py.clone(),
receiver.clone(),
timeout,
);
// Spawn each worker on a dedicated thread.
std::thread::Builder::new()
.name("uv-compile".to_owned())
.spawn(move || {
// Report panics back to the main thread.
let result = panic::catch_unwind(AssertUnwindSafe(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Failed to build runtime")
.block_on(worker)
}));
// This may fail if the main thread returned early due to an error.
let _ = tx.send(result);
})
.expect("Failed to start compilation worker");
worker_handles.push(async { rx.await.unwrap() });
}
// Make sure the channel gets closed when all workers exit.
drop(receiver);
// Start the producer, sending all `.py` files to workers.
let mut source_files = 0;
let mut send_error = None;
let walker = WalkDir::new(dir)
.into_iter()
// Otherwise we stumble over temporary files from `compileall`.
.filter_entry(|dir| dir.file_name() != "__pycache__");
for entry in walker {
// Retrieve the entry and its metadata, with shared handling for IO errors
let (entry, metadata) =
match entry.and_then(|entry| entry.metadata().map(|metadata| (entry, metadata))) {
Ok((entry, metadata)) => (entry, metadata),
Err(err) => {
if err
.io_error()
.is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
{
// The directory was removed, just ignore it
continue;
}
return Err(err.into());
}
};
// https://github.com/pypa/pip/blob/3820b0e52c7fed2b2c43ba731b718f316e6816d1/src/pip/_internal/operations/install/wheel.py#L593-L604
if metadata.is_file() && entry.path().extension().is_some_and(|ext| ext == "py") {
source_files += 1;
if let Err(err) = sender.send(entry.path().to_owned()).await {
// The workers exited.
// If e.g. something with the Python interpreter is wrong, the workers have exited
// with an error. We try to report this informative error and only if that fails,
// report the send error.
send_error = Some(err);
break;
}
}
}
// All workers will receive an error after the last item. Note that there are still
// up to worker_count * 10 items in the queue.
drop(sender);
// Make sure all workers exit regularly, avoid hiding errors.
for result in futures::future::join_all(worker_handles).await {
match result {
// There spawning earlier errored due to a panic in a task.
Err(_) => return Err(CompileError::Join),
// The worker reports an error.
Ok(Err(compile_error)) => return Err(compile_error),
Ok(Ok(())) => {}
}
}
if let Some(send_error) = send_error {
// This is suspicious: Why did the channel stop working, but all workers exited
// successfully?
return Err(CompileError::WorkerDisappeared(send_error));
}
Ok(source_files)
}
async fn worker(
dir: PathBuf,
interpreter: PathBuf,
pip_compileall_py: PathBuf,
receiver: Receiver<PathBuf>,
timeout: Option<Duration>,
) -> Result<(), CompileError> {
fs_err::tokio::write(&pip_compileall_py, COMPILEALL_SCRIPT)
.await
.map_err(CompileError::TempFile)?;
// Sometimes, the first time we read from stdout, we get an empty string back (no newline). If
// we try to write to stdin, it will often be a broken pipe. In this case, we have to restart
// the child process
// https://github.com/astral-sh/uv/issues/2245
let wait_until_ready = async {
loop {
// If the interpreter started successful, return it, else retry.
if let Some(child) =
launch_bytecode_compiler(&dir, &interpreter, &pip_compileall_py).await?
{
break Ok::<_, CompileError>(child);
}
}
};
// Handle a broken `python` by using a timeout, one that's higher than any compilation
// should ever take.
let (mut bytecode_compiler, child_stdin, mut child_stdout, mut child_stderr) =
if let Some(duration) = timeout {
tokio::time::timeout(duration, wait_until_ready)
.await
.map_err(|_| CompileError::StartupTimeout(timeout.unwrap()))??
} else {
wait_until_ready.await?
};
let stderr_reader = tokio::task::spawn(async move {
let mut child_stderr_collected: Vec<u8> = Vec::new();
child_stderr
.read_to_end(&mut child_stderr_collected)
.await?;
Ok(child_stderr_collected)
});
let result = worker_main_loop(receiver, child_stdin, &mut child_stdout, timeout).await;
// Reap the process to avoid zombies.
let _ = bytecode_compiler.kill().await;
// If there was something printed to stderr (which shouldn't happen, we muted all errors), tell
// the user, otherwise only forward the result.
let child_stderr_collected = stderr_reader
.await
.map_err(|_| CompileError::Join)?
.map_err(|err| CompileError::ChildStdio {
device: "stderr",
err,
})?;
let result = if child_stderr_collected.is_empty() {
result
} else {
let stderr = String::from_utf8_lossy(&child_stderr_collected);
match result {
Ok(()) => {
debug!(
"Bytecode compilation `python` at {} stderr:\n{}\n---",
interpreter.user_display(),
stderr
);
Ok(())
}
Err(err) => Err(CompileError::ErrorWithStderr {
stderr: stderr.trim().to_string(),
err: Box::new(err),
}),
}
};
debug!("Bytecode compilation worker exiting: {:?}", result);
result
}
/// Returns the child and stdin/stdout/stderr on a successful launch or `None` for a broken interpreter state.
async fn launch_bytecode_compiler(
dir: &Path,
interpreter: &Path,
pip_compileall_py: &Path,
) -> Result<
Option<(
Child,
ChildStdin,
BufReader<ChildStdout>,
BufReader<ChildStderr>,
)>,
CompileError,
> {
// We input the paths through stdin and get the successful paths returned through stdout.
let mut bytecode_compiler = Command::new(interpreter)
.arg(pip_compileall_py)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.current_dir(dir)
// Otherwise stdout is buffered and we'll wait forever for a response
.env(EnvVars::PYTHONUNBUFFERED, "1")
.spawn()
.map_err(CompileError::PythonSubcommand)?;
// https://stackoverflow.com/questions/49218599/write-to-child-process-stdin-in-rust/49597789#comment120223107_49597789
// Unbuffered, we need to write immediately or the python process will get stuck waiting
let child_stdin = bytecode_compiler
.stdin
.take()
.expect("Child must have stdin");
let mut child_stdout = BufReader::new(
bytecode_compiler
.stdout
.take()
.expect("Child must have stdout"),
);
let child_stderr = BufReader::new(
bytecode_compiler
.stderr
.take()
.expect("Child must have stderr"),
);
// Check if the launch was successful.
let mut out_line = String::new();
child_stdout
.read_line(&mut out_line)
.await
.map_err(|err| CompileError::ChildStdio {
device: "stdout",
err,
})?;
if out_line.trim_end() == "Ready" {
// Success
Ok(Some((
bytecode_compiler,
child_stdin,
child_stdout,
child_stderr,
)))
} else if out_line.is_empty() {
// Failed to launch, try again
Ok(None)
} else {
// Not observed yet
Err(CompileError::WrongPath("Ready".to_string(), out_line))
}
}
/// We use stdin/stdout as a sort of bounded channel. We write one path to stdin, then wait until
/// we get the same path back from stdout. This way we ensure one worker is only working on one
/// piece of work at the same time.
async fn worker_main_loop(
receiver: Receiver<PathBuf>,
mut child_stdin: ChildStdin,
child_stdout: &mut BufReader<ChildStdout>,
timeout: Option<Duration>,
) -> Result<(), CompileError> {
let mut out_line = String::new();
while let Ok(source_file) = receiver.recv().await {
let source_file = source_file.display().to_string();
if source_file.contains(['\r', '\n']) {
warn_user!("Path contains newline, skipping: {source_file:?}");
continue;
}
// Luckily, LF alone works on windows too
let bytes = format!("{source_file}\n").into_bytes();
let python_handle = async {
child_stdin
.write_all(&bytes)
.await
.map_err(|err| CompileError::ChildStdio {
device: "stdin",
err,
})?;
out_line.clear();
child_stdout.read_line(&mut out_line).await.map_err(|err| {
CompileError::ChildStdio {
device: "stdout",
err,
}
})?;
Ok::<(), CompileError>(())
};
// Handle a broken `python` by using a timeout, one that's higher than any compilation
// should ever take.
if let Some(duration) = timeout {
tokio::time::timeout(duration, python_handle)
.await
.map_err(|_| CompileError::CompileTimeout {
elapsed: duration,
source_file: source_file.clone(),
})??;
} else {
python_handle.await?;
}
// This is a sanity check, if we don't get the path back something has gone wrong, e.g.
// we're not actually running a python interpreter.
let actual = out_line.trim_end_matches(['\n', '\r']);
if actual != source_file {
return Err(CompileError::WrongPath(source_file, actual.to_string()));
}
}
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-installer/src/satisfies.rs | crates/uv-installer/src/satisfies.rs | use std::borrow::Cow;
use std::fmt::Debug;
use same_file::is_same_file;
use tracing::{debug, trace};
use url::Url;
use uv_cache_info::CacheInfo;
use uv_cache_key::{CanonicalUrl, RepositoryUrl};
use uv_distribution_filename::ExpandedTags;
use uv_distribution_types::{
BuildInfo, BuildVariables, ConfigSettings, ExtraBuildRequirement, ExtraBuildRequires,
ExtraBuildVariables, InstalledDirectUrlDist, InstalledDist, InstalledDistKind,
PackageConfigSettings, RequirementSource,
};
use uv_git_types::{GitLfs, GitOid};
use uv_normalize::PackageName;
use uv_platform_tags::{IncompatibleTag, TagCompatibility, Tags};
use uv_pypi_types::{DirInfo, DirectUrl, VcsInfo, VcsKind};
use crate::InstallationStrategy;
#[derive(Debug, Copy, Clone)]
pub(crate) enum RequirementSatisfaction {
Mismatch,
Satisfied,
OutOfDate,
CacheInvalid,
}
impl RequirementSatisfaction {
/// Returns true if a requirement is satisfied by an installed distribution.
///
/// Returns an error if IO fails during a freshness check for a local path.
pub(crate) fn check(
name: &PackageName,
distribution: &InstalledDist,
source: &RequirementSource,
installation: InstallationStrategy,
tags: &Tags,
config_settings: &ConfigSettings,
config_settings_package: &PackageConfigSettings,
extra_build_requires: &ExtraBuildRequires,
extra_build_variables: &ExtraBuildVariables,
) -> Self {
trace!(
"Comparing installed with source: {:?} {:?}",
distribution, source
);
// If the distribution was built with other settings, it is out of date.
if distribution.build_info().is_some_and(|dist_build_info| {
let config_settings =
config_settings_for(name, config_settings, config_settings_package);
let extra_build_requires = extra_build_requires_for(name, extra_build_requires);
let extra_build_variables = extra_build_variables_for(name, extra_build_variables);
let build_info = BuildInfo::from_settings(
&config_settings,
extra_build_requires,
extra_build_variables,
);
dist_build_info != &build_info
}) {
debug!("Build info mismatch for {name}: {distribution}");
return Self::OutOfDate;
}
// Filter out already-installed packages.
match source {
// If the requirement comes from a registry, check by name.
RequirementSource::Registry { specifier, .. } => {
// If the installed distribution is _not_ from a registry, reject it if and only if
// we're in a stateless install.
//
// For example: the `uv pip` CLI is stateful, in that it "respects"
// already-installed packages in the virtual environment. So if you run `uv pip
// install ./path/to/idna`, and then `uv pip install anyio` (which depends on
// `idna`), we'll "accept" the already-installed `idna` even though it is implicitly
// being "required" as a registry package.
//
// The `uv sync` CLI is stateless, in that all requirements must be defined
// declaratively ahead-of-time. So if you `uv sync` to install `./path/to/idna` and
// later `uv sync` to install `anyio`, we'll know (during that second sync) if the
// already-installed `idna` should come from the registry or not.
if installation == InstallationStrategy::Strict {
if !matches!(distribution.kind, InstalledDistKind::Registry { .. }) {
debug!("Distribution type mismatch for {name}: {distribution:?}");
return Self::Mismatch;
}
}
if !specifier.contains(distribution.version()) {
return Self::Mismatch;
}
}
RequirementSource::Url {
// We use the location since `direct_url.json` also stores this URL, e.g.
// `pip install git+https://github.com/tqdm/tqdm@cc372d09dcd5a5eabdc6ed4cf365bdb0be004d44#subdirectory=.`
// records `"url": "https://github.com/tqdm/tqdm"` in `direct_url.json`.
location: requested_url,
subdirectory: requested_subdirectory,
ext: _,
url: _,
} => {
let InstalledDistKind::Url(InstalledDirectUrlDist {
direct_url,
editable,
cache_info,
..
}) = &distribution.kind
else {
return Self::Mismatch;
};
let DirectUrl::ArchiveUrl {
url: installed_url,
archive_info: _,
subdirectory: installed_subdirectory,
} = direct_url.as_ref()
else {
return Self::Mismatch;
};
if *editable {
return Self::Mismatch;
}
if requested_subdirectory != installed_subdirectory {
return Self::Mismatch;
}
if !CanonicalUrl::parse(installed_url)
.is_ok_and(|installed_url| installed_url == CanonicalUrl::new(requested_url))
{
return Self::Mismatch;
}
// If the requirement came from a local path, check freshness.
if requested_url.scheme() == "file" {
if let Ok(archive) = requested_url.to_file_path() {
let Some(cache_info) = cache_info.as_ref() else {
return Self::OutOfDate;
};
match CacheInfo::from_path(&archive) {
Ok(read_cache_info) => {
if *cache_info != read_cache_info {
return Self::OutOfDate;
}
}
Err(err) => {
debug!(
"Failed to read cached requirement for: {distribution} ({err})"
);
return Self::CacheInvalid;
}
}
}
}
}
RequirementSource::Git {
url: _,
git: requested_git,
subdirectory: requested_subdirectory,
} => {
let InstalledDistKind::Url(InstalledDirectUrlDist { direct_url, .. }) =
&distribution.kind
else {
return Self::Mismatch;
};
let DirectUrl::VcsUrl {
url: installed_url,
vcs_info:
VcsInfo {
vcs: VcsKind::Git,
requested_revision: _,
commit_id: installed_precise,
git_lfs: installed_git_lfs,
},
subdirectory: installed_subdirectory,
} = direct_url.as_ref()
else {
return Self::Mismatch;
};
if requested_subdirectory != installed_subdirectory {
debug!(
"Subdirectory mismatch: {:?} vs. {:?}",
installed_subdirectory, requested_subdirectory
);
return Self::Mismatch;
}
let requested_git_lfs = requested_git.lfs();
let installed_git_lfs = installed_git_lfs.map(GitLfs::from).unwrap_or_default();
if requested_git_lfs != installed_git_lfs {
debug!(
"Git LFS mismatch: {} (installed) vs. {} (requested)",
installed_git_lfs, requested_git_lfs,
);
return Self::Mismatch;
}
if !RepositoryUrl::parse(installed_url).is_ok_and(|installed_url| {
installed_url == RepositoryUrl::new(requested_git.repository())
}) {
debug!(
"Repository mismatch: {:?} vs. {:?}",
installed_url,
requested_git.repository()
);
return Self::Mismatch;
}
// TODO(charlie): It would be more consistent for us to compare the requested
// revisions here.
if installed_precise.as_deref()
!= requested_git.precise().as_ref().map(GitOid::as_str)
{
debug!(
"Precise mismatch: {:?} vs. {:?}",
installed_precise,
requested_git.precise()
);
return Self::OutOfDate;
}
}
RequirementSource::Path {
install_path: requested_path,
ext: _,
url: _,
} => {
let InstalledDistKind::Url(InstalledDirectUrlDist {
direct_url,
cache_info,
..
}) = &distribution.kind
else {
return Self::Mismatch;
};
let DirectUrl::ArchiveUrl {
url: installed_url,
archive_info: _,
subdirectory: None,
} = direct_url.as_ref()
else {
return Self::Mismatch;
};
let Some(installed_path) = Url::parse(installed_url)
.ok()
.and_then(|url| url.to_file_path().ok())
else {
return Self::Mismatch;
};
if !(**requested_path == installed_path
|| is_same_file(requested_path, &installed_path).unwrap_or(false))
{
trace!(
"Path mismatch: {:?} vs. {:?}",
requested_path, installed_path,
);
return Self::Mismatch;
}
let Some(cache_info) = cache_info.as_ref() else {
return Self::OutOfDate;
};
match CacheInfo::from_path(requested_path) {
Ok(read_cache_info) => {
if *cache_info != read_cache_info {
return Self::OutOfDate;
}
}
Err(err) => {
debug!("Failed to read cached requirement for: {distribution} ({err})");
return Self::CacheInvalid;
}
}
}
RequirementSource::Directory {
install_path: requested_path,
editable: requested_editable,
r#virtual: _,
url: _,
} => {
let InstalledDistKind::Url(InstalledDirectUrlDist {
direct_url,
cache_info,
..
}) = &distribution.kind
else {
return Self::Mismatch;
};
let DirectUrl::LocalDirectory {
url: installed_url,
dir_info:
DirInfo {
editable: installed_editable,
},
subdirectory: None,
} = direct_url.as_ref()
else {
return Self::Mismatch;
};
if requested_editable != installed_editable {
trace!(
"Editable mismatch: {:?} vs. {:?}",
*requested_editable,
installed_editable.unwrap_or_default()
);
return Self::Mismatch;
}
let Some(installed_path) = Url::parse(installed_url)
.ok()
.and_then(|url| url.to_file_path().ok())
else {
return Self::Mismatch;
};
if !(**requested_path == installed_path
|| is_same_file(requested_path, &installed_path).unwrap_or(false))
{
trace!(
"Path mismatch: {:?} vs. {:?}",
requested_path, installed_path,
);
return Self::Mismatch;
}
let Some(cache_info) = cache_info.as_ref() else {
return Self::OutOfDate;
};
match CacheInfo::from_path(requested_path) {
Ok(read_cache_info) => {
if *cache_info != read_cache_info {
return Self::OutOfDate;
}
}
Err(err) => {
debug!("Failed to read cached requirement for: {distribution} ({err})");
return Self::CacheInvalid;
}
}
}
}
// If the distribution isn't compatible with the current platform, it is a mismatch.
if let Ok(Some(wheel_tags)) = distribution.read_tags() {
if !wheel_tags.is_compatible(tags) {
if let Some(hint) = generate_dist_compatibility_hint(wheel_tags, tags) {
debug!("Platform tags mismatch for {distribution}: {hint}");
} else {
debug!("Platform tags mismatch for {distribution}");
}
return Self::Mismatch;
}
}
// Otherwise, assume the requirement is up-to-date.
Self::Satisfied
}
}
/// 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)
}
/// Generate a hint for explaining tag compatibility issues.
// TODO(zanieb): We should refactor this to share logic with `generate_wheel_compatibility_hint`
fn generate_dist_compatibility_hint(wheel_tags: &ExpandedTags, tags: &Tags) -> Option<String> {
let TagCompatibility::Incompatible(incompatible_tag) = wheel_tags.compatibility(tags) else {
return None;
};
match incompatible_tag {
IncompatibleTag::Python => {
let wheel_tags = wheel_tags.python_tags();
let current_tag = tags.python_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{pretty} (`{current}`)")
} else {
format!("`{current}`")
};
Some(format!(
"The distribution is compatible with {}, but you're using {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The distribution requires {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
IncompatibleTag::Abi => {
let wheel_tags = wheel_tags.abi_tags();
let current_tag = tags.abi_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{pretty} (`{current}`)")
} else {
format!("`{current}`")
};
Some(format!(
"The distribution is compatible with {}, but you're using {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The distribution requires {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
IncompatibleTag::Platform => {
let wheel_tags = wheel_tags.platform_tags();
let current_tag = tags.platform_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{pretty} (`{current}`)")
} else {
format!("`{current}`")
};
Some(format!(
"The distribution is compatible with {}, but you're on {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The distribution requires {}",
wheel_tags
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{pretty} (`{tag}`)")
} else {
format!("`{tag}`")
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
_ => 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-installer/src/plan.rs | crates/uv-installer/src/plan.rs | use std::sync::Arc;
use anyhow::{Result, bail};
use owo_colors::OwoColorize;
use tracing::{debug, warn};
use uv_cache::{Cache, CacheBucket, WheelCache};
use uv_cache_info::Timestamp;
use uv_configuration::{BuildOptions, Reinstall};
use uv_distribution::{
BuiltWheelIndex, HttpArchivePointer, LocalArchivePointer, RegistryWheelIndex,
};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{
BuiltDist, CachedDirectUrlDist, CachedDist, ConfigSettings, Dist, Error, ExtraBuildRequires,
ExtraBuildVariables, Hashed, IndexLocations, InstalledDist, Name, PackageConfigSettings,
RequirementSource, Resolution, ResolvedDist, SourceDist,
};
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_platform_tags::{IncompatibleTag, TagCompatibility, Tags};
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::PythonEnvironment;
use uv_types::HashStrategy;
use crate::satisfies::RequirementSatisfaction;
use crate::{InstallationStrategy, SitePackages};
/// A planner to generate an [`Plan`] based on a set of requirements.
#[derive(Debug)]
pub struct Planner<'a> {
resolution: &'a Resolution,
}
impl<'a> Planner<'a> {
/// Set the requirements use in the [`Plan`].
pub fn new(resolution: &'a Resolution) -> Self {
Self { resolution }
}
/// Partition a set of requirements into those that should be linked from the cache, those that
/// need to be downloaded, and those that should be removed.
///
/// The install plan will respect cache [`Freshness`]. Specifically, if refresh is enabled, the
/// plan will respect cache entries created after the current time (as per the [`Refresh`]
/// policy). Otherwise, entries will be ignored. The downstream distribution database may still
/// read those entries from the cache after revalidating them.
///
/// The install plan will also respect the required hashes, such that it will never return a
/// cached distribution that does not match the required hash. Like pip, though, it _will_
/// return an _installed_ distribution that does not match the required hash.
pub fn build(
self,
mut site_packages: SitePackages,
installation: InstallationStrategy,
reinstall: &Reinstall,
build_options: &BuildOptions,
hasher: &HashStrategy,
index_locations: &IndexLocations,
config_settings: &ConfigSettings,
config_settings_package: &PackageConfigSettings,
extra_build_requires: &ExtraBuildRequires,
extra_build_variables: &ExtraBuildVariables,
cache: &Cache,
venv: &PythonEnvironment,
tags: &Tags,
) -> Result<Plan> {
// Index all the already-downloaded wheels in the cache.
let mut registry_index = RegistryWheelIndex::new(
cache,
tags,
index_locations,
hasher,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
);
let built_index = BuiltWheelIndex::new(
cache,
tags,
hasher,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
);
let mut cached = vec![];
let mut remote = vec![];
let mut reinstalls = vec![];
let mut extraneous = vec![];
// TODO(charlie): There are a few assumptions here that are hard to spot:
//
// 1. Apparently, we never return direct URL distributions as [`ResolvedDist::Installed`].
// If you trace the resolver, we only ever return [`ResolvedDist::Installed`] if you go
// through the [`CandidateSelector`], and we only go through the [`CandidateSelector`]
// for registry distributions.
//
// 2. We expect any distribution returned as [`ResolvedDist::Installed`] to hit the
// "Requirement already installed" path (hence the `unreachable!`) a few lines below it.
// So, e.g., if a package is marked as `--reinstall`, we _expect_ that it's not passed in
// as [`ResolvedDist::Installed`] here.
for dist in self.resolution.distributions() {
// Check if the package should be reinstalled.
let reinstall = reinstall.contains_package(dist.name())
|| dist
.source_tree()
.is_some_and(|source_tree| reinstall.contains_path(source_tree));
// Check if installation of a binary version of the package should be allowed.
let no_binary = build_options.no_binary_package(dist.name());
let no_build = build_options.no_build_package(dist.name());
// Determine whether the distribution is already installed.
let installed_dists = site_packages.remove_packages(dist.name());
if reinstall {
reinstalls.extend(installed_dists);
} else {
match installed_dists.as_slice() {
[] => {}
[installed] => {
let source = RequirementSource::from(dist);
match RequirementSatisfaction::check(
dist.name(),
installed,
&source,
installation,
tags,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
) {
RequirementSatisfaction::Mismatch => {
debug!(
"Requirement installed, but mismatched:\n Installed: {installed:?}\n Requested: {source:?}"
);
}
RequirementSatisfaction::Satisfied => {
debug!("Requirement already installed: {installed}");
continue;
}
RequirementSatisfaction::OutOfDate => {
debug!("Requirement installed, but not fresh: {installed}");
// If we made it here, something went wrong in the resolver, because it returned an
// already-installed distribution that we "shouldn't" use. Typically, this means the
// distribution was considered out-of-date, but in a way that the resolver didn't
// detect, and is indicative of drift between the resolver's candidate selector and
// the install plan. For example, at present, the resolver doesn't check that an
// installed distribution was built with the expected build settings. Treat it as
// up-to-date for now; it's just means we may not rebuild a package when we otherwise
// should. This is a known issue, but should only affect the `uv pip` CLI, as the
// project APIs never return installed distributions during resolution (i.e., the
// resolver is stateless).
// TODO(charlie): Incorporate these checks into the resolver.
if matches!(dist, ResolvedDist::Installed { .. }) {
warn!(
"Installed distribution was considered out-of-date, but returned by the resolver: {dist}"
);
continue;
}
}
RequirementSatisfaction::CacheInvalid => {
// Already logged
}
}
reinstalls.push(installed.clone());
}
// We reinstall installed distributions with multiple versions because
// we do not want to keep multiple incompatible versions but removing
// one version is likely to break another.
_ => reinstalls.extend(installed_dists),
}
}
let ResolvedDist::Installable { dist, .. } = dist else {
unreachable!("Installed distribution could not be found in site-packages: {dist}");
};
if cache.must_revalidate_package(dist.name())
|| dist
.source_tree()
.is_some_and(|source_tree| cache.must_revalidate_path(source_tree))
{
debug!("Must revalidate requirement: {}", dist.name());
remote.push(dist.clone());
continue;
}
// Identify any cached distributions that satisfy the requirement.
match dist.as_ref() {
Dist::Built(BuiltDist::Registry(wheel)) => {
if let Some(distribution) = registry_index.get(wheel.name()).find_map(|entry| {
if *entry.index.url() != wheel.best_wheel().index {
return None;
}
if entry.dist.filename != wheel.best_wheel().filename {
return None;
}
if entry.built && no_build {
return None;
}
if !entry.built && no_binary {
return None;
}
Some(&entry.dist)
}) {
debug!("Registry requirement already cached: {distribution}");
cached.push(CachedDist::Registry(distribution.clone()));
continue;
}
}
Dist::Built(BuiltDist::DirectUrl(wheel)) => {
if !wheel.filename.is_compatible(tags) {
let hint = generate_wheel_compatibility_hint(&wheel.filename, tags);
if let Some(hint) = hint {
bail!(
"A URL dependency is incompatible with the current platform: {}\n\n{}{} {}",
wheel.url,
"hint".bold().cyan(),
":".bold(),
hint
);
}
bail!(
"A URL dependency is incompatible with the current platform: {}",
wheel.url
);
}
if no_binary {
bail!(
"A URL dependency points to a wheel which conflicts with `--no-binary`: {}",
wheel.url
);
}
// Find the exact wheel from the cache, since we know the filename in
// advance.
let cache_entry = cache
.shard(
CacheBucket::Wheels,
WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
)
.entry(format!("{}.http", wheel.filename.cache_key()));
// Read the HTTP pointer.
match HttpArchivePointer::read_from(&cache_entry) {
Ok(Some(pointer)) => {
let cache_info = pointer.to_cache_info();
let build_info = pointer.to_build_info();
let archive = pointer.into_archive();
if archive.satisfies(hasher.get(dist.as_ref())) {
let cached_dist = CachedDirectUrlDist {
filename: wheel.filename.clone(),
url: VerbatimParsedUrl {
parsed_url: wheel.parsed_url(),
verbatim: wheel.url.clone(),
},
hashes: archive.hashes,
cache_info,
build_info,
path: cache.archive(&archive.id).into_boxed_path(),
};
debug!("URL wheel requirement already cached: {cached_dist}");
cached.push(CachedDist::Url(cached_dist));
continue;
}
debug!(
"Cached URL wheel requirement does not match expected hash policy for: {wheel}"
);
}
Ok(None) => {}
Err(err) => {
debug!(
"Failed to deserialize cached URL wheel requirement for: {wheel} ({err})"
);
}
}
}
Dist::Built(BuiltDist::Path(wheel)) => {
// Validate that the path exists.
if !wheel.install_path.exists() {
return Err(Error::NotFound(wheel.url.to_url()).into());
}
if !wheel.filename.is_compatible(tags) {
let hint = generate_wheel_compatibility_hint(&wheel.filename, tags);
if let Some(hint) = hint {
bail!(
"A path dependency is incompatible with the current platform: {}\n\n{}{} {}",
wheel.install_path.user_display(),
"hint".bold().cyan(),
":".bold(),
hint
);
}
bail!(
"A path dependency is incompatible with the current platform: {}",
wheel.install_path.user_display()
);
}
if no_binary {
bail!(
"A path dependency points to a wheel which conflicts with `--no-binary`: {}",
wheel.url
);
}
// Find the exact wheel from the cache, since we know the filename in
// advance.
let cache_entry = cache
.shard(
CacheBucket::Wheels,
WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
)
.entry(format!("{}.rev", wheel.filename.cache_key()));
match LocalArchivePointer::read_from(&cache_entry) {
Ok(Some(pointer)) => match Timestamp::from_path(&wheel.install_path) {
Ok(timestamp) => {
if pointer.is_up_to_date(timestamp) {
let cache_info = pointer.to_cache_info();
let build_info = pointer.to_build_info();
let archive = pointer.into_archive();
if archive.satisfies(hasher.get(dist.as_ref())) {
let cached_dist = CachedDirectUrlDist {
filename: wheel.filename.clone(),
url: VerbatimParsedUrl {
parsed_url: wheel.parsed_url(),
verbatim: wheel.url.clone(),
},
hashes: archive.hashes,
cache_info,
build_info,
path: cache.archive(&archive.id).into_boxed_path(),
};
debug!(
"Path wheel requirement already cached: {cached_dist}"
);
cached.push(CachedDist::Url(cached_dist));
continue;
}
debug!(
"Cached path wheel requirement does not match expected hash policy for: {wheel}"
);
}
}
Err(err) => {
debug!("Failed to get timestamp for wheel {wheel} ({err})");
}
},
Ok(None) => {}
Err(err) => {
debug!(
"Failed to deserialize cached path wheel requirement for: {wheel} ({err})"
);
}
}
}
Dist::Source(SourceDist::Registry(sdist)) => {
if let Some(distribution) = registry_index.get(sdist.name()).find_map(|entry| {
if *entry.index.url() != sdist.index {
return None;
}
if entry.dist.filename.name != sdist.name {
return None;
}
if entry.dist.filename.version != sdist.version {
return None;
}
if entry.built && no_build {
return None;
}
if !entry.built && no_binary {
return None;
}
Some(&entry.dist)
}) {
debug!("Registry requirement already cached: {distribution}");
cached.push(CachedDist::Registry(distribution.clone()));
continue;
}
}
Dist::Source(SourceDist::DirectUrl(sdist)) => {
// Find the most-compatible wheel from the cache, since we don't know
// the filename in advance.
match built_index.url(sdist) {
Ok(Some(wheel)) => {
if wheel.filename.name == sdist.name {
let cached_dist = wheel.into_url_dist(sdist);
debug!("URL source requirement already cached: {cached_dist}");
cached.push(CachedDist::Url(cached_dist));
continue;
}
warn!(
"Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
sdist, wheel.filename
);
}
Ok(None) => {}
Err(err) => {
debug!(
"Failed to deserialize cached wheel filename for: {sdist} ({err})"
);
}
}
}
Dist::Source(SourceDist::Git(sdist)) => {
// Find the most-compatible wheel from the cache, since we don't know
// the filename in advance.
if let Some(wheel) = built_index.git(sdist) {
if wheel.filename.name == sdist.name {
let cached_dist = wheel.into_git_dist(sdist);
debug!("Git source requirement already cached: {cached_dist}");
cached.push(CachedDist::Url(cached_dist));
continue;
}
warn!(
"Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
sdist, wheel.filename
);
}
}
Dist::Source(SourceDist::Path(sdist)) => {
// Validate that the path exists.
if !sdist.install_path.exists() {
return Err(Error::NotFound(sdist.url.to_url()).into());
}
// Find the most-compatible wheel from the cache, since we don't know
// the filename in advance.
match built_index.path(sdist) {
Ok(Some(wheel)) => {
if wheel.filename.name == sdist.name {
let cached_dist = wheel.into_path_dist(sdist);
debug!("Path source requirement already cached: {cached_dist}");
cached.push(CachedDist::Url(cached_dist));
continue;
}
warn!(
"Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
sdist, wheel.filename
);
}
Ok(None) => {}
Err(err) => {
debug!(
"Failed to deserialize cached wheel filename for: {sdist} ({err})"
);
}
}
}
Dist::Source(SourceDist::Directory(sdist)) => {
// Validate that the path exists.
if !sdist.install_path.exists() {
return Err(Error::NotFound(sdist.url.to_url()).into());
}
// Find the most-compatible wheel from the cache, since we don't know
// the filename in advance.
match built_index.directory(sdist) {
Ok(Some(wheel)) => {
if wheel.filename.name == sdist.name {
let cached_dist = wheel.into_directory_dist(sdist);
debug!(
"Directory source requirement already cached: {cached_dist}"
);
cached.push(CachedDist::Url(cached_dist));
continue;
}
warn!(
"Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
sdist, wheel.filename
);
}
Ok(None) => {}
Err(err) => {
debug!(
"Failed to deserialize cached wheel filename for: {sdist} ({err})"
);
}
}
}
}
debug!("Identified uncached distribution: {dist}");
remote.push(dist.clone());
}
// Remove any unnecessary packages.
if site_packages.any() {
// Retain seed packages unless: (1) the virtual environment was created by uv and
// (2) the `--seed` argument was not passed to `uv venv`.
let seed_packages = !venv.cfg().is_ok_and(|cfg| cfg.is_uv() && !cfg.is_seed());
for dist_info in site_packages {
if seed_packages && is_seed_package(&dist_info, venv) {
debug!("Preserving seed package: {dist_info}");
continue;
}
debug!("Unnecessary package: {dist_info}");
extraneous.push(dist_info);
}
}
Ok(Plan {
cached,
remote,
reinstalls,
extraneous,
})
}
}
/// Returns `true` if the given distribution is a seed package.
fn is_seed_package(dist_info: &InstalledDist, venv: &PythonEnvironment) -> bool {
if venv.interpreter().python_tuple() >= (3, 12) {
matches!(dist_info.name().as_ref(), "uv" | "pip")
} else {
// Include `setuptools` and `wheel` on Python <3.12.
matches!(
dist_info.name().as_ref(),
"pip" | "setuptools" | "wheel" | "uv"
)
}
}
/// Generate a hint for explaining wheel compatibility issues.
fn generate_wheel_compatibility_hint(filename: &WheelFilename, tags: &Tags) -> Option<String> {
let TagCompatibility::Incompatible(incompatible_tag) = filename.compatibility(tags) else {
return None;
};
match incompatible_tag {
IncompatibleTag::Python => {
let wheel_tags = filename.python_tags();
let current_tag = tags.python_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{} (`{}`)", pretty.cyan(), current.cyan())
} else {
format!("`{}`", current.cyan())
};
Some(format!(
"The wheel is compatible with {}, but you're using {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The wheel requires {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
IncompatibleTag::Abi => {
let wheel_tags = filename.abi_tags();
let current_tag = tags.abi_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{} (`{}`)", pretty.cyan(), current.cyan())
} else {
format!("`{}`", current.cyan())
};
Some(format!(
"The wheel is compatible with {}, but you're using {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The wheel requires {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
IncompatibleTag::Platform => {
let wheel_tags = filename.platform_tags();
let current_tag = tags.platform_tag();
if let Some(current) = current_tag {
let message = if let Some(pretty) = current.pretty() {
format!("{} (`{}`)", pretty.cyan(), current.cyan())
} else {
format!("`{}`", current.cyan())
};
Some(format!(
"The wheel is compatible with {}, but you're on {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", "),
message
))
} else {
Some(format!(
"The wheel requires {}",
wheel_tags
.iter()
.map(|tag| if let Some(pretty) = tag.pretty() {
format!("{} (`{}`)", pretty.cyan(), tag.cyan())
} else {
format!("`{}`", tag.cyan())
})
.collect::<Vec<_>>()
.join(", ")
))
}
}
_ => None,
}
}
#[derive(Debug, Default)]
pub struct Plan {
/// The distributions that are not already installed in the current environment, but are
/// available in the local cache.
pub cached: Vec<CachedDist>,
/// The distributions that are not already installed in the current environment, and are
/// not available in the local cache.
pub remote: Vec<Arc<Dist>>,
/// Any distributions that are already installed in the current environment, but will be
/// re-installed (including upgraded) to satisfy the requirements.
pub reinstalls: Vec<InstalledDist>,
/// Any distributions that are already installed in the current environment, and are
/// _not_ necessary to satisfy the requirements.
pub extraneous: Vec<InstalledDist>,
}
impl Plan {
/// Returns `true` if the plan is empty.
pub fn is_empty(&self) -> bool {
self.cached.is_empty()
&& self.remote.is_empty()
&& self.reinstalls.is_empty()
&& self.extraneous.is_empty()
}
/// Partition the remote distributions based on a predicate function.
///
/// Returns a tuple of plans, where the first plan contains the remote distributions that match
/// the predicate, and the second plan contains those that do not.
///
/// Any extraneous and cached distributions will be returned in the first plan, while the second
/// plan will contain any `false` matches from the remote distributions, along with any
/// reinstalls for those distributions.
pub fn partition<F>(self, mut f: F) -> (Self, Self)
where
F: FnMut(&PackageName) -> bool,
{
let Self {
cached,
remote,
reinstalls,
extraneous,
} = self;
// Partition the remote distributions based on the predicate function.
let (left_remote, right_remote) = remote
.into_iter()
.partition::<Vec<_>, _>(|dist| f(dist.name()));
// If any remote distributions are not matched, but are already installed, ensure that
| 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-installer/src/preparer.rs | crates/uv-installer/src/preparer.rs | use std::cmp::Reverse;
use std::sync::Arc;
use futures::{FutureExt, Stream, TryFutureExt, TryStreamExt, stream::FuturesUnordered};
use tracing::{debug, instrument};
use uv_cache::Cache;
use uv_configuration::BuildOptions;
use uv_distribution::{DistributionDatabase, LocalWheel};
use uv_distribution_types::{
BuildableSource, CachedDist, DerivationChain, Dist, DistErrorKind, Hashed, Identifier, Name,
RemoteSource, Resolution,
};
use uv_normalize::PackageName;
use uv_platform_tags::Tags;
use uv_redacted::DisplaySafeUrl;
use uv_types::{BuildContext, HashStrategy, InFlight};
/// Prepare distributions for installation.
///
/// Downloads, builds, and unzips a set of distributions.
pub struct Preparer<'a, Context: BuildContext> {
tags: &'a Tags,
cache: &'a Cache,
hashes: &'a HashStrategy,
build_options: &'a BuildOptions,
database: DistributionDatabase<'a, Context>,
reporter: Option<Arc<dyn Reporter>>,
}
impl<'a, Context: BuildContext> Preparer<'a, Context> {
pub fn new(
cache: &'a Cache,
tags: &'a Tags,
hashes: &'a HashStrategy,
build_options: &'a BuildOptions,
database: DistributionDatabase<'a, Context>,
) -> Self {
Self {
tags,
cache,
hashes,
build_options,
database,
reporter: None,
}
}
/// Set the [`Reporter`] to use for operations.
#[must_use]
pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
tags: self.tags,
cache: self.cache,
hashes: self.hashes,
build_options: self.build_options,
database: self
.database
.with_reporter(reporter.clone().into_distribution_reporter()),
reporter: Some(reporter),
}
}
/// Fetch, build, and unzip the distributions in parallel.
pub fn prepare_stream<'stream>(
&'stream self,
distributions: Vec<Arc<Dist>>,
in_flight: &'stream InFlight,
resolution: &'stream Resolution,
) -> impl Stream<Item = Result<CachedDist, Error>> + 'stream {
distributions
.into_iter()
.map(async |dist| {
let wheel = self
.get_wheel((*dist).clone(), in_flight, resolution)
.boxed_local()
.await?;
if let Some(reporter) = self.reporter.as_ref() {
reporter.on_progress(&wheel);
}
Ok::<CachedDist, Error>(wheel)
})
.collect::<FuturesUnordered<_>>()
}
/// Download, build, and unzip a set of distributions.
#[instrument(skip_all, fields(total = distributions.len()))]
pub async fn prepare(
&self,
mut distributions: Vec<Arc<Dist>>,
in_flight: &InFlight,
resolution: &Resolution,
) -> Result<Vec<CachedDist>, Error> {
// Sort the distributions by size.
distributions
.sort_unstable_by_key(|distribution| Reverse(distribution.size().unwrap_or(u64::MAX)));
let wheels = self
.prepare_stream(distributions, in_flight, resolution)
.try_collect()
.await?;
if let Some(reporter) = self.reporter.as_ref() {
reporter.on_complete();
}
Ok(wheels)
}
/// Download, build, and unzip a single wheel.
#[instrument(skip_all, fields(name = % dist, size = ? dist.size(), url = dist.file().map(| file | file.url.to_string()).unwrap_or_default()))]
pub async fn get_wheel(
&self,
dist: Dist,
in_flight: &InFlight,
resolution: &Resolution,
) -> Result<CachedDist, Error> {
// Validate that the distribution is compatible with the build options.
match dist {
Dist::Built(ref dist) => {
if self.build_options.no_binary_package(dist.name()) {
return Err(Error::NoBinary(dist.name().clone()));
}
}
Dist::Source(ref dist) => {
if self.build_options.no_build_package(dist.name()) {
if dist.is_editable() {
debug!("Allowing build for editable source distribution: {dist}");
} else {
return Err(Error::NoBuild(dist.name().clone()));
}
}
}
}
let id = dist.distribution_id();
if in_flight.downloads.register(id.clone()) {
let policy = self.hashes.get(&dist);
let result = self
.database
.get_or_build_wheel(&dist, self.tags, policy)
.boxed_local()
.map_err(|err| Error::from_dist(dist.clone(), err, resolution))
.await
.and_then(|wheel: LocalWheel| {
if wheel.satisfies(policy) {
Ok(wheel)
} else {
let err = uv_distribution::Error::hash_mismatch(
dist.to_string(),
policy.digests(),
wheel.hashes(),
);
Err(Error::from_dist(dist, err, resolution))
}
})
.map(CachedDist::from);
match result {
Ok(cached) => {
in_flight.downloads.done(id, Ok(cached.clone()));
Ok(cached)
}
Err(err) => {
in_flight.downloads.done(id, Err(err.to_string()));
Err(err)
}
}
} else {
let result = in_flight
.downloads
.wait(&id)
.await
.expect("missing value for registered task");
match result.as_ref() {
Ok(cached) => {
// Validate that the wheel is compatible with the distribution.
//
// `get_or_build_wheel` is guaranteed to return a wheel that matches the
// distribution. But there could be multiple requested distributions that share
// a cache entry in `in_flight`, so we need to double-check here.
//
// For example, if two requirements are based on the same local path, but use
// different names, then they'll share an `in_flight` entry, but one of the two
// should be rejected (since at least one of the names will not match the
// package name).
if *dist.name() != cached.filename().name {
let err = uv_distribution::Error::WheelMetadataNameMismatch {
given: dist.name().clone(),
metadata: cached.filename().name.clone(),
};
return Err(Error::from_dist(dist, err, resolution));
}
if let Some(version) = dist.version() {
if *version != cached.filename().version
&& *version != cached.filename().version.clone().without_local()
{
let err = uv_distribution::Error::WheelMetadataVersionMismatch {
given: version.clone(),
metadata: cached.filename().version.clone(),
};
return Err(Error::from_dist(dist, err, resolution));
}
}
Ok(cached.clone())
}
Err(err) => Err(Error::Thread(err.to_owned())),
}
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Building source distributions is disabled, but attempted to build `{0}`")]
NoBuild(PackageName),
#[error("Using pre-built wheels is disabled, but attempted to use `{0}`")]
NoBinary(PackageName),
#[error("{0} `{1}`")]
Dist(
DistErrorKind,
Box<Dist>,
DerivationChain,
#[source] uv_distribution::Error,
),
#[error("Cyclic build dependency detected for `{0}`")]
CyclicBuildDependency(PackageName),
#[error("Unzip failed in another thread: {0}")]
Thread(String),
}
impl Error {
/// Create an [`Error`] from a distribution error.
fn from_dist(dist: Dist, err: uv_distribution::Error, resolution: &Resolution) -> Self {
let chain =
DerivationChain::from_resolution(resolution, (&dist).into()).unwrap_or_default();
Self::Dist(
DistErrorKind::from_dist(&dist, &err),
Box::new(dist),
chain,
err,
)
}
}
pub trait Reporter: Send + Sync {
/// Callback to invoke when a wheel is unzipped. This implies that the wheel was downloaded and,
/// if necessary, built.
fn on_progress(&self, dist: &CachedDist);
/// Callback to invoke when the operation is complete.
fn on_complete(&self);
/// 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, index: usize, bytes: u64);
/// Callback to invoke when a download is complete.
fn on_download_complete(&self, name: &PackageName, index: usize);
/// 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, index: usize);
}
impl dyn Reporter {
/// Converts this reporter to a [`uv_distribution::Reporter`].
pub(crate) fn into_distribution_reporter(
self: Arc<dyn Reporter>,
) -> Arc<dyn uv_distribution::Reporter> {
Arc::new(Facade {
reporter: self.clone(),
})
}
}
/// A facade for converting from [`Reporter`] to [`uv_distribution::Reporter`].
struct Facade {
reporter: Arc<dyn Reporter>,
}
impl uv_distribution::Reporter for Facade {
fn on_build_start(&self, source: &BuildableSource) -> usize {
self.reporter.on_build_start(source)
}
fn on_build_complete(&self, source: &BuildableSource, id: usize) {
self.reporter.on_build_complete(source, id);
}
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, index: usize) {
self.reporter.on_checkout_complete(url, rev, index);
}
fn on_download_start(&self, name: &PackageName, size: Option<u64>) -> usize {
self.reporter.on_download_start(name, size)
}
fn on_download_progress(&self, index: usize, inc: u64) {
self.reporter.on_download_progress(index, inc);
}
fn on_download_complete(&self, name: &PackageName, index: usize) {
self.reporter.on_download_complete(name, 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-installer/src/site_packages.rs | crates/uv-installer/src/site_packages.rs | use std::borrow::Cow;
use std::collections::BTreeSet;
use std::iter::Flatten;
use std::path::PathBuf;
use anyhow::{Context, Result};
use fs_err as fs;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use uv_distribution_types::{
ConfigSettings, Diagnostic, ExtraBuildRequires, ExtraBuildVariables, InstalledDist,
InstalledDistKind, Name, NameRequirementSpecification, PackageConfigSettings, Requirement,
UnresolvedRequirement, UnresolvedRequirementSpecification,
};
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::VersionOrUrl;
use uv_platform_tags::Tags;
use uv_pypi_types::{ResolverMarkerEnvironment, VerbatimParsedUrl};
use uv_python::{Interpreter, PythonEnvironment};
use uv_redacted::DisplaySafeUrl;
use uv_types::InstalledPackagesProvider;
use uv_warnings::warn_user;
use crate::satisfies::RequirementSatisfaction;
/// An index over the packages installed in an environment.
///
/// Packages are indexed by both name and (for editable installs) URL.
#[derive(Debug, Clone)]
pub struct SitePackages {
interpreter: Interpreter,
/// The vector of all installed distributions. The `by_name` and `by_url` indices index into
/// this vector. The vector may contain `None` values, which represent distributions that were
/// removed from the virtual environment.
distributions: Vec<Option<InstalledDist>>,
/// The installed distributions, keyed by name. Although the Python runtime does not support it,
/// it is possible to have multiple distributions with the same name to be present in the
/// virtual environment, which we handle gracefully.
by_name: FxHashMap<PackageName, Vec<usize>>,
/// The installed editable distributions, keyed by URL.
by_url: FxHashMap<DisplaySafeUrl, Vec<usize>>,
}
impl SitePackages {
/// Build an index of installed packages from the given Python environment.
pub fn from_environment(environment: &PythonEnvironment) -> Result<Self> {
Self::from_interpreter(environment.interpreter())
}
/// Build an index of installed packages from the given Python executable.
pub fn from_interpreter(interpreter: &Interpreter) -> Result<Self> {
let mut distributions: Vec<Option<InstalledDist>> = Vec::new();
let mut by_name = FxHashMap::default();
let mut by_url = FxHashMap::default();
for site_packages in interpreter.site_packages() {
// Read the site-packages directory.
let site_packages = match fs::read_dir(site_packages.as_ref()) {
Ok(read_dir) => {
// Collect sorted directory paths; `read_dir` is not stable across platforms
let dist_likes: BTreeSet<_> = read_dir
.filter_map(|read_dir| match read_dir {
Ok(entry) => match entry.file_type() {
Ok(file_type) => (file_type.is_dir()
|| entry
.path()
.extension()
.is_some_and(|ext| ext == "egg-link" || ext == "egg-info"))
.then_some(Ok(entry.path())),
Err(err) => Some(Err(err)),
},
Err(err) => Some(Err(err)),
})
.collect::<Result<_, std::io::Error>>()
.with_context(|| {
format!(
"Failed to read site-packages directory contents: {}",
site_packages.user_display()
)
})?;
dist_likes
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(Self {
interpreter: interpreter.clone(),
distributions,
by_name,
by_url,
});
}
Err(err) => return Err(err).context("Failed to read site-packages directory"),
};
// Index all installed packages by name.
for path in site_packages {
let dist_info = match InstalledDist::try_from_path(&path) {
Ok(Some(dist_info)) => dist_info,
Ok(None) => continue,
Err(_)
if path.file_name().is_some_and(|name| {
name.to_str().is_some_and(|name| name.starts_with('~'))
}) =>
{
warn_user!(
"Ignoring dangling temporary directory: `{}`",
path.simplified_display().cyan()
);
continue;
}
Err(err) => {
return Err(err).context(format!(
"Failed to read metadata from: `{}`",
path.simplified_display()
));
}
};
let idx = distributions.len();
// Index the distribution by name.
by_name
.entry(dist_info.name().clone())
.or_default()
.push(idx);
// Index the distribution by URL.
if let InstalledDistKind::Url(dist) = &dist_info.kind {
by_url.entry(dist.url.clone()).or_default().push(idx);
}
// Add the distribution to the database.
distributions.push(Some(dist_info));
}
}
Ok(Self {
interpreter: interpreter.clone(),
distributions,
by_name,
by_url,
})
}
/// Returns the [`Interpreter`] used to install the packages.
pub fn interpreter(&self) -> &Interpreter {
&self.interpreter
}
/// Returns an iterator over the installed distributions.
pub fn iter(&self) -> impl Iterator<Item = &InstalledDist> {
self.distributions.iter().flatten()
}
/// Returns the installed distributions for a given package.
pub fn get_packages(&self, name: &PackageName) -> Vec<&InstalledDist> {
let Some(indexes) = self.by_name.get(name) else {
return Vec::new();
};
indexes
.iter()
.flat_map(|&index| &self.distributions[index])
.collect()
}
/// Remove the given packages from the index, returning all installed versions, if any.
pub fn remove_packages(&mut self, name: &PackageName) -> Vec<InstalledDist> {
let Some(indexes) = self.by_name.get(name) else {
return Vec::new();
};
indexes
.iter()
.filter_map(|index| std::mem::take(&mut self.distributions[*index]))
.collect()
}
/// Returns the distributions installed from the given URL, if any.
pub fn get_urls(&self, url: &DisplaySafeUrl) -> Vec<&InstalledDist> {
let Some(indexes) = self.by_url.get(url) else {
return Vec::new();
};
indexes
.iter()
.flat_map(|&index| &self.distributions[index])
.collect()
}
/// Returns `true` if there are any installed packages.
pub fn any(&self) -> bool {
self.distributions.iter().any(Option::is_some)
}
/// Validate the installed packages in the virtual environment.
pub fn diagnostics(
&self,
markers: &ResolverMarkerEnvironment,
tags: &Tags,
) -> Result<Vec<SitePackagesDiagnostic>> {
let mut diagnostics = Vec::new();
for (package, indexes) in &self.by_name {
let mut distributions = indexes.iter().flat_map(|index| &self.distributions[*index]);
// Find the installed distribution for the given package.
let Some(distribution) = distributions.next() else {
continue;
};
if let Some(conflict) = distributions.next() {
// There are multiple installed distributions for the same package.
diagnostics.push(SitePackagesDiagnostic::DuplicatePackage {
package: package.clone(),
paths: std::iter::once(distribution.install_path().to_owned())
.chain(std::iter::once(conflict.install_path().to_owned()))
.chain(distributions.map(|dist| dist.install_path().to_owned()))
.collect(),
});
continue;
}
for index in indexes {
let Some(distribution) = &self.distributions[*index] else {
continue;
};
// Determine the dependencies for the given package.
let Ok(metadata) = distribution.read_metadata() else {
diagnostics.push(SitePackagesDiagnostic::MetadataUnavailable {
package: package.clone(),
path: distribution.install_path().to_owned(),
});
continue;
};
// Verify that the package is compatible with the current Python version.
if let Some(requires_python) = metadata.requires_python.as_ref() {
if !requires_python.contains(markers.python_full_version()) {
diagnostics.push(SitePackagesDiagnostic::IncompatiblePythonVersion {
package: package.clone(),
version: self.interpreter.python_version().clone(),
requires_python: requires_python.clone(),
});
}
}
// Verify that the package is compatible with the current tags.
match distribution.read_tags() {
Ok(Some(wheel_tags)) => {
if !wheel_tags.is_compatible(tags) {
// TODO(charlie): Show the expanded tag hint, that explains _why_ it doesn't match.
diagnostics.push(SitePackagesDiagnostic::IncompatiblePlatform {
package: package.clone(),
});
}
}
Ok(None) => {}
Err(_) => {
diagnostics.push(SitePackagesDiagnostic::TagsUnavailable {
package: package.clone(),
path: distribution.install_path().to_owned(),
});
}
}
// Verify that the dependencies are installed.
for dependency in &metadata.requires_dist {
if !dependency.evaluate_markers(markers, &[]) {
continue;
}
let installed = self.get_packages(&dependency.name);
match installed.as_slice() {
[] => {
// No version installed.
diagnostics.push(SitePackagesDiagnostic::MissingDependency {
package: package.clone(),
requirement: dependency.clone(),
});
}
[installed] => {
match &dependency.version_or_url {
None | Some(VersionOrUrl::Url(_)) => {
// Nothing to do (accept any installed version).
}
Some(VersionOrUrl::VersionSpecifier(version_specifier)) => {
// The installed version doesn't satisfy the requirement.
if !version_specifier.contains(installed.version()) {
diagnostics.push(
SitePackagesDiagnostic::IncompatibleDependency {
package: package.clone(),
version: installed.version().clone(),
requirement: dependency.clone(),
},
);
}
}
}
}
_ => {
// There are multiple installed distributions for the same package.
}
}
}
}
}
Ok(diagnostics)
}
/// Returns if the installed packages satisfy the given requirements.
pub fn satisfies_spec(
&self,
requirements: &[UnresolvedRequirementSpecification],
constraints: &[NameRequirementSpecification],
overrides: &[UnresolvedRequirementSpecification],
installation: InstallationStrategy,
markers: &ResolverMarkerEnvironment,
tags: &Tags,
config_settings: &ConfigSettings,
config_settings_package: &PackageConfigSettings,
extra_build_requires: &ExtraBuildRequires,
extra_build_variables: &ExtraBuildVariables,
) -> Result<SatisfiesResult> {
// First, map all unnamed requirements to named requirements.
let requirements = {
let mut named = Vec::with_capacity(requirements.len());
for requirement in requirements {
match &requirement.requirement {
UnresolvedRequirement::Named(requirement) => {
named.push(Cow::Borrowed(requirement));
}
UnresolvedRequirement::Unnamed(requirement) => {
match self.get_urls(requirement.url.verbatim.raw()).as_slice() {
[] => {
return Ok(SatisfiesResult::Unsatisfied(
requirement.url.verbatim.raw().to_string(),
));
}
[distribution] => {
let requirement = uv_pep508::Requirement {
name: distribution.name().clone(),
version_or_url: Some(VersionOrUrl::Url(
requirement.url.clone(),
)),
marker: requirement.marker,
extras: requirement.extras.clone(),
origin: requirement.origin.clone(),
};
named.push(Cow::Owned(Requirement::from(requirement)));
}
_ => {
return Ok(SatisfiesResult::Unsatisfied(
requirement.url.verbatim.raw().to_string(),
));
}
}
}
}
}
named
};
// Second, map all overrides to named requirements. We assume that all overrides are
// relevant.
let overrides = {
let mut named = Vec::with_capacity(overrides.len());
for requirement in overrides {
match &requirement.requirement {
UnresolvedRequirement::Named(requirement) => {
named.push(Cow::Borrowed(requirement));
}
UnresolvedRequirement::Unnamed(requirement) => {
match self.get_urls(requirement.url.verbatim.raw()).as_slice() {
[] => {
return Ok(SatisfiesResult::Unsatisfied(
requirement.url.verbatim.raw().to_string(),
));
}
[distribution] => {
let requirement = uv_pep508::Requirement {
name: distribution.name().clone(),
version_or_url: Some(VersionOrUrl::Url(
requirement.url.clone(),
)),
marker: requirement.marker,
extras: requirement.extras.clone(),
origin: requirement.origin.clone(),
};
named.push(Cow::Owned(Requirement::from(requirement)));
}
_ => {
return Ok(SatisfiesResult::Unsatisfied(
requirement.url.verbatim.raw().to_string(),
));
}
}
}
}
}
named
};
self.satisfies_requirements(
requirements.iter().map(Cow::as_ref),
constraints.iter().map(|constraint| &constraint.requirement),
overrides.iter().map(Cow::as_ref),
installation,
markers,
tags,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
)
}
/// Like [`SitePackages::satisfies_spec`], but with resolved names for all requirements.
pub fn satisfies_requirements<'a>(
&self,
requirements: impl ExactSizeIterator<Item = &'a Requirement>,
constraints: impl Iterator<Item = &'a Requirement>,
overrides: impl Iterator<Item = &'a Requirement>,
installation: InstallationStrategy,
markers: &ResolverMarkerEnvironment,
tags: &Tags,
config_settings: &ConfigSettings,
config_settings_package: &PackageConfigSettings,
extra_build_requires: &ExtraBuildRequires,
extra_build_variables: &ExtraBuildVariables,
) -> Result<SatisfiesResult> {
// Collect the constraints and overrides by package name.
let constraints: FxHashMap<&PackageName, Vec<&Requirement>> =
constraints.fold(FxHashMap::default(), |mut constraints, constraint| {
constraints
.entry(&constraint.name)
.or_default()
.push(constraint);
constraints
});
let overrides: FxHashMap<&PackageName, Vec<&Requirement>> =
overrides.fold(FxHashMap::default(), |mut overrides, r#override| {
overrides
.entry(&r#override.name)
.or_default()
.push(r#override);
overrides
});
let mut stack = Vec::with_capacity(requirements.len());
let mut seen = FxHashSet::with_capacity_and_hasher(requirements.len(), FxBuildHasher);
// Add the direct requirements to the queue.
for requirement in requirements {
if let Some(r#overrides) = overrides.get(&requirement.name) {
for dependency in r#overrides {
if dependency.evaluate_markers(Some(markers), &[]) {
if seen.insert((*dependency).clone()) {
stack.push(Cow::Borrowed(*dependency));
}
}
}
} else {
if requirement.evaluate_markers(Some(markers), &[]) {
if seen.insert(requirement.clone()) {
stack.push(Cow::Borrowed(requirement));
}
}
}
}
// Verify that all non-editable requirements are met.
while let Some(requirement) = stack.pop() {
let name = &requirement.name;
let installed = self.get_packages(name);
match installed.as_slice() {
[] => {
// The package isn't installed.
return Ok(SatisfiesResult::Unsatisfied(requirement.to_string()));
}
[distribution] => {
// Validate that the requirement is satisfied.
if requirement.evaluate_markers(Some(markers), &[]) {
match RequirementSatisfaction::check(
name,
distribution,
&requirement.source,
installation,
tags,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
) {
RequirementSatisfaction::Mismatch
| RequirementSatisfaction::OutOfDate
| RequirementSatisfaction::CacheInvalid => {
return Ok(SatisfiesResult::Unsatisfied(requirement.to_string()));
}
RequirementSatisfaction::Satisfied => {}
}
}
// Validate that the installed version satisfies the constraints.
for constraint in constraints.get(name).into_iter().flatten() {
if constraint.evaluate_markers(Some(markers), &[]) {
match RequirementSatisfaction::check(
name,
distribution,
&constraint.source,
installation,
tags,
config_settings,
config_settings_package,
extra_build_requires,
extra_build_variables,
) {
RequirementSatisfaction::Mismatch
| RequirementSatisfaction::OutOfDate
| RequirementSatisfaction::CacheInvalid => {
return Ok(SatisfiesResult::Unsatisfied(
requirement.to_string(),
));
}
RequirementSatisfaction::Satisfied => {}
}
}
}
// Recurse into the dependencies.
let metadata = distribution
.read_metadata()
.with_context(|| format!("Failed to read metadata for: {distribution}"))?;
// Add the dependencies to the queue.
for dependency in &metadata.requires_dist {
let dependency = Requirement::from(dependency.clone());
if let Some(r#overrides) = overrides.get(&dependency.name) {
for dependency in r#overrides {
if dependency.evaluate_markers(Some(markers), &requirement.extras) {
if seen.insert((*dependency).clone()) {
stack.push(Cow::Borrowed(*dependency));
}
}
}
} else {
if dependency.evaluate_markers(Some(markers), &requirement.extras) {
if seen.insert(dependency.clone()) {
stack.push(Cow::Owned(dependency));
}
}
}
}
}
_ => {
// There are multiple installed distributions for the same package.
return Ok(SatisfiesResult::Unsatisfied(requirement.to_string()));
}
}
}
Ok(SatisfiesResult::Fresh {
recursive_requirements: seen,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallationStrategy {
/// A permissive installation strategy, which accepts existing installations even if the source
/// type differs, as in the `pip` and `uv pip` CLIs.
///
/// In this strategy, packages that are already installed in the environment may be reused if
/// they implicitly match the requirements. For example, if the user installs `./path/to/idna`,
/// then runs `uv pip install anyio` (which depends on `idna`), the existing `idna` installation
/// will be reused if its version matches the requirement, even though it was installed from a
/// path and is being implicitly requested from a registry.
Permissive,
/// A strict installation strategy, which requires that existing installations match the source
/// type, as in the `uv sync` CLI.
///
/// This strategy enforces that the installation source must match the requirement source.
/// It prevents reusing packages that were installed from different sources, ensuring
/// declarative and reproducible environments.
Strict,
}
/// We check if all requirements are already satisfied, recursing through the requirements tree.
#[derive(Debug)]
pub enum SatisfiesResult {
/// All requirements are recursively satisfied.
Fresh {
/// The flattened set (transitive closure) of all requirements checked.
recursive_requirements: FxHashSet<Requirement>,
},
/// We found an unsatisfied requirement. Since we exit early, we only know about the first
/// unsatisfied requirement.
Unsatisfied(String),
}
impl IntoIterator for SitePackages {
type Item = InstalledDist;
type IntoIter = Flatten<std::vec::IntoIter<Option<InstalledDist>>>;
fn into_iter(self) -> Self::IntoIter {
self.distributions.into_iter().flatten()
}
}
#[derive(Debug)]
pub enum SitePackagesDiagnostic {
MetadataUnavailable {
/// The package that is missing metadata.
package: PackageName,
/// The path to the package.
path: PathBuf,
},
TagsUnavailable {
/// The package that is missing tags.
package: PackageName,
/// The path to the package.
path: PathBuf,
},
IncompatiblePythonVersion {
/// The package that requires a different version of Python.
package: PackageName,
/// The version of Python that is installed.
version: Version,
/// The version of Python that is required.
requires_python: VersionSpecifiers,
},
IncompatiblePlatform {
/// The package that was built for a different platform.
package: PackageName,
},
MissingDependency {
/// The package that is missing a dependency.
package: PackageName,
/// The dependency that is missing.
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
},
IncompatibleDependency {
/// The package that has an incompatible dependency.
package: PackageName,
/// The version of the package that is installed.
version: Version,
/// The dependency that is incompatible.
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
},
DuplicatePackage {
/// The package that has multiple installed distributions.
package: PackageName,
/// The installed versions of the package.
paths: Vec<PathBuf>,
},
}
impl Diagnostic for SitePackagesDiagnostic {
/// Convert the diagnostic into a user-facing message.
fn message(&self) -> String {
match self {
Self::MetadataUnavailable { package, path } => format!(
"The package `{package}` is broken or incomplete (unable to read `METADATA`). Consider recreating the virtualenv, or removing the package directory at: {}.",
path.display(),
),
Self::TagsUnavailable { package, path } => format!(
"The package `{package}` is broken or incomplete (unable to read `WHEEL` file). Consider recreating the virtualenv, or removing the package directory at: {}.",
path.display(),
),
Self::IncompatiblePythonVersion {
package,
version,
requires_python,
} => format!(
"The package `{package}` requires Python {requires_python}, but `{version}` is installed"
),
Self::IncompatiblePlatform { package } => {
format!("The package `{package}` was built for a different platform")
}
Self::MissingDependency {
package,
requirement,
} => {
format!("The package `{package}` requires `{requirement}`, but it's not installed")
}
Self::IncompatibleDependency {
package,
version,
requirement,
} => format!(
"The package `{package}` requires `{requirement}`, but `{version}` is installed"
),
Self::DuplicatePackage { package, paths } => {
let mut paths = paths.clone();
paths.sort();
format!(
"The package `{package}` has multiple installed distributions: {}",
paths.iter().fold(String::new(), |acc, path| acc
+ &format!("\n - {}", path.display()))
)
}
}
}
/// Returns `true` if the [`PackageName`] is involved in this diagnostic.
fn includes(&self, name: &PackageName) -> bool {
match self {
Self::MetadataUnavailable { package, .. } => name == package,
Self::TagsUnavailable { package, .. } => name == package,
Self::IncompatiblePythonVersion { package, .. } => name == package,
Self::IncompatiblePlatform { package } => name == package,
Self::MissingDependency { package, .. } => name == package,
Self::IncompatibleDependency {
package,
requirement,
..
} => name == package || &requirement.name == name,
Self::DuplicatePackage { package, .. } => name == package,
}
}
}
impl InstalledPackagesProvider for SitePackages {
fn iter(&self) -> impl Iterator<Item = &InstalledDist> {
self.iter()
}
fn get_packages(&self, name: &PackageName) -> Vec<&InstalledDist> {
self.get_packages(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-settings/src/settings.rs | crates/uv-settings/src/settings.rs | use std::{fmt::Debug, num::NonZeroUsize, path::Path, path::PathBuf};
use serde::{Deserialize, Serialize};
use uv_cache_info::CacheKey;
use uv_configuration::{
BuildIsolation, IndexStrategy, KeyringProviderType, PackageNameSpecifier, Reinstall,
RequiredVersion, TargetTriple, TrustedHost, TrustedPublishing, Upgrade,
};
use uv_distribution_types::{
ConfigSettings, ExtraBuildVariables, Index, IndexUrl, IndexUrlError, PackageConfigSettings,
PipExtraIndex, PipFindLinks, PipIndex, StaticMetadata,
};
use uv_install_wheel::LinkMode;
use uv_macros::{CombineOptions, OptionsMetadata};
use uv_normalize::{ExtraName, PackageName, PipGroupName};
use uv_pep508::Requirement;
use uv_pypi_types::{SupportedEnvironments, VerbatimParsedUrl};
use uv_python::{PythonDownloads, PythonPreference, PythonVersion};
use uv_redacted::DisplaySafeUrl;
use uv_resolver::{
AnnotationStyle, ExcludeNewer, ExcludeNewerPackage, ExcludeNewerValue, ForkStrategy,
PrereleaseMode, ResolutionMode,
};
use uv_torch::TorchMode;
use uv_workspace::pyproject::ExtraBuildDependencies;
use uv_workspace::pyproject_mut::AddBoundsKind;
/// A `pyproject.toml` with an (optional) `[tool.uv]` section.
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct PyProjectToml {
pub(crate) tool: Option<Tools>,
}
/// A `[tool]` section.
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct Tools {
pub(crate) uv: Option<Options>,
}
/// A `[tool.uv]` section.
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Deserialize, CombineOptions, OptionsMetadata)]
#[serde(from = "OptionsWire", rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(!from))]
pub struct Options {
#[serde(flatten)]
pub globals: GlobalOptions,
#[serde(flatten)]
pub top_level: ResolverInstallerSchema,
#[serde(flatten)]
pub install_mirrors: PythonInstallMirrors,
#[serde(flatten)]
pub publish: PublishOptions,
#[serde(flatten)]
pub add: AddOptions,
#[option_group]
pub pip: Option<PipOptions>,
/// The keys to consider when caching builds for the project.
///
/// Cache keys enable you to specify the files or directories that should trigger a rebuild when
/// modified. By default, uv will rebuild a project whenever the `pyproject.toml`, `setup.py`,
/// or `setup.cfg` files in the project directory are modified, or if a `src` directory is
/// added or removed, i.e.:
///
/// ```toml
/// cache-keys = [{ file = "pyproject.toml" }, { file = "setup.py" }, { file = "setup.cfg" }, { dir = "src" }]
/// ```
///
/// As an example: if a project uses dynamic metadata to read its dependencies from a
/// `requirements.txt` file, you can specify `cache-keys = [{ file = "requirements.txt" }, { file = "pyproject.toml" }]`
/// to ensure that the project is rebuilt whenever the `requirements.txt` file is modified (in
/// addition to watching the `pyproject.toml`).
///
/// Globs are supported, following the syntax of the [`glob`](https://docs.rs/glob/0.3.1/glob/struct.Pattern.html)
/// crate. For example, to invalidate the cache whenever a `.toml` file in the project directory
/// or any of its subdirectories is modified, you can specify `cache-keys = [{ file = "**/*.toml" }]`.
/// Note that the use of globs can be expensive, as uv may need to walk the filesystem to
/// determine whether any files have changed.
///
/// Cache keys can also include version control information. For example, if a project uses
/// `setuptools_scm` to read its version from a Git commit, you can specify `cache-keys = [{ git = { commit = true }, { file = "pyproject.toml" }]`
/// to include the current Git commit hash in the cache key (in addition to the
/// `pyproject.toml`). Git tags are also supported via `cache-keys = [{ git = { commit = true, tags = true } }]`.
///
/// Cache keys can also include environment variables. For example, if a project relies on
/// `MACOSX_DEPLOYMENT_TARGET` or other environment variables to determine its behavior, you can
/// specify `cache-keys = [{ env = "MACOSX_DEPLOYMENT_TARGET" }]` to invalidate the cache
/// whenever the environment variable changes.
///
/// Cache keys only affect the project defined by the `pyproject.toml` in which they're
/// specified (as opposed to, e.g., affecting all members in a workspace), and all paths and
/// globs are interpreted as relative to the project directory.
#[option(
default = r#"[{ file = "pyproject.toml" }, { file = "setup.py" }, { file = "setup.cfg" }]"#,
value_type = "list[dict]",
example = r#"
cache-keys = [{ file = "pyproject.toml" }, { file = "requirements.txt" }, { git = { commit = true } }]
"#
)]
pub cache_keys: Option<Vec<CacheKey>>,
// NOTE(charlie): These fields are shared with `ToolUv` in
// `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
// They're respected in both `pyproject.toml` and `uv.toml` files.
#[cfg_attr(feature = "schemars", schemars(skip))]
pub override_dependencies: Option<Vec<Requirement<VerbatimParsedUrl>>>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub exclude_dependencies: Option<Vec<uv_normalize::PackageName>>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub constraint_dependencies: Option<Vec<Requirement<VerbatimParsedUrl>>>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub build_constraint_dependencies: Option<Vec<Requirement<VerbatimParsedUrl>>>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub environments: Option<SupportedEnvironments>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub required_environments: Option<SupportedEnvironments>,
// NOTE(charlie): These fields should be kept in-sync with `ToolUv` in
// `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
// They're only respected in `pyproject.toml` files, and should be rejected in `uv.toml` files.
#[cfg_attr(feature = "schemars", schemars(skip))]
pub conflicts: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub workspace: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub sources: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub dev_dependencies: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub default_groups: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub dependency_groups: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub managed: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub r#package: Option<serde::de::IgnoredAny>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub build_backend: Option<serde::de::IgnoredAny>,
}
impl Options {
/// Construct an [`Options`] with the given global and top-level settings.
pub fn simple(globals: GlobalOptions, top_level: ResolverInstallerSchema) -> Self {
Self {
globals,
top_level,
..Default::default()
}
}
/// Resolve the [`Options`] relative to the given root directory.
pub fn relative_to(self, root_dir: &Path) -> Result<Self, IndexUrlError> {
Ok(Self {
top_level: self.top_level.relative_to(root_dir)?,
pip: self.pip.map(|pip| pip.relative_to(root_dir)).transpose()?,
..self
})
}
}
/// Global settings, relevant to all invocations.
#[derive(Debug, Clone, Default, Deserialize, CombineOptions, OptionsMetadata)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct GlobalOptions {
/// Enforce a requirement on the version of uv.
///
/// If the version of uv does not meet the requirement at runtime, uv will exit
/// with an error.
///
/// Accepts a [PEP 440](https://peps.python.org/pep-0440/) specifier, like `==0.5.0` or `>=0.5.0`.
#[option(
default = "null",
value_type = "str",
example = r#"
required-version = ">=0.5.0"
"#
)]
pub required_version: Option<RequiredVersion>,
/// 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.
#[option(
default = "false",
value_type = "bool",
example = r#"
native-tls = true
"#
)]
pub native_tls: Option<bool>,
/// Disable network access, relying only on locally cached data and locally available files.
#[option(
default = "false",
value_type = "bool",
example = r#"
offline = true
"#
)]
pub offline: Option<bool>,
/// Avoid reading from or writing to the cache, instead using a temporary directory for the
/// duration of the operation.
#[option(
default = "false",
value_type = "bool",
example = r#"
no-cache = true
"#
)]
pub no_cache: Option<bool>,
/// Path to the cache directory.
///
/// Defaults to `$XDG_CACHE_HOME/uv` or `$HOME/.cache/uv` on Linux and macOS, and
/// `%LOCALAPPDATA%\uv\cache` on Windows.
#[option(
default = "None",
value_type = "str",
example = r#"
cache-dir = "./.uv_cache"
"#
)]
pub cache_dir: Option<PathBuf>,
/// Whether to enable experimental, preview features.
#[option(
default = "false",
value_type = "bool",
example = r#"
preview = true
"#
)]
pub preview: Option<bool>,
/// Whether to prefer using Python installations that are already present on the system, or
/// those that are downloaded and installed by uv.
#[option(
default = "\"managed\"",
value_type = "str",
example = r#"
python-preference = "managed"
"#,
possible_values = true
)]
pub python_preference: Option<PythonPreference>,
/// Whether to allow Python downloads.
#[option(
default = "\"automatic\"",
value_type = "str",
example = r#"
python-downloads = "manual"
"#,
possible_values = true
)]
pub python_downloads: Option<PythonDownloads>,
/// The maximum number of in-flight concurrent downloads that uv will perform at any given
/// time.
#[option(
default = "50",
value_type = "int",
example = r#"
concurrent-downloads = 4
"#
)]
pub concurrent_downloads: Option<NonZeroUsize>,
/// The maximum number of source distributions that uv will build concurrently at any given
/// time.
///
/// Defaults to the number of available CPU cores.
#[option(
default = "None",
value_type = "int",
example = r#"
concurrent-builds = 4
"#
)]
pub concurrent_builds: Option<NonZeroUsize>,
/// The number of threads used when installing and unzipping packages.
///
/// Defaults to the number of available CPU cores.
#[option(
default = "None",
value_type = "int",
example = r#"
concurrent-installs = 4
"#
)]
pub concurrent_installs: Option<NonZeroUsize>,
/// Allow insecure connections to host.
///
/// 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.
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
allow-insecure-host = ["localhost:8080"]
"#
)]
pub allow_insecure_host: Option<Vec<TrustedHost>>,
}
/// Settings relevant to all installer operations.
#[derive(Debug, Clone, Default, CombineOptions)]
pub struct InstallerOptions {
pub index: Option<Vec<Index>>,
pub index_url: Option<PipIndex>,
pub extra_index_url: Option<Vec<PipExtraIndex>>,
pub no_index: Option<bool>,
pub find_links: Option<Vec<PipFindLinks>>,
pub index_strategy: Option<IndexStrategy>,
pub keyring_provider: Option<KeyringProviderType>,
pub config_settings: Option<ConfigSettings>,
pub exclude_newer: Option<ExcludeNewerValue>,
pub link_mode: Option<LinkMode>,
pub compile_bytecode: Option<bool>,
pub reinstall: Option<Reinstall>,
pub build_isolation: Option<BuildIsolation>,
pub no_build: Option<bool>,
pub no_build_package: Option<Vec<PackageName>>,
pub no_binary: Option<bool>,
pub no_binary_package: Option<Vec<PackageName>>,
pub no_sources: Option<bool>,
}
/// Settings relevant to all resolver operations.
#[derive(Debug, Clone, Default, CombineOptions)]
pub struct ResolverOptions {
pub index: Option<Vec<Index>>,
pub index_url: Option<PipIndex>,
pub extra_index_url: Option<Vec<PipExtraIndex>>,
pub no_index: Option<bool>,
pub find_links: Option<Vec<PipFindLinks>>,
pub index_strategy: Option<IndexStrategy>,
pub keyring_provider: Option<KeyringProviderType>,
pub resolution: Option<ResolutionMode>,
pub prerelease: Option<PrereleaseMode>,
pub fork_strategy: Option<ForkStrategy>,
pub dependency_metadata: Option<Vec<StaticMetadata>>,
pub config_settings: Option<ConfigSettings>,
pub config_settings_package: Option<PackageConfigSettings>,
pub exclude_newer: ExcludeNewer,
pub link_mode: Option<LinkMode>,
pub torch_backend: Option<TorchMode>,
pub upgrade: Option<Upgrade>,
pub build_isolation: Option<BuildIsolation>,
pub no_build: Option<bool>,
pub no_build_package: Option<Vec<PackageName>>,
pub no_binary: Option<bool>,
pub no_binary_package: Option<Vec<PackageName>>,
pub extra_build_dependencies: Option<ExtraBuildDependencies>,
pub extra_build_variables: Option<ExtraBuildVariables>,
pub no_sources: Option<bool>,
}
/// Shared settings, relevant to all operations that must resolve and install dependencies. The
/// union of [`InstallerOptions`] and [`ResolverOptions`].
#[derive(Debug, Clone, Default, CombineOptions)]
pub struct ResolverInstallerOptions {
pub index: Option<Vec<Index>>,
pub index_url: Option<PipIndex>,
pub extra_index_url: Option<Vec<PipExtraIndex>>,
pub no_index: Option<bool>,
pub find_links: Option<Vec<PipFindLinks>>,
pub index_strategy: Option<IndexStrategy>,
pub keyring_provider: Option<KeyringProviderType>,
pub resolution: Option<ResolutionMode>,
pub prerelease: Option<PrereleaseMode>,
pub fork_strategy: Option<ForkStrategy>,
pub dependency_metadata: Option<Vec<StaticMetadata>>,
pub config_settings: Option<ConfigSettings>,
pub config_settings_package: Option<PackageConfigSettings>,
pub build_isolation: Option<BuildIsolation>,
pub extra_build_dependencies: Option<ExtraBuildDependencies>,
pub extra_build_variables: Option<ExtraBuildVariables>,
pub exclude_newer: Option<ExcludeNewerValue>,
pub exclude_newer_package: Option<ExcludeNewerPackage>,
pub link_mode: Option<LinkMode>,
pub torch_backend: Option<TorchMode>,
pub compile_bytecode: Option<bool>,
pub no_sources: Option<bool>,
pub upgrade: Option<Upgrade>,
pub reinstall: Option<Reinstall>,
pub no_build: Option<bool>,
pub no_build_package: Option<Vec<PackageName>>,
pub no_binary: Option<bool>,
pub no_binary_package: Option<Vec<PackageName>>,
}
impl From<ResolverInstallerSchema> for ResolverInstallerOptions {
fn from(value: ResolverInstallerSchema) -> Self {
let ResolverInstallerSchema {
index,
index_url,
extra_index_url,
no_index,
find_links,
index_strategy,
keyring_provider,
resolution,
prerelease,
fork_strategy,
dependency_metadata,
config_settings,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
extra_build_dependencies,
extra_build_variables,
exclude_newer,
exclude_newer_package,
link_mode,
torch_backend,
compile_bytecode,
no_sources,
upgrade,
upgrade_package,
reinstall,
reinstall_package,
no_build,
no_build_package,
no_binary,
no_binary_package,
} = value;
Self {
index,
index_url,
extra_index_url,
no_index,
find_links,
index_strategy,
keyring_provider,
resolution,
prerelease,
fork_strategy,
dependency_metadata,
config_settings,
config_settings_package,
build_isolation: BuildIsolation::from_args(
no_build_isolation,
no_build_isolation_package.into_iter().flatten().collect(),
),
extra_build_dependencies,
extra_build_variables,
exclude_newer,
exclude_newer_package,
link_mode,
torch_backend,
compile_bytecode,
no_sources,
upgrade: Upgrade::from_args(
upgrade,
upgrade_package
.into_iter()
.flatten()
.map(Into::into)
.collect(),
),
reinstall: Reinstall::from_args(reinstall, reinstall_package.unwrap_or_default()),
no_build,
no_build_package,
no_binary,
no_binary_package,
}
}
}
impl ResolverInstallerSchema {
/// Resolve the [`ResolverInstallerSchema`] relative to the given root directory.
pub fn relative_to(self, root_dir: &Path) -> Result<Self, IndexUrlError> {
Ok(Self {
index: self
.index
.map(|index| {
index
.into_iter()
.map(|index| index.relative_to(root_dir))
.collect::<Result<Vec<_>, _>>()
})
.transpose()?,
index_url: self
.index_url
.map(|index_url| index_url.relative_to(root_dir))
.transpose()?,
extra_index_url: self
.extra_index_url
.map(|extra_index_url| {
extra_index_url
.into_iter()
.map(|extra_index_url| extra_index_url.relative_to(root_dir))
.collect::<Result<Vec<_>, _>>()
})
.transpose()?,
find_links: self
.find_links
.map(|find_links| {
find_links
.into_iter()
.map(|find_link| find_link.relative_to(root_dir))
.collect::<Result<Vec<_>, _>>()
})
.transpose()?,
..self
})
}
}
/// The JSON schema for the `[tool.uv]` section of a `pyproject.toml` file.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ResolverInstallerSchema {
/// The package 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 those
/// 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"
"#
)]
pub index: Option<Vec<Index>>,
/// The URL of the Python package index (by default: <https://pypi.org/simple>).
///
/// 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.
///
/// The index provided by this setting is given lower priority than any indexes specified via
/// [`extra_index_url`](#extra-index-url) or [`index`](#index).
///
/// (Deprecated: use `index` instead.)
#[option(
default = "\"https://pypi.org/simple\"",
value_type = "str",
example = r#"
index-url = "https://test.pypi.org/simple"
"#
)]
pub index_url: Option<PipIndex>,
/// Extra URLs of package indexes to use, in addition to `--index-url`.
///
/// 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.
///
/// All indexes provided via this flag take priority over the index specified by
/// [`index_url`](#index-url) or [`index`](#index) with `default = true`. When multiple indexes
/// are provided, earlier values take priority.
///
/// To control uv's resolution strategy when multiple indexes are present, see
/// [`index_strategy`](#index-strategy).
///
/// (Deprecated: use `index` instead.)
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
extra-index-url = ["https://download.pytorch.org/whl/cpu"]
"#
)]
pub extra_index_url: Option<Vec<PipExtraIndex>>,
/// Ignore all registry indexes (e.g., PyPI), instead relying on direct URL dependencies and
/// those provided via `--find-links`.
#[option(
default = "false",
value_type = "bool",
example = r#"
no-index = true
"#
)]
pub no_index: Option<bool>,
/// Locations to search for candidate distributions, in addition to those found in the registry
/// indexes.
///
/// If a path, the target must be a directory that contains packages as wheel files (`.whl`) or
/// source distributions (e.g., `.tar.gz` or `.zip`) at the top level.
///
/// If a URL, the page must contain a flat list of links to package files adhering to the
/// formats described above.
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
find-links = ["https://download.pytorch.org/whl/torch_stable.html"]
"#
)]
pub find_links: Option<Vec<PipFindLinks>>,
/// The strategy to use when resolving against multiple index URLs.
///
/// By default, uv will stop at the first index on which a given package is available, and
/// limit resolutions to those present on that first index (`first-index`). This prevents
/// "dependency confusion" attacks, whereby an attacker can upload a malicious package under the
/// same name to an alternate index.
#[option(
default = "\"first-index\"",
value_type = "str",
example = r#"
index-strategy = "unsafe-best-match"
"#,
possible_values = true
)]
pub index_strategy: Option<IndexStrategy>,
/// Attempt to use `keyring` for authentication for index URLs.
///
/// At present, only `--keyring-provider subprocess` is supported, which configures uv to
/// use the `keyring` CLI to handle authentication.
#[option(
default = "\"disabled\"",
value_type = "str",
example = r#"
keyring-provider = "subprocess"
"#
)]
pub keyring_provider: Option<KeyringProviderType>,
/// The strategy to use when selecting between the different compatible versions for a given
/// package requirement.
///
/// By default, uv will use the latest compatible version of each package (`highest`).
#[option(
default = "\"highest\"",
value_type = "str",
example = r#"
resolution = "lowest-direct"
"#,
possible_values = true
)]
pub resolution: Option<ResolutionMode>,
/// The strategy to use when considering pre-release versions.
///
/// By default, uv will accept pre-releases for packages that _only_ publish pre-releases,
/// along with first-party requirements that contain an explicit pre-release marker in the
/// declared specifiers (`if-necessary-or-explicit`).
#[option(
default = "\"if-necessary-or-explicit\"",
value_type = "str",
example = r#"
prerelease = "allow"
"#,
possible_values = true
)]
pub prerelease: Option<PrereleaseMode>,
/// The strategy to use when selecting multiple versions of a given package across Python
/// versions and platforms.
///
/// By default, uv will optimize for selecting the latest version of each package for each
/// supported Python version (`requires-python`), while minimizing the number of selected
/// versions across platforms.
///
/// Under `fewest`, uv will minimize the number of selected versions for each package,
/// preferring older versions that are compatible with a wider range of supported Python
/// versions or platforms.
#[option(
default = "\"requires-python\"",
value_type = "str",
example = r#"
fork-strategy = "fewest"
"#,
possible_values = true
)]
pub fork_strategy: Option<ForkStrategy>,
/// Pre-defined static metadata for dependencies of the project (direct or transitive). When
/// provided, enables the resolver to use the specified metadata instead of querying the
/// registry or building the relevant package from source.
///
/// Metadata should be provided in adherence with the [Metadata 2.3](https://packaging.python.org/en/latest/specifications/core-metadata/)
/// standard, though only the following fields are respected:
///
/// - `name`: The name of the package.
/// - (Optional) `version`: The version of the package. If omitted, the metadata will be applied
/// to all versions of the package.
/// - (Optional) `requires-dist`: The dependencies of the package (e.g., `werkzeug>=0.14`).
/// - (Optional) `requires-python`: The Python version required by the package (e.g., `>=3.10`).
/// - (Optional) `provides-extra`: The extras provided by the package.
#[option(
default = r#"[]"#,
value_type = "list[dict]",
example = r#"
dependency-metadata = [
{ name = "flask", version = "1.0.0", requires-dist = ["werkzeug"], requires-python = ">=3.6" },
]
"#
)]
pub dependency_metadata: Option<Vec<StaticMetadata>>,
/// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend,
/// specified as `KEY=VALUE` pairs.
#[option(
default = "{}",
value_type = "dict",
example = r#"
config-settings = { editable_mode = "compat" }
"#
)]
pub config_settings: Option<ConfigSettings>,
/// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend for specific packages,
/// specified as `KEY=VALUE` pairs.
///
/// Accepts a map from package names to string key-value pairs.
#[option(
default = "{}",
value_type = "dict",
example = r#"
config-settings-package = { numpy = { editable_mode = "compat" } }
"#
)]
pub config_settings_package: Option<PackageConfigSettings>,
/// Disable isolation when building source distributions.
///
/// Assumes that build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
/// are already installed.
#[option(
default = "false",
value_type = "bool",
example = r#"
no-build-isolation = true
"#
)]
pub no_build_isolation: Option<bool>,
/// Disable isolation when building source distributions for a specific package.
///
/// Assumes that the packages' build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
/// are already installed.
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
no-build-isolation-package = ["package1", "package2"]
"#
)]
pub no_build_isolation_package: Option<Vec<PackageName>>,
/// Additional build dependencies for packages.
///
/// This allows extending the PEP 517 build environment for the project's dependencies with
/// additional packages. This is useful for packages that assume the presence of packages like
/// `pip`, and do not declare them as build dependencies.
#[option(
default = "[]",
value_type = "dict",
example = r#"
extra-build-dependencies = { pytest = ["setuptools"] }
"#
)]
pub extra_build_dependencies: Option<ExtraBuildDependencies>,
/// Extra environment variables to set when building certain packages.
///
/// Environment variables will be added to the environment when building the
/// specified packages.
#[option(
default = r#"{}"#,
value_type = r#"dict[str, dict[str, str]]"#,
example = r#"
extra-build-variables = { flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" } }
"#
)]
pub extra_build_variables: Option<ExtraBuildVariables>,
/// Limit candidate packages to those that were uploaded prior to the given date.
///
/// Accepts RFC 3339 timestamps (e.g., `2006-12-02T02:07:43Z`), a "friendly" duration (e.g.,
/// `24 hours`, `1 week`, `30 days`), or an ISO 8601 duration (e.g., `PT24H`, `P7D`, `P30D`).
///
/// Durations do not respect semantics of the local time zone and are always resolved to a fixed
/// number of seconds assuming that a day is 24 hours (e.g., DST transitions are ignored).
/// Calendar units such as months and years are not allowed.
#[option(
default = "None",
value_type = "str",
example = r#"
exclude-newer = "2006-12-02T02:07:43Z"
"#
)]
pub exclude_newer: Option<ExcludeNewerValue>,
/// Limit candidate packages for specific packages to those that were uploaded prior to the
/// given date.
///
| 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-settings/src/lib.rs | crates/uv-settings/src/lib.rs | use std::num::NonZeroUsize;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::time::Duration;
use uv_dirs::{system_config_file, user_config_dir};
use uv_flags::EnvironmentFlags;
use uv_fs::Simplified;
use uv_static::EnvVars;
use uv_warnings::warn_user;
pub use crate::combine::*;
pub use crate::settings::*;
mod combine;
mod settings;
/// The [`Options`] as loaded from a configuration file on disk.
#[derive(Debug, Clone)]
pub struct FilesystemOptions(Options);
impl FilesystemOptions {
/// Convert the [`FilesystemOptions`] into [`Options`].
pub fn into_options(self) -> Options {
self.0
}
}
impl Deref for FilesystemOptions {
type Target = Options;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FilesystemOptions {
/// Load the user [`FilesystemOptions`].
pub fn user() -> Result<Option<Self>, Error> {
let Some(dir) = user_config_dir() else {
return Ok(None);
};
let root = dir.join("uv");
let file = root.join("uv.toml");
tracing::debug!("Searching for user configuration in: `{}`", file.display());
match read_file(&file) {
Ok(options) => {
tracing::debug!("Found user configuration in: `{}`", file.display());
validate_uv_toml(&file, &options)?;
Ok(Some(Self(options)))
}
Err(Error::Io(err))
if matches!(
err.kind(),
std::io::ErrorKind::NotFound
| std::io::ErrorKind::NotADirectory
| std::io::ErrorKind::PermissionDenied
) =>
{
Ok(None)
}
Err(err) => Err(err),
}
}
pub fn system() -> Result<Option<Self>, Error> {
let Some(file) = system_config_file() else {
return Ok(None);
};
tracing::debug!("Found system configuration in: `{}`", file.display());
let options = read_file(&file)?;
validate_uv_toml(&file, &options)?;
Ok(Some(Self(options)))
}
/// Find the [`FilesystemOptions`] for the given path.
///
/// The search starts at the given path and goes up the directory tree until a `uv.toml` file or
/// `pyproject.toml` file is found.
pub fn find(path: &Path) -> Result<Option<Self>, Error> {
for ancestor in path.ancestors() {
match Self::from_directory(ancestor) {
Ok(Some(options)) => {
return Ok(Some(options));
}
Ok(None) => {
// Continue traversing the directory tree.
}
Err(Error::PyprojectToml(path, err)) => {
// If we see an invalid `pyproject.toml`, warn but continue.
warn_user!(
"Failed to parse `{}` during settings discovery:\n{}",
path.user_display().cyan(),
textwrap::indent(&err.to_string(), " ")
);
}
Err(err) => {
// Otherwise, warn and stop.
return Err(err);
}
}
}
Ok(None)
}
/// Load a [`FilesystemOptions`] from a directory, preferring a `uv.toml` file over a
/// `pyproject.toml` file.
pub fn from_directory(dir: &Path) -> Result<Option<Self>, Error> {
// Read a `uv.toml` file in the current directory.
let path = dir.join("uv.toml");
match fs_err::read_to_string(&path) {
Ok(content) => {
let options = toml::from_str::<Options>(&content)
.map_err(|err| Error::UvToml(path.clone(), Box::new(err)))?
.relative_to(&std::path::absolute(dir)?)?;
// If the directory also contains a `[tool.uv]` table in a `pyproject.toml` file,
// warn.
let pyproject = dir.join("pyproject.toml");
if let Some(pyproject) = fs_err::read_to_string(pyproject)
.ok()
.and_then(|content| toml::from_str::<PyProjectToml>(&content).ok())
{
if let Some(options) = pyproject.tool.as_ref().and_then(|tool| tool.uv.as_ref())
{
warn_uv_toml_masked_fields(options);
}
}
tracing::debug!("Found workspace configuration at `{}`", path.display());
validate_uv_toml(&path, &options)?;
return Ok(Some(Self(options)));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
// Read a `pyproject.toml` file in the current directory.
let path = dir.join("pyproject.toml");
match fs_err::read_to_string(&path) {
Ok(content) => {
// Parse, but skip any `pyproject.toml` that doesn't have a `[tool.uv]` section.
let pyproject: PyProjectToml = toml::from_str(&content)
.map_err(|err| Error::PyprojectToml(path.clone(), Box::new(err)))?;
let Some(tool) = pyproject.tool else {
tracing::debug!(
"Skipping `pyproject.toml` in `{}` (no `[tool]` section)",
dir.display()
);
return Ok(None);
};
let Some(options) = tool.uv else {
tracing::debug!(
"Skipping `pyproject.toml` in `{}` (no `[tool.uv]` section)",
dir.display()
);
return Ok(None);
};
let options = options.relative_to(&std::path::absolute(dir)?)?;
tracing::debug!("Found workspace configuration at `{}`", path.display());
return Ok(Some(Self(options)));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
Ok(None)
}
/// Load a [`FilesystemOptions`] from a `uv.toml` file.
pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
let path = path.as_ref();
tracing::debug!("Reading user configuration from: `{}`", path.display());
let options = read_file(path)?;
validate_uv_toml(path, &options)?;
Ok(Self(options))
}
}
impl From<Options> for FilesystemOptions {
fn from(options: Options) -> Self {
Self(options)
}
}
/// Load [`Options`] from a `uv.toml` file.
fn read_file(path: &Path) -> Result<Options, Error> {
let content = fs_err::read_to_string(path)?;
let options = toml::from_str::<Options>(&content)
.map_err(|err| Error::UvToml(path.to_path_buf(), Box::new(err)))?;
let options = if let Some(parent) = std::path::absolute(path)?.parent() {
options.relative_to(parent)?
} else {
options
};
Ok(options)
}
/// Validate that an [`Options`] schema is compatible with `uv.toml`.
fn validate_uv_toml(path: &Path, options: &Options) -> Result<(), Error> {
let Options {
globals: _,
top_level: _,
install_mirrors: _,
publish: _,
add: _,
pip: _,
cache_keys: _,
override_dependencies: _,
exclude_dependencies: _,
constraint_dependencies: _,
build_constraint_dependencies: _,
environments,
required_environments,
conflicts,
workspace,
sources,
dev_dependencies,
default_groups,
dependency_groups,
managed,
package,
build_backend,
} = options;
// The `uv.toml` format is not allowed to include any of the following, which are
// permitted by the schema since they _can_ be included in `pyproject.toml` files
// (and we want to use `deny_unknown_fields`).
if conflicts.is_some() {
return Err(Error::PyprojectOnlyField(path.to_path_buf(), "conflicts"));
}
if workspace.is_some() {
return Err(Error::PyprojectOnlyField(path.to_path_buf(), "workspace"));
}
if sources.is_some() {
return Err(Error::PyprojectOnlyField(path.to_path_buf(), "sources"));
}
if dev_dependencies.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"dev-dependencies",
));
}
if default_groups.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"default-groups",
));
}
if dependency_groups.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"dependency-groups",
));
}
if managed.is_some() {
return Err(Error::PyprojectOnlyField(path.to_path_buf(), "managed"));
}
if package.is_some() {
return Err(Error::PyprojectOnlyField(path.to_path_buf(), "package"));
}
if build_backend.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"build-backend",
));
}
if environments.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"environments",
));
}
if required_environments.is_some() {
return Err(Error::PyprojectOnlyField(
path.to_path_buf(),
"required-environments",
));
}
Ok(())
}
/// Validate that an [`Options`] contains no fields that `uv.toml` would mask
///
/// This is essentially the inverse of [`validate_uv_toml`].
fn warn_uv_toml_masked_fields(options: &Options) {
let Options {
globals:
GlobalOptions {
required_version,
native_tls,
offline,
no_cache,
cache_dir,
preview,
python_preference,
python_downloads,
concurrent_downloads,
concurrent_builds,
concurrent_installs,
allow_insecure_host,
},
top_level:
ResolverInstallerSchema {
index,
index_url,
extra_index_url,
no_index,
find_links,
index_strategy,
keyring_provider,
resolution,
prerelease,
fork_strategy,
dependency_metadata,
config_settings,
config_settings_package,
no_build_isolation,
no_build_isolation_package,
extra_build_dependencies,
extra_build_variables,
exclude_newer,
exclude_newer_package,
link_mode,
compile_bytecode,
no_sources,
upgrade,
upgrade_package,
reinstall,
reinstall_package,
no_build,
no_build_package,
no_binary,
no_binary_package,
torch_backend,
},
install_mirrors:
PythonInstallMirrors {
python_install_mirror,
pypy_install_mirror,
python_downloads_json_url,
},
publish:
PublishOptions {
publish_url,
trusted_publishing,
check_url,
},
add: AddOptions { add_bounds },
pip,
cache_keys,
override_dependencies,
exclude_dependencies,
constraint_dependencies,
build_constraint_dependencies,
environments: _,
required_environments: _,
conflicts: _,
workspace: _,
sources: _,
dev_dependencies: _,
default_groups: _,
dependency_groups: _,
managed: _,
package: _,
build_backend: _,
} = options;
let mut masked_fields = vec![];
if required_version.is_some() {
masked_fields.push("required-version");
}
if native_tls.is_some() {
masked_fields.push("native-tls");
}
if offline.is_some() {
masked_fields.push("offline");
}
if no_cache.is_some() {
masked_fields.push("no-cache");
}
if cache_dir.is_some() {
masked_fields.push("cache-dir");
}
if preview.is_some() {
masked_fields.push("preview");
}
if python_preference.is_some() {
masked_fields.push("python-preference");
}
if python_downloads.is_some() {
masked_fields.push("python-downloads");
}
if concurrent_downloads.is_some() {
masked_fields.push("concurrent-downloads");
}
if concurrent_builds.is_some() {
masked_fields.push("concurrent-builds");
}
if concurrent_installs.is_some() {
masked_fields.push("concurrent-installs");
}
if allow_insecure_host.is_some() {
masked_fields.push("allow-insecure-host");
}
if index.is_some() {
masked_fields.push("index");
}
if index_url.is_some() {
masked_fields.push("index-url");
}
if extra_index_url.is_some() {
masked_fields.push("extra-index-url");
}
if no_index.is_some() {
masked_fields.push("no-index");
}
if find_links.is_some() {
masked_fields.push("find-links");
}
if index_strategy.is_some() {
masked_fields.push("index-strategy");
}
if keyring_provider.is_some() {
masked_fields.push("keyring-provider");
}
if resolution.is_some() {
masked_fields.push("resolution");
}
if prerelease.is_some() {
masked_fields.push("prerelease");
}
if fork_strategy.is_some() {
masked_fields.push("fork-strategy");
}
if dependency_metadata.is_some() {
masked_fields.push("dependency-metadata");
}
if config_settings.is_some() {
masked_fields.push("config-settings");
}
if config_settings_package.is_some() {
masked_fields.push("config-settings-package");
}
if no_build_isolation.is_some() {
masked_fields.push("no-build-isolation");
}
if no_build_isolation_package.is_some() {
masked_fields.push("no-build-isolation-package");
}
if extra_build_dependencies.is_some() {
masked_fields.push("extra-build-dependencies");
}
if extra_build_variables.is_some() {
masked_fields.push("extra-build-variables");
}
if exclude_newer.is_some() {
masked_fields.push("exclude-newer");
}
if exclude_newer_package.is_some() {
masked_fields.push("exclude-newer-package");
}
if link_mode.is_some() {
masked_fields.push("link-mode");
}
if compile_bytecode.is_some() {
masked_fields.push("compile-bytecode");
}
if no_sources.is_some() {
masked_fields.push("no-sources");
}
if upgrade.is_some() {
masked_fields.push("upgrade");
}
if upgrade_package.is_some() {
masked_fields.push("upgrade-package");
}
if reinstall.is_some() {
masked_fields.push("reinstall");
}
if reinstall_package.is_some() {
masked_fields.push("reinstall-package");
}
if no_build.is_some() {
masked_fields.push("no-build");
}
if no_build_package.is_some() {
masked_fields.push("no-build-package");
}
if no_binary.is_some() {
masked_fields.push("no-binary");
}
if no_binary_package.is_some() {
masked_fields.push("no-binary-package");
}
if torch_backend.is_some() {
masked_fields.push("torch-backend");
}
if python_install_mirror.is_some() {
masked_fields.push("python-install-mirror");
}
if pypy_install_mirror.is_some() {
masked_fields.push("pypy-install-mirror");
}
if python_downloads_json_url.is_some() {
masked_fields.push("python-downloads-json-url");
}
if publish_url.is_some() {
masked_fields.push("publish-url");
}
if trusted_publishing.is_some() {
masked_fields.push("trusted-publishing");
}
if check_url.is_some() {
masked_fields.push("check-url");
}
if add_bounds.is_some() {
masked_fields.push("add-bounds");
}
if pip.is_some() {
masked_fields.push("pip");
}
if cache_keys.is_some() {
masked_fields.push("cache_keys");
}
if override_dependencies.is_some() {
masked_fields.push("override-dependencies");
}
if exclude_dependencies.is_some() {
masked_fields.push("exclude-dependencies");
}
if constraint_dependencies.is_some() {
masked_fields.push("constraint-dependencies");
}
if build_constraint_dependencies.is_some() {
masked_fields.push("build-constraint-dependencies");
}
if !masked_fields.is_empty() {
let field_listing = masked_fields.join("\n- ");
warn_user!(
"Found both a `uv.toml` file and a `[tool.uv]` section in an adjacent `pyproject.toml`. The following fields from `[tool.uv]` will be ignored in favor of the `uv.toml` file:\n- {}",
field_listing,
);
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Index(#[from] uv_distribution_types::IndexUrlError),
#[error("Failed to parse: `{}`", _0.user_display())]
PyprojectToml(PathBuf, #[source] Box<toml::de::Error>),
#[error("Failed to parse: `{}`", _0.user_display())]
UvToml(PathBuf, #[source] Box<toml::de::Error>),
#[error("Failed to parse: `{}`. The `{}` field is not allowed in a `uv.toml` file. `{}` is only applicable in the context of a project, and should be placed in a `pyproject.toml` file instead.", _0.user_display(), _1, _1
)]
PyprojectOnlyField(PathBuf, &'static str),
#[error("Failed to parse environment variable `{name}` with invalid value `{value}`: {err}")]
InvalidEnvironmentVariable {
name: String,
value: String,
err: String,
},
}
#[derive(Copy, Clone, Debug)]
pub struct Concurrency {
pub downloads: Option<NonZeroUsize>,
pub builds: Option<NonZeroUsize>,
pub installs: Option<NonZeroUsize>,
}
/// Options loaded from environment variables.
///
/// This is currently a subset of all respected environment variables, most are parsed via Clap at
/// the CLI level, however there are limited semantics in that context.
#[derive(Debug, Clone)]
pub struct EnvironmentOptions {
pub skip_wheel_filename_check: Option<bool>,
pub hide_build_output: Option<bool>,
pub python_install_bin: Option<bool>,
pub python_install_registry: Option<bool>,
pub install_mirrors: PythonInstallMirrors,
pub log_context: Option<bool>,
pub lfs: Option<bool>,
pub http_timeout: Duration,
pub http_retries: u32,
pub upload_http_timeout: Duration,
pub concurrency: Concurrency,
#[cfg(feature = "tracing-durations-export")]
pub tracing_durations_file: Option<PathBuf>,
}
impl EnvironmentOptions {
/// Create a new [`EnvironmentOptions`] from environment variables.
pub fn new() -> Result<Self, Error> {
// Timeout options, matching https://doc.rust-lang.org/nightly/cargo/reference/config.html#httptimeout
// `UV_REQUEST_TIMEOUT` is provided for backwards compatibility with v0.1.6
let http_timeout = parse_integer_environment_variable(EnvVars::UV_HTTP_TIMEOUT)?
.or(parse_integer_environment_variable(
EnvVars::UV_REQUEST_TIMEOUT,
)?)
.or(parse_integer_environment_variable(EnvVars::HTTP_TIMEOUT)?)
.map(Duration::from_secs);
Ok(Self {
skip_wheel_filename_check: parse_boolish_environment_variable(
EnvVars::UV_SKIP_WHEEL_FILENAME_CHECK,
)?,
hide_build_output: parse_boolish_environment_variable(EnvVars::UV_HIDE_BUILD_OUTPUT)?,
python_install_bin: parse_boolish_environment_variable(EnvVars::UV_PYTHON_INSTALL_BIN)?,
python_install_registry: parse_boolish_environment_variable(
EnvVars::UV_PYTHON_INSTALL_REGISTRY,
)?,
concurrency: Concurrency {
downloads: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_DOWNLOADS)?,
builds: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_BUILDS)?,
installs: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_INSTALLS)?,
},
install_mirrors: PythonInstallMirrors {
python_install_mirror: parse_string_environment_variable(
EnvVars::UV_PYTHON_INSTALL_MIRROR,
)?,
pypy_install_mirror: parse_string_environment_variable(
EnvVars::UV_PYPY_INSTALL_MIRROR,
)?,
python_downloads_json_url: parse_string_environment_variable(
EnvVars::UV_PYTHON_DOWNLOADS_JSON_URL,
)?,
},
log_context: parse_boolish_environment_variable(EnvVars::UV_LOG_CONTEXT)?,
lfs: parse_boolish_environment_variable(EnvVars::UV_GIT_LFS)?,
upload_http_timeout: parse_integer_environment_variable(
EnvVars::UV_UPLOAD_HTTP_TIMEOUT,
)?
.map(Duration::from_secs)
.or(http_timeout)
.unwrap_or(Duration::from_secs(15 * 60)),
http_timeout: http_timeout.unwrap_or(Duration::from_secs(30)),
http_retries: parse_integer_environment_variable(EnvVars::UV_HTTP_RETRIES)?
.unwrap_or(uv_client::DEFAULT_RETRIES),
#[cfg(feature = "tracing-durations-export")]
tracing_durations_file: parse_path_environment_variable(
EnvVars::TRACING_DURATIONS_FILE,
),
})
}
}
/// Parse a boolean environment variable.
///
/// Adapted from Clap's `BoolishValueParser` which is dual licensed under the MIT and Apache-2.0.
fn parse_boolish_environment_variable(name: &'static str) -> Result<Option<bool>, Error> {
// See `clap_builder/src/util/str_to_bool.rs`
// We want to match Clap's accepted values
// True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
// False values are `n`, `no`, `f`, `false`, `off`, and `0`.
const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
// Converts a string literal representation of truth to true or false.
//
// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
//
// Any other value will be considered as `true`.
fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
let pat: &str = &val.as_ref().to_lowercase();
if TRUE_LITERALS.contains(&pat) {
Some(true)
} else if FALSE_LITERALS.contains(&pat) {
Some(false)
} else {
None
}
}
let Some(value) = std::env::var_os(name) else {
return Ok(None);
};
let Some(value) = value.to_str() else {
return Err(Error::InvalidEnvironmentVariable {
name: name.to_string(),
value: value.to_string_lossy().to_string(),
err: "expected a valid UTF-8 string".to_string(),
});
};
let Some(value) = str_to_bool(value) else {
return Err(Error::InvalidEnvironmentVariable {
name: name.to_string(),
value: value.to_string(),
err: "expected a boolish value".to_string(),
});
};
Ok(Some(value))
}
/// Parse a string environment variable.
fn parse_string_environment_variable(name: &'static str) -> Result<Option<String>, Error> {
match std::env::var(name) {
Ok(v) => {
if v.is_empty() {
Ok(None)
} else {
Ok(Some(v))
}
}
Err(e) => match e {
std::env::VarError::NotPresent => Ok(None),
std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
name: name.to_string(),
value: err.to_string_lossy().to_string(),
err: "expected a valid UTF-8 string".to_string(),
}),
},
}
}
fn parse_integer_environment_variable<T>(name: &'static str) -> Result<Option<T>, Error>
where
T: std::str::FromStr + Copy,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
let value = match std::env::var(name) {
Ok(v) => v,
Err(e) => {
return match e {
std::env::VarError::NotPresent => Ok(None),
std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
name: name.to_string(),
value: err.to_string_lossy().to_string(),
err: "expected a valid UTF-8 string".to_string(),
}),
};
}
};
if value.is_empty() {
return Ok(None);
}
match value.parse::<T>() {
Ok(v) => Ok(Some(v)),
Err(err) => Err(Error::InvalidEnvironmentVariable {
name: name.to_string(),
value,
err: err.to_string(),
}),
}
}
#[cfg(feature = "tracing-durations-export")]
/// Parse a path environment variable.
fn parse_path_environment_variable(name: &'static str) -> Option<PathBuf> {
let value = std::env::var_os(name)?;
if value.is_empty() {
return None;
}
Some(PathBuf::from(value))
}
/// Populate the [`EnvironmentFlags`] from the given [`EnvironmentOptions`].
impl From<&EnvironmentOptions> for EnvironmentFlags {
fn from(options: &EnvironmentOptions) -> Self {
let mut flags = Self::empty();
if options.skip_wheel_filename_check == Some(true) {
flags.insert(Self::SKIP_WHEEL_FILENAME_CHECK);
}
if options.hide_build_output == Some(true) {
flags.insert(Self::HIDE_BUILD_OUTPUT);
}
flags
}
}
| 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-settings/src/combine.rs | crates/uv-settings/src/combine.rs | use std::path::PathBuf;
use std::{collections::BTreeMap, num::NonZeroUsize};
use url::Url;
use uv_configuration::{
BuildIsolation, ExportFormat, IndexStrategy, KeyringProviderType, Reinstall, RequiredVersion,
TargetTriple, TrustedPublishing, Upgrade,
};
use uv_distribution_types::{
ConfigSettings, ExtraBuildVariables, Index, IndexUrl, PackageConfigSettings, PipExtraIndex,
PipFindLinks, PipIndex,
};
use uv_install_wheel::LinkMode;
use uv_pypi_types::{SchemaConflicts, SupportedEnvironments};
use uv_python::{PythonDownloads, PythonPreference, PythonVersion};
use uv_redacted::DisplaySafeUrl;
use uv_resolver::{
AnnotationStyle, ExcludeNewer, ExcludeNewerPackage, ExcludeNewerValue, ForkStrategy,
PrereleaseMode, ResolutionMode,
};
use uv_torch::TorchMode;
use uv_workspace::pyproject::ExtraBuildDependencies;
use uv_workspace::pyproject_mut::AddBoundsKind;
use crate::{FilesystemOptions, Options, PipOptions};
pub trait Combine {
/// Combine two values, preferring the values in `self`.
///
/// The logic should follow that of Cargo's `config.toml`:
///
/// > If a key is specified in multiple config files, the values will get merged together.
/// > Numbers, strings, and booleans will use the value in the deeper config directory taking
/// > precedence over ancestor directories, where the home directory is the lowest priority.
/// > Arrays will be joined together with higher precedence items being placed later in the
/// > merged array.
///
/// ...with one exception: we place items with higher precedence earlier in the merged array.
#[must_use]
fn combine(self, other: Self) -> Self;
}
impl Combine for Option<FilesystemOptions> {
/// Combine the options used in two [`FilesystemOptions`]s. Retains the root of `self`.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(FilesystemOptions(
a.into_options().combine(b.into_options()),
)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<Options> {
/// Combine the options used in two [`Options`]s. Retains the root of `self`.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<PipOptions> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
macro_rules! impl_combine_or {
($name:ident) => {
impl Combine for Option<$name> {
fn combine(self, other: Option<$name>) -> Option<$name> {
self.or(other)
}
}
};
}
impl_combine_or!(AddBoundsKind);
impl_combine_or!(AnnotationStyle);
impl_combine_or!(ExcludeNewer);
impl_combine_or!(ExcludeNewerValue);
impl_combine_or!(ExportFormat);
impl_combine_or!(ForkStrategy);
impl_combine_or!(Index);
impl_combine_or!(IndexStrategy);
impl_combine_or!(IndexUrl);
impl_combine_or!(KeyringProviderType);
impl_combine_or!(LinkMode);
impl_combine_or!(DisplaySafeUrl);
impl_combine_or!(NonZeroUsize);
impl_combine_or!(PathBuf);
impl_combine_or!(PipExtraIndex);
impl_combine_or!(PipFindLinks);
impl_combine_or!(PipIndex);
impl_combine_or!(PrereleaseMode);
impl_combine_or!(PythonDownloads);
impl_combine_or!(PythonPreference);
impl_combine_or!(PythonVersion);
impl_combine_or!(RequiredVersion);
impl_combine_or!(ResolutionMode);
impl_combine_or!(SchemaConflicts);
impl_combine_or!(String);
impl_combine_or!(SupportedEnvironments);
impl_combine_or!(TargetTriple);
impl_combine_or!(TorchMode);
impl_combine_or!(TrustedPublishing);
impl_combine_or!(Url);
impl_combine_or!(bool);
impl<T> Combine for Option<Vec<T>> {
/// Combine two vectors by extending the vector in `self` with the vector in `other`, if they're
/// both `Some`.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(mut a), Some(b)) => {
a.extend(b);
Some(a)
}
(a, b) => a.or(b),
}
}
}
impl<K: Ord, T> Combine for Option<BTreeMap<K, Vec<T>>> {
/// Combine two maps of vecs by combining their vecs
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(mut a), Some(b)) => {
for (key, value) in b {
a.entry(key).or_default().extend(value);
}
Some(a)
}
(a, b) => a.or(b),
}
}
}
impl Combine for Option<ExcludeNewerPackage> {
/// Combine two [`ExcludeNewerPackage`] instances by merging them, with the values in `self` taking precedence.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(mut a), Some(b)) => {
// Extend with values from b, but a takes precedence (we don't overwrite existing keys)
for (key, value) in b {
a.entry(key).or_insert(value);
}
Some(a)
}
(a, b) => a.or(b),
}
}
}
impl Combine for Option<ConfigSettings> {
/// Combine two maps by merging the map in `self` with the map in `other`, if they're both
/// `Some`.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.merge(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<PackageConfigSettings> {
/// Combine two maps by merging the map in `self` with the map in `other`, if they're both
/// `Some`.
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.merge(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<Upgrade> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<Reinstall> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for Option<BuildIsolation> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for serde::de::IgnoredAny {
fn combine(self, _other: Self) -> Self {
self
}
}
impl Combine for Option<serde::de::IgnoredAny> {
fn combine(self, _other: Self) -> Self {
self
}
}
impl Combine for ExcludeNewer {
fn combine(mut self, other: Self) -> Self {
self.global = self.global.combine(other.global);
if !other.package.is_empty() {
if self.package.is_empty() {
self.package = other.package;
} else {
// Merge package-specific timestamps, with self taking precedence
for (pkg, timestamp) in &other.package {
self.package.entry(pkg.clone()).or_insert(timestamp.clone());
}
}
}
self
}
}
impl Combine for ExtraBuildDependencies {
fn combine(mut self, other: Self) -> Self {
for (key, value) in other {
match self.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
// Combine the vecs, with self taking precedence
let existing = entry.get_mut();
existing.extend(value);
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
self
}
}
impl Combine for Option<ExtraBuildDependencies> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
impl Combine for ExtraBuildVariables {
fn combine(mut self, other: Self) -> Self {
for (key, value) in other {
match self.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
// Combine the maps, with self taking precedence
let existing = entry.get_mut();
for (k, v) in value {
existing.entry(k).or_insert(v);
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
self
}
}
impl Combine for Option<ExtraBuildVariables> {
fn combine(self, other: Self) -> Self {
match (self, other) {
(Some(a), Some(b)) => Some(a.combine(b)),
(a, b) => a.or(b),
}
}
}
| 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-pep440/src/lib.rs | crates/uv-pep440/src/lib.rs | //! A library for python version numbers and specifiers, implementing
//! [PEP 440](https://peps.python.org/pep-0440)
//!
//! PEP 440 has a lot of unintuitive features, including:
//!
//! * An epoch that you can prefix the version which, e.g. `1!1.2.3`. Lower epoch always means lower
//! version (`1.0 <=2!0.1`)
//! * post versions, which can be attached to both stable releases and pre-releases
//! * dev versions, which can be attached to both table releases and pre-releases. When attached to a
//! pre-release the dev version is ordered just below the normal pre-release, however when attached
//! to a stable version, the dev version is sorted before a pre-releases
//! * pre-release handling is a mess: "Pre-releases of any kind, including developmental releases,
//! are implicitly excluded from all version specifiers, unless they are already present on the
//! system, explicitly requested by the user, or if the only available version that satisfies
//! the version specifier is a pre-release.". This means that we can't say whether a specifier
//! matches without also looking at the environment
//! * pre-release vs. pre-release incl. dev is fuzzy
//! * local versions on top of all the others, which are added with a + and have implicitly typed
//! string and number segments
//! * no semver-caret (`^`), but a pseudo-semver tilde (`~=`)
//! * ordering contradicts matching: We have e.g. `1.0+local > 1.0` when sorting,
//! but `==1.0` matches `1.0+local`. While the ordering of versions itself is a total order
//! the version matching needs to catch all sorts of special cases
#![warn(missing_docs)]
#[cfg(feature = "version-ranges")]
pub use version_ranges::{
LowerBound, UpperBound, release_specifier_to_range, release_specifiers_to_ranges,
};
pub use {
version::{
BumpCommand, LocalSegment, LocalVersion, LocalVersionSlice, MIN_VERSION, Operator,
OperatorParseError, Prerelease, PrereleaseKind, Version, VersionParseError, VersionPattern,
VersionPatternParseError,
},
version_specifier::{
TildeVersionSpecifier, VersionSpecifier, VersionSpecifierBuildError, VersionSpecifiers,
VersionSpecifiersParseError,
},
};
mod version;
mod version_specifier;
#[cfg(feature = "version-ranges")]
mod version_ranges;
#[cfg(test)]
mod tests {
use super::{Version, VersionSpecifier, VersionSpecifiers};
use std::str::FromStr;
#[test]
fn test_version() {
let version = Version::from_str("1.19").unwrap();
let version_specifier = VersionSpecifier::from_str("== 1.*").unwrap();
assert!(version_specifier.contains(&version));
let version_specifiers = VersionSpecifiers::from_str(">=1.16, <2.0").unwrap();
assert!(version_specifiers.contains(&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-pep440/src/version.rs | crates/uv-pep440/src/version.rs | use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use std::fmt::Formatter;
use std::num::NonZero;
use std::ops::Deref;
use std::sync::LazyLock;
use std::{
borrow::Borrow,
cmp::Ordering,
hash::{Hash, Hasher},
str::FromStr,
sync::Arc,
};
use uv_cache_key::{CacheKey, CacheKeyHasher};
/// One of `~=` `==` `!=` `<=` `>=` `<` `>` `===`
#[derive(Eq, Ord, PartialEq, PartialOrd, Debug, Hash, Clone, Copy)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
pub enum Operator {
/// `== 1.2.3`
Equal,
/// `== 1.2.*`
EqualStar,
/// `===` (discouraged)
///
/// <https://peps.python.org/pep-0440/#arbitrary-equality>
///
/// "Use of this operator is heavily discouraged and tooling MAY display a warning when it is used"
// clippy doesn't like this: #[deprecated = "Use of this operator is heavily discouraged"]
ExactEqual,
/// `!= 1.2.3`
NotEqual,
/// `!= 1.2.*`
NotEqualStar,
/// `~=`
///
/// Invariant: With `~=`, there are always at least 2 release segments.
TildeEqual,
/// `<`
LessThan,
/// `<=`
LessThanEqual,
/// `>`
GreaterThan,
/// `>=`
GreaterThanEqual,
}
impl Operator {
/// Negates this operator, if a negation exists, so that it has the
/// opposite meaning.
///
/// This returns a negated operator in every case except for the `~=`
/// operator. In that case, `None` is returned and callers may need to
/// handle its negation at a higher level. (For example, if it's negated
/// in the context of a marker expression, then the "compatible" version
/// constraint can be split into its component parts and turned into a
/// disjunction of the negation of each of those parts.)
///
/// Note that this routine is not reversible in all cases. For example
/// `Operator::ExactEqual` negates to `Operator::NotEqual`, and
/// `Operator::NotEqual` in turn negates to `Operator::Equal`.
pub fn negate(self) -> Option<Self> {
Some(match self {
Self::Equal => Self::NotEqual,
Self::EqualStar => Self::NotEqualStar,
Self::ExactEqual => Self::NotEqual,
Self::NotEqual => Self::Equal,
Self::NotEqualStar => Self::EqualStar,
Self::TildeEqual => return None,
Self::LessThan => Self::GreaterThanEqual,
Self::LessThanEqual => Self::GreaterThan,
Self::GreaterThan => Self::LessThanEqual,
Self::GreaterThanEqual => Self::LessThan,
})
}
/// Returns true if and only if this operator can be used in a version
/// specifier with a version containing a non-empty local segment.
///
/// Specifically, this comes from the "Local version identifiers are
/// NOT permitted in this version specifier." phrasing in the version
/// specifiers [spec].
///
/// [spec]: https://packaging.python.org/en/latest/specifications/version-specifiers/
pub(crate) fn is_local_compatible(self) -> bool {
!matches!(
self,
Self::GreaterThan
| Self::GreaterThanEqual
| Self::LessThan
| Self::LessThanEqual
| Self::TildeEqual
| Self::EqualStar
| Self::NotEqualStar
)
}
/// Returns the wildcard version of this operator, if appropriate.
///
/// This returns `None` when this operator doesn't have an analogous
/// wildcard operator.
pub(crate) fn to_star(self) -> Option<Self> {
match self {
Self::Equal => Some(Self::EqualStar),
Self::NotEqual => Some(Self::NotEqualStar),
_ => None,
}
}
/// Returns `true` if this operator represents a wildcard.
pub fn is_star(self) -> bool {
matches!(self, Self::EqualStar | Self::NotEqualStar)
}
/// Returns the string representation of this operator.
pub fn as_str(self) -> &'static str {
match self {
Self::Equal => "==",
// Beware, this doesn't print the star
Self::EqualStar => "==",
#[allow(deprecated)]
Self::ExactEqual => "===",
Self::NotEqual => "!=",
Self::NotEqualStar => "!=",
Self::TildeEqual => "~=",
Self::LessThan => "<",
Self::LessThanEqual => "<=",
Self::GreaterThan => ">",
Self::GreaterThanEqual => ">=",
}
}
}
impl FromStr for Operator {
type Err = OperatorParseError;
/// Notably, this does not know about star versions, it just assumes the base operator
fn from_str(s: &str) -> Result<Self, Self::Err> {
let operator = match s {
"==" => Self::Equal,
"===" => {
#[cfg(feature = "tracing")]
{
tracing::warn!("Using arbitrary equality (`===`) is discouraged");
}
#[allow(deprecated)]
Self::ExactEqual
}
"!=" => Self::NotEqual,
"~=" => Self::TildeEqual,
"<" => Self::LessThan,
"<=" => Self::LessThanEqual,
">" => Self::GreaterThan,
">=" => Self::GreaterThanEqual,
other => {
return Err(OperatorParseError {
got: other.to_string(),
});
}
};
Ok(operator)
}
}
impl std::fmt::Display for Operator {
/// Note the `EqualStar` is also `==`.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let operator = self.as_str();
write!(f, "{operator}")
}
}
/// An error that occurs when parsing an invalid version specifier operator.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperatorParseError {
pub(crate) got: String,
}
impl std::error::Error for OperatorParseError {}
impl std::fmt::Display for OperatorParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"no such comparison operator {:?}, must be one of ~= == != <= >= < > ===",
self.got
)
}
}
// NOTE: I did a little bit of experimentation to determine what most version
// numbers actually look like. The idea here is that if we know what most look
// like, then we can optimize our representation for the common case, while
// falling back to something more complete for any cases that fall outside of
// that.
//
// The experiment downloaded PyPI's distribution metadata from Google BigQuery,
// and then counted the number of versions with various qualities:
//
// total: 11264078
// release counts:
// 01: 51204 (0.45%)
// 02: 754520 (6.70%)
// 03: 9757602 (86.63%)
// 04: 527403 (4.68%)
// 05: 77994 (0.69%)
// 06: 91346 (0.81%)
// 07: 1421 (0.01%)
// 08: 205 (0.00%)
// 09: 72 (0.00%)
// 10: 2297 (0.02%)
// 11: 5 (0.00%)
// 12: 2 (0.00%)
// 13: 4 (0.00%)
// 20: 2 (0.00%)
// 39: 1 (0.00%)
// JUST release counts:
// 01: 48297 (0.43%)
// 02: 604692 (5.37%)
// 03: 8460917 (75.11%)
// 04: 465354 (4.13%)
// 05: 49293 (0.44%)
// 06: 25909 (0.23%)
// 07: 1413 (0.01%)
// 08: 192 (0.00%)
// 09: 72 (0.00%)
// 10: 2292 (0.02%)
// 11: 5 (0.00%)
// 12: 2 (0.00%)
// 13: 4 (0.00%)
// 20: 2 (0.00%)
// 39: 1 (0.00%)
// non-zero epochs: 1902 (0.02%)
// pre-releases: 752184 (6.68%)
// post-releases: 134383 (1.19%)
// dev-releases: 765099 (6.79%)
// locals: 1 (0.00%)
// fitsu8: 10388430 (92.23%)
// sweetspot: 10236089 (90.87%)
//
// The "JUST release counts" corresponds to versions that only have a release
// component and nothing else. The "fitsu8" property indicates that all numbers
// (except for local numeric segments) fit into `u8`. The "sweetspot" property
// consists of any version number with no local part, 4 or fewer parts in the
// release version and *all* numbers fit into a u8.
//
// This somewhat confirms what one might expect: the vast majority of versions
// (75%) are precisely in the format of `x.y.z`. That is, a version with only a
// release version of 3 components.
//
// ---AG
/// A version number such as `1.2.3` or `4!5.6.7-a8.post9.dev0`.
///
/// Beware that the sorting implemented with [Ord] and [Eq] is not consistent with the operators
/// from PEP 440, i.e. compare two versions in rust with `>` gives a different result than a
/// `VersionSpecifier` with `>` as operator.
///
/// Parse with [`Version::from_str`]:
///
/// ```rust
/// use std::str::FromStr;
/// use uv_pep440::Version;
///
/// let version = Version::from_str("1.19").unwrap();
/// ```
#[derive(Clone)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
pub struct Version {
inner: VersionInner,
}
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
enum VersionInner {
Small { small: VersionSmall },
Full { full: Arc<VersionFull> },
}
impl Version {
/// Create a new version from an iterator of segments in the release part
/// of a version.
///
/// # Panics
///
/// When the iterator yields no elements.
#[inline]
pub fn new<I, R>(release_numbers: I) -> Self
where
I: IntoIterator<Item = R>,
R: Borrow<u64>,
{
Self {
inner: VersionInner::Small {
small: VersionSmall::new(),
},
}
.with_release(release_numbers)
}
/// Whether this is an alpha/beta/rc or dev version
#[inline]
pub fn any_prerelease(&self) -> bool {
self.is_pre() || self.is_dev()
}
/// Whether this is a stable version (i.e., _not_ an alpha/beta/rc or dev version)
#[inline]
pub fn is_stable(&self) -> bool {
!self.is_pre() && !self.is_dev()
}
/// Whether this is an alpha/beta/rc version
#[inline]
pub fn is_pre(&self) -> bool {
self.pre().is_some()
}
/// Whether this is a dev version
#[inline]
pub fn is_dev(&self) -> bool {
self.dev().is_some()
}
/// Whether this is a post version
#[inline]
pub fn is_post(&self) -> bool {
self.post().is_some()
}
/// Whether this is a local version (e.g. `1.2.3+localsuffixesareweird`)
///
/// When true, it is guaranteed that the slice returned by
/// [`Version::local`] is non-empty.
#[inline]
pub fn is_local(&self) -> bool {
!self.local().is_empty()
}
/// Returns the epoch of this version.
#[inline]
pub fn epoch(&self) -> u64 {
match self.inner {
VersionInner::Small { ref small } => small.epoch(),
VersionInner::Full { ref full } => full.epoch,
}
}
/// Returns the release number part of the version.
#[inline]
pub fn release(&self) -> Release<'_> {
let inner = match &self.inner {
VersionInner::Small { small } => {
// Parse out the version digits.
// * Bytes 6 and 7 correspond to the first release segment as a `u16`.
// * Bytes 5, 4 and 3 correspond to the second, third and fourth release
// segments, respectively.
match small.len {
0 => ReleaseInner::Small0([]),
1 => ReleaseInner::Small1([(small.repr >> 0o60) & 0xFFFF]),
2 => ReleaseInner::Small2([
(small.repr >> 0o60) & 0xFFFF,
(small.repr >> 0o50) & 0xFF,
]),
3 => ReleaseInner::Small3([
(small.repr >> 0o60) & 0xFFFF,
(small.repr >> 0o50) & 0xFF,
(small.repr >> 0o40) & 0xFF,
]),
4 => ReleaseInner::Small4([
(small.repr >> 0o60) & 0xFFFF,
(small.repr >> 0o50) & 0xFF,
(small.repr >> 0o40) & 0xFF,
(small.repr >> 0o30) & 0xFF,
]),
_ => unreachable!("{}", small.len),
}
}
VersionInner::Full { full } => ReleaseInner::Full(&full.release),
};
Release { inner }
}
/// Returns the pre-release part of this version, if it exists.
#[inline]
pub fn pre(&self) -> Option<Prerelease> {
match self.inner {
VersionInner::Small { ref small } => small.pre(),
VersionInner::Full { ref full } => full.pre,
}
}
/// Returns the post-release part of this version, if it exists.
#[inline]
pub fn post(&self) -> Option<u64> {
match self.inner {
VersionInner::Small { ref small } => small.post(),
VersionInner::Full { ref full } => full.post,
}
}
/// Returns the dev-release part of this version, if it exists.
#[inline]
pub fn dev(&self) -> Option<u64> {
match self.inner {
VersionInner::Small { ref small } => small.dev(),
VersionInner::Full { ref full } => full.dev,
}
}
/// Returns the local segments in this version, if any exist.
#[inline]
pub fn local(&self) -> LocalVersionSlice<'_> {
match self.inner {
VersionInner::Small { ref small } => small.local_slice(),
VersionInner::Full { ref full } => full.local.as_slice(),
}
}
/// Returns the min-release part of this version, if it exists.
///
/// The "min" component is internal-only, and does not exist in PEP 440.
/// The version `1.0min0` is smaller than all other `1.0` versions,
/// like `1.0a1`, `1.0dev0`, etc.
#[inline]
pub fn min(&self) -> Option<u64> {
match self.inner {
VersionInner::Small { ref small } => small.min(),
VersionInner::Full { ref full } => full.min,
}
}
/// Returns the max-release part of this version, if it exists.
///
/// The "max" component is internal-only, and does not exist in PEP 440.
/// The version `1.0max0` is larger than all other `1.0` versions,
/// like `1.0.post1`, `1.0+local`, etc.
#[inline]
pub fn max(&self) -> Option<u64> {
match self.inner {
VersionInner::Small { ref small } => small.max(),
VersionInner::Full { ref full } => full.max,
}
}
/// Set the release numbers and return the updated version.
///
/// Usually one can just use `Version::new` to create a new version with
/// the updated release numbers, but this is useful when one wants to
/// preserve the other components of a version number while only changing
/// the release numbers.
///
/// # Panics
///
/// When the iterator yields no elements.
#[inline]
#[must_use]
pub fn with_release<I, R>(mut self, release_numbers: I) -> Self
where
I: IntoIterator<Item = R>,
R: Borrow<u64>,
{
self.clear_release();
for n in release_numbers {
self.push_release(*n.borrow());
}
assert!(
!self.release().is_empty(),
"release must have non-zero size"
);
self
}
/// Push the given release number into this version. It will become the
/// last number in the release component.
#[inline]
fn push_release(&mut self, n: u64) {
if let VersionInner::Small { small } = &mut self.inner {
if small.push_release(n) {
return;
}
}
self.make_full().release.push(n);
}
/// Clears the release component of this version so that it has no numbers.
///
/// Generally speaking, this empty state should not be exposed to callers
/// since all versions should have at least one release number.
#[inline]
fn clear_release(&mut self) {
match &mut self.inner {
VersionInner::Small { small } => small.clear_release(),
VersionInner::Full { full } => {
Arc::make_mut(full).release.clear();
}
}
}
/// Set the epoch and return the updated version.
#[inline]
#[must_use]
pub fn with_epoch(mut self, value: u64) -> Self {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_epoch(value) {
return self;
}
}
self.make_full().epoch = value;
self
}
/// Set the pre-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_pre(mut self, value: Option<Prerelease>) -> Self {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_pre(value) {
return self;
}
}
self.make_full().pre = value;
self
}
/// Set the post-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_post(mut self, value: Option<u64>) -> Self {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_post(value) {
return self;
}
}
self.make_full().post = value;
self
}
/// Set the dev-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_dev(mut self, value: Option<u64>) -> Self {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_dev(value) {
return self;
}
}
self.make_full().dev = value;
self
}
/// Set the local segments and return the updated version.
#[inline]
#[must_use]
pub fn with_local_segments(mut self, value: Vec<LocalSegment>) -> Self {
if value.is_empty() {
self.without_local()
} else {
self.make_full().local = LocalVersion::Segments(value);
self
}
}
/// Set the local version and return the updated version.
#[inline]
#[must_use]
pub fn with_local(mut self, value: LocalVersion) -> Self {
match value {
LocalVersion::Segments(segments) => self.with_local_segments(segments),
LocalVersion::Max => {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_local(LocalVersion::Max) {
return self;
}
}
self.make_full().local = value;
self
}
}
}
/// For PEP 440 specifier matching: "Except where specifically noted below,
/// local version identifiers MUST NOT be permitted in version specifiers,
/// and local version labels MUST be ignored entirely when checking if
/// candidate versions match a given version specifier."
#[inline]
#[must_use]
pub fn without_local(mut self) -> Self {
if let VersionInner::Small { small } = &mut self.inner {
if small.set_local(LocalVersion::empty()) {
return self;
}
}
self.make_full().local = LocalVersion::empty();
self
}
/// Return the version with any segments apart from the release removed.
#[inline]
#[must_use]
pub fn only_release(&self) -> Self {
Self::new(self.release().iter().copied())
}
/// Return the version with any segments apart from the minor version of the release removed.
#[inline]
#[must_use]
pub fn only_minor_release(&self) -> Self {
Self::new(self.release().iter().take(2).copied())
}
/// Return the version with any segments apart from the release removed, with trailing zeroes
/// trimmed.
#[inline]
#[must_use]
pub fn only_release_trimmed(&self) -> Self {
if let Some(last_non_zero) = self.release().iter().rposition(|segment| *segment != 0) {
if last_non_zero == self.release().len() {
// Already trimmed.
self.clone()
} else {
Self::new(self.release().iter().take(last_non_zero + 1).copied())
}
} else {
// `0` is a valid version.
Self::new([0])
}
}
/// Return the version with trailing `.0` release segments removed.
///
/// # Panics
///
/// When the release is all zero segments.
#[inline]
#[must_use]
pub fn without_trailing_zeros(self) -> Self {
let mut release = self.release().to_vec();
while let Some(0) = release.last() {
release.pop();
}
self.with_release(release)
}
/// Various "increment the version" operations
pub fn bump(&mut self, bump: BumpCommand) {
// This code operates on the understanding that the components of a version form
// the following hierarchy:
//
// major > minor > patch > stable > pre > post > dev
//
// Any updates to something earlier in the hierarchy should clear all values lower
// in the hierarchy. So for instance:
//
// if you bump `minor`, then clear: patch, pre, post, dev
// if you bump `pre`, then clear: post, dev
//
// ...and so on.
//
// If you bump a value that doesn't exist, it will be set to "1".
//
// The special "stable" mode has no value, bumping it clears: pre, post, dev.
let full = self.make_full();
match bump {
BumpCommand::BumpRelease { index, value } => {
// Clear all sub-release items
full.pre = None;
full.post = None;
full.dev = None;
// Use `max` here to try to do 0.2 => 0.3 instead of 0.2 => 0.3.0
let old_parts = &full.release;
let len = old_parts.len().max(index + 1);
let new_release_vec = (0..len)
.map(|i| match i.cmp(&index) {
// Everything before the bumped value is preserved (or is an implicit 0)
Ordering::Less => old_parts.get(i).copied().unwrap_or(0),
// This is the value to bump (could be implicit 0)
Ordering::Equal => {
value.unwrap_or_else(|| old_parts.get(i).copied().unwrap_or(0) + 1)
}
// Everything after the bumped value becomes 0
Ordering::Greater => 0,
})
.collect::<Vec<u64>>();
full.release = new_release_vec;
}
BumpCommand::MakeStable => {
// Clear all sub-release items
full.pre = None;
full.post = None;
full.dev = None;
}
BumpCommand::BumpPrerelease { kind, value } => {
// Clear all sub-prerelease items
full.post = None;
full.dev = None;
if let Some(value) = value {
full.pre = Some(Prerelease {
kind,
number: value,
});
} else {
// Either bump the matching kind or set to 1
if let Some(prerelease) = &mut full.pre {
if prerelease.kind == kind {
prerelease.number += 1;
return;
}
}
full.pre = Some(Prerelease { kind, number: 1 });
}
}
BumpCommand::BumpPost { value } => {
// Clear sub-post items
full.dev = None;
if let Some(value) = value {
full.post = Some(value);
} else {
// Either bump or set to 1
if let Some(post) = &mut full.post {
*post += 1;
} else {
full.post = Some(1);
}
}
}
BumpCommand::BumpDev { value } => {
if let Some(value) = value {
full.dev = Some(value);
} else {
// Either bump or set to 1
if let Some(dev) = &mut full.dev {
*dev += 1;
} else {
full.dev = Some(1);
}
}
}
}
}
/// Set the min-release component and return the updated version.
///
/// The "min" component is internal-only, and does not exist in PEP 440.
/// The version `1.0min0` is smaller than all other `1.0` versions,
/// like `1.0a1`, `1.0dev0`, etc.
#[inline]
#[must_use]
pub fn with_min(mut self, value: Option<u64>) -> Self {
debug_assert!(!self.is_pre(), "min is not allowed on pre-release versions");
debug_assert!(!self.is_dev(), "min is not allowed on dev versions");
if let VersionInner::Small { small } = &mut self.inner {
if small.set_min(value) {
return self;
}
}
self.make_full().min = value;
self
}
/// Set the max-release component and return the updated version.
///
/// The "max" component is internal-only, and does not exist in PEP 440.
/// The version `1.0max0` is larger than all other `1.0` versions,
/// like `1.0.post1`, `1.0+local`, etc.
#[inline]
#[must_use]
pub fn with_max(mut self, value: Option<u64>) -> Self {
debug_assert!(
!self.is_post(),
"max is not allowed on post-release versions"
);
debug_assert!(!self.is_dev(), "max is not allowed on dev versions");
if let VersionInner::Small { small } = &mut self.inner {
if small.set_max(value) {
return self;
}
}
self.make_full().max = value;
self
}
/// Convert this version to a "full" representation in-place and return a
/// mutable borrow to the full type.
fn make_full(&mut self) -> &mut VersionFull {
if let VersionInner::Small { ref small } = self.inner {
let full = VersionFull {
epoch: small.epoch(),
release: self.release().to_vec(),
min: small.min(),
max: small.max(),
pre: small.pre(),
post: small.post(),
dev: small.dev(),
local: small.local(),
};
*self = Self {
inner: VersionInner::Full {
full: Arc::new(full),
},
};
}
match &mut self.inner {
VersionInner::Full { full } => Arc::make_mut(full),
VersionInner::Small { .. } => unreachable!(),
}
}
/// Performs a "slow" but complete comparison between two versions.
///
/// This comparison is done using only the public API of a `Version`, and
/// is thus independent of its specific representation. This is useful
/// to use when comparing two versions that aren't *both* the small
/// representation.
#[cold]
#[inline(never)]
fn cmp_slow(&self, other: &Self) -> Ordering {
match self.epoch().cmp(&other.epoch()) {
Ordering::Less => {
return Ordering::Less;
}
Ordering::Equal => {}
Ordering::Greater => {
return Ordering::Greater;
}
}
match compare_release(&self.release(), &other.release()) {
Ordering::Less => {
return Ordering::Less;
}
Ordering::Equal => {}
Ordering::Greater => {
return Ordering::Greater;
}
}
// release is equal, so compare the other parts
sortable_tuple(self).cmp(&sortable_tuple(other))
}
}
impl<'de> Deserialize<'de> for Version {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = Version;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
Version::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl Serialize for Version {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
/// Shows normalized version
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.epoch() != 0 {
write!(f, "{}!", self.epoch())?;
}
let release = self.release();
let mut release_iter = release.iter();
if let Some(first) = release_iter.next() {
write!(f, "{first}")?;
for n in release_iter {
write!(f, ".{n}")?;
}
}
if let Some(Prerelease { kind, number }) = self.pre() {
write!(f, "{kind}{number}")?;
}
if let Some(post) = self.post() {
write!(f, ".post{post}")?;
}
if let Some(dev) = self.dev() {
write!(f, ".dev{dev}")?;
}
if !self.local().is_empty() {
match self.local() {
LocalVersionSlice::Segments(_) => {
write!(f, "+{}", self.local())?;
}
LocalVersionSlice::Max => {
write!(f, "+")?;
}
}
}
Ok(())
}
}
impl std::fmt::Debug for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "\"{self}\"")
}
}
impl PartialEq<Self> for Version {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Version {}
impl Hash for Version {
/// Custom implementation to ignoring trailing zero because `PartialEq` zero pads
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.epoch().hash(state);
// Skip trailing zeros
for i in self.release().iter().rev().skip_while(|x| **x == 0) {
i.hash(state);
}
self.pre().hash(state);
self.dev().hash(state);
self.post().hash(state);
self.local().hash(state);
}
}
impl CacheKey for Version {
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.epoch().cache_key(state);
let release = self.release();
release.len().cache_key(state);
for segment in release.iter() {
segment.cache_key(state);
}
if let Some(pre) = self.pre() {
1u8.cache_key(state);
match pre.kind {
PrereleaseKind::Alpha => 0u8.cache_key(state),
PrereleaseKind::Beta => 1u8.cache_key(state),
PrereleaseKind::Rc => 2u8.cache_key(state),
}
pre.number.cache_key(state);
} else {
0u8.cache_key(state);
}
if let Some(post) = self.post() {
1u8.cache_key(state);
post.cache_key(state);
} else {
0u8.cache_key(state);
}
if let Some(dev) = self.dev() {
1u8.cache_key(state);
dev.cache_key(state);
} else {
0u8.cache_key(state);
}
self.local().cache_key(state);
}
}
impl PartialOrd<Self> for Version {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
| 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-pep440/src/version_ranges.rs | crates/uv-pep440/src/version_ranges.rs | //! Convert [`VersionSpecifiers`] to [`Ranges`].
use std::cmp::Ordering;
use std::collections::Bound;
use std::ops::Deref;
use version_ranges::Ranges;
use crate::{
LocalVersion, LocalVersionSlice, Operator, Prerelease, Version, VersionSpecifier,
VersionSpecifiers,
};
impl From<VersionSpecifiers> for Ranges<Version> {
/// Convert [`VersionSpecifiers`] to a PubGrub-compatible version range, using PEP 440
/// semantics.
fn from(specifiers: VersionSpecifiers) -> Self {
let mut range = Self::full();
for specifier in specifiers {
range = range.intersection(&Self::from(specifier));
}
range
}
}
impl From<VersionSpecifier> for Ranges<Version> {
/// Convert the [`VersionSpecifier`] to a PubGrub-compatible version range, using PEP 440
/// semantics.
fn from(specifier: VersionSpecifier) -> Self {
let VersionSpecifier { operator, version } = specifier;
match operator {
Operator::Equal => match version.local() {
LocalVersionSlice::Segments(&[]) => {
let low = version;
let high = low.clone().with_local(LocalVersion::Max);
Self::between(low, high)
}
LocalVersionSlice::Segments(_) => Self::singleton(version),
LocalVersionSlice::Max => unreachable!(
"found `LocalVersionSlice::Sentinel`, which should be an internal-only value"
),
},
Operator::ExactEqual => Self::singleton(version),
Operator::NotEqual => Self::from(VersionSpecifier {
operator: Operator::Equal,
version,
})
.complement(),
Operator::TildeEqual => {
let release = version.release();
let [rest @ .., last, _] = &*release else {
unreachable!("~= must have at least two segments");
};
let upper = Version::new(rest.iter().chain([&(last + 1)]))
.with_epoch(version.epoch())
.with_dev(Some(0));
Self::from_range_bounds(version..upper)
}
Operator::LessThan => {
// Per PEP 440: "The exclusive ordered comparison <V MUST NOT allow a
// pre-release of the specified version unless the specified version is itself a
// pre-release."
if version.any_prerelease() {
// If V is a pre-release, we allow pre-releases of the same version.
Self::strictly_lower_than(version)
} else if let Some(post) = version.post() {
// If V is a post-release (e.g., `<0.12.0.post2`), we want to:
// - Exclude pre-releases of the base version (e.g., `0.12.0a1`)
// - Include the final release (e.g., `0.12.0`)
// - Include earlier post-releases (e.g., `0.12.0.post1`)
//
// The range is: `(-β, base.min0) βͺ [base, V.post)`
// where `base` is the version without the post-release component.
let base = version.clone().with_post(None);
// Everything below the base version's pre-releases
let lower = Self::strictly_lower_than(base.clone().with_min(Some(0)));
// From base (inclusive) up to but not including V
let upper = Self::from_range_bounds(base..version.with_post(Some(post)));
lower.union(&upper)
} else {
// V is not a pre-release or post-release, so exclude pre-releases of the
// specified version by using a "min" sentinel that sorts before all
// pre-releases.
Self::strictly_lower_than(version.with_min(Some(0)))
}
}
Operator::LessThanEqual => Self::lower_than(version.with_local(LocalVersion::Max)),
Operator::GreaterThan => {
// Per PEP 440: "The exclusive ordered comparison >V MUST NOT allow a post-release of
// the given version unless V itself is a post release."
if let Some(dev) = version.dev() {
Self::higher_than(version.with_dev(Some(dev + 1)))
} else if let Some(post) = version.post() {
Self::higher_than(version.with_post(Some(post + 1)))
} else {
Self::strictly_higher_than(version.with_max(Some(0)))
}
}
Operator::GreaterThanEqual => Self::higher_than(version),
Operator::EqualStar => {
let low = version.with_dev(Some(0));
let mut high = low.clone();
if let Some(post) = high.post() {
high = high.with_post(Some(post + 1));
} else if let Some(pre) = high.pre() {
high = high.with_pre(Some(Prerelease {
kind: pre.kind,
number: pre.number + 1,
}));
} else {
let mut release = high.release().to_vec();
*release.last_mut().unwrap() += 1;
high = high.with_release(release);
}
Self::from_range_bounds(low..high)
}
Operator::NotEqualStar => {
let low = version.with_dev(Some(0));
let mut high = low.clone();
if let Some(post) = high.post() {
high = high.with_post(Some(post + 1));
} else if let Some(pre) = high.pre() {
high = high.with_pre(Some(Prerelease {
kind: pre.kind,
number: pre.number + 1,
}));
} else {
let mut release = high.release().to_vec();
*release.last_mut().unwrap() += 1;
high = high.with_release(release);
}
Self::from_range_bounds(low..high).complement()
}
}
}
}
/// Convert the [`VersionSpecifiers`] to a PubGrub-compatible version range, using release-only
/// semantics.
///
/// Assumes that the range will only be tested against versions that consist solely of release
/// segments (e.g., `3.12.0`, but not `3.12.0b1`).
///
/// These semantics are used for testing Python compatibility (e.g., `requires-python` against
/// the user's installed Python version). In that context, it's more intuitive that `3.13.0b0`
/// is allowed for projects that declare `requires-python = ">=3.13"`.
///
/// See: <https://github.com/pypa/pip/blob/a432c7f4170b9ef798a15f035f5dfdb4cc939f35/src/pip/_internal/resolution/resolvelib/candidates.py#L540>
pub fn release_specifiers_to_ranges(specifiers: VersionSpecifiers) -> Ranges<Version> {
let mut range = Ranges::full();
for specifier in specifiers {
range = range.intersection(&release_specifier_to_range(specifier, false));
}
range
}
/// Convert the [`VersionSpecifier`] to a PubGrub-compatible version range, using release-only
/// semantics.
///
/// Assumes that the range will only be tested against versions that consist solely of release
/// segments (e.g., `3.12.0`, but not `3.12.0b1`).
///
/// These semantics are used for testing Python compatibility (e.g., `requires-python` against
/// the user's installed Python version). In that context, it's more intuitive that `3.13.0b0`
/// is allowed for projects that declare `requires-python = ">3.13"`.
///
/// See: <https://github.com/pypa/pip/blob/a432c7f4170b9ef798a15f035f5dfdb4cc939f35/src/pip/_internal/resolution/resolvelib/candidates.py#L540>
pub fn release_specifier_to_range(specifier: VersionSpecifier, trim: bool) -> Ranges<Version> {
let VersionSpecifier { operator, version } = specifier;
// Note(konsti): We switched strategies to trimmed for the markers, but we don't want to cause
// churn in lockfile requires-python, so we only trim for markers.
let version_trimmed = if trim {
version.only_release_trimmed()
} else {
version.only_release()
};
match operator {
// Trailing zeroes are not semantically relevant.
Operator::Equal => Ranges::singleton(version_trimmed),
Operator::ExactEqual => Ranges::singleton(version_trimmed),
Operator::NotEqual => Ranges::singleton(version_trimmed).complement(),
Operator::LessThan => Ranges::strictly_lower_than(version_trimmed),
Operator::LessThanEqual => Ranges::lower_than(version_trimmed),
Operator::GreaterThan => Ranges::strictly_higher_than(version_trimmed),
Operator::GreaterThanEqual => Ranges::higher_than(version_trimmed),
// Trailing zeroes are semantically relevant.
Operator::TildeEqual => {
let release = version.release();
let [rest @ .., last, _] = &*release else {
unreachable!("~= must have at least two segments");
};
let upper = Version::new(rest.iter().chain([&(last + 1)]));
Ranges::from_range_bounds(version_trimmed..upper)
}
Operator::EqualStar => {
// For (not-)equal-star, trailing zeroes are still before the star.
let low_full = version.only_release();
let high = {
let mut high = low_full.clone();
let mut release = high.release().to_vec();
*release.last_mut().unwrap() += 1;
high = high.with_release(release);
high
};
Ranges::from_range_bounds(version..high)
}
Operator::NotEqualStar => {
// For (not-)equal-star, trailing zeroes are still before the star.
let low_full = version.only_release();
let high = {
let mut high = low_full.clone();
let mut release = high.release().to_vec();
*release.last_mut().unwrap() += 1;
high = high.with_release(release);
high
};
Ranges::from_range_bounds(version..high).complement()
}
}
}
/// A lower bound for a version range.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct LowerBound(pub Bound<Version>);
impl LowerBound {
/// Initialize a [`LowerBound`] with the given bound.
///
/// These bounds use release-only semantics when comparing versions.
pub fn new(bound: Bound<Version>) -> Self {
Self(match bound {
Bound::Included(version) => Bound::Included(version.only_release_trimmed()),
Bound::Excluded(version) => Bound::Excluded(version.only_release_trimmed()),
Bound::Unbounded => Bound::Unbounded,
})
}
/// Return the [`LowerBound`] truncated to the major and minor version.
#[must_use]
pub fn major_minor(&self) -> Self {
match &self.0 {
// Ex) `>=3.10.1` -> `>=3.10`
Bound::Included(version) => Self(Bound::Included(Version::new(
version.release().iter().take(2),
))),
// Ex) `>3.10.1` -> `>=3.10`.
Bound::Excluded(version) => Self(Bound::Included(Version::new(
version.release().iter().take(2),
))),
Bound::Unbounded => Self(Bound::Unbounded),
}
}
/// Returns `true` if the lower bound contains the given version.
pub fn contains(&self, version: &Version) -> bool {
match self.0 {
Bound::Included(ref bound) => bound <= version,
Bound::Excluded(ref bound) => bound < version,
Bound::Unbounded => true,
}
}
/// Returns the [`VersionSpecifier`] for the lower bound.
pub fn specifier(&self) -> Option<VersionSpecifier> {
match &self.0 {
Bound::Included(version) => Some(VersionSpecifier::greater_than_equal_version(
version.clone(),
)),
Bound::Excluded(version) => {
Some(VersionSpecifier::greater_than_version(version.clone()))
}
Bound::Unbounded => None,
}
}
}
impl PartialOrd for LowerBound {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// See: <https://github.com/pubgrub-rs/pubgrub/blob/4b4b44481c5f93f3233221dc736dd23e67e00992/src/range.rs#L324>
impl Ord for LowerBound {
fn cmp(&self, other: &Self) -> Ordering {
let left = self.0.as_ref();
let right = other.0.as_ref();
match (left, right) {
// left: β-----
// right: β-----
(Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
// left: [---
// right: β-----
(Bound::Included(_left), Bound::Unbounded) => Ordering::Greater,
// left: ]---
// right: β-----
(Bound::Excluded(_left), Bound::Unbounded) => Ordering::Greater,
// left: β-----
// right: [---
(Bound::Unbounded, Bound::Included(_right)) => Ordering::Less,
// left: [----- OR [----- OR [-----
// right: [--- OR [----- OR [---
(Bound::Included(left), Bound::Included(right)) => left.cmp(right),
(Bound::Excluded(left), Bound::Included(right)) => match left.cmp(right) {
// left: ]-----
// right: [---
Ordering::Less => Ordering::Less,
// left: ]-----
// right: [---
Ordering::Equal => Ordering::Greater,
// left: ]---
// right: [-----
Ordering::Greater => Ordering::Greater,
},
// left: β-----
// right: ]---
(Bound::Unbounded, Bound::Excluded(_right)) => Ordering::Less,
(Bound::Included(left), Bound::Excluded(right)) => match left.cmp(right) {
// left: [-----
// right: ]---
Ordering::Less => Ordering::Less,
// left: [-----
// right: ]---
Ordering::Equal => Ordering::Less,
// left: [---
// right: ]-----
Ordering::Greater => Ordering::Greater,
},
// left: ]----- OR ]----- OR ]---
// right: ]--- OR ]----- OR ]-----
(Bound::Excluded(left), Bound::Excluded(right)) => left.cmp(right),
}
}
}
impl Default for LowerBound {
fn default() -> Self {
Self(Bound::Unbounded)
}
}
impl Deref for LowerBound {
type Target = Bound<Version>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<LowerBound> for Bound<Version> {
fn from(bound: LowerBound) -> Self {
bound.0
}
}
/// An upper bound for a version range.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct UpperBound(pub Bound<Version>);
impl UpperBound {
/// Initialize a [`UpperBound`] with the given bound.
///
/// These bounds use release-only semantics when comparing versions.
pub fn new(bound: Bound<Version>) -> Self {
Self(match bound {
Bound::Included(version) => Bound::Included(version.only_release_trimmed()),
Bound::Excluded(version) => Bound::Excluded(version.only_release_trimmed()),
Bound::Unbounded => Bound::Unbounded,
})
}
/// Return the [`UpperBound`] truncated to the major and minor version.
#[must_use]
pub fn major_minor(&self) -> Self {
match &self.0 {
// Ex) `<=3.10.1` -> `<=3.10`
Bound::Included(version) => Self(Bound::Included(Version::new(
version.release().iter().take(2),
))),
// Ex) `<3.10.1` -> `<=3.10` (but `<3.10.0` is `<3.10`)
Bound::Excluded(version) => {
if version.release().get(2).is_some_and(|patch| *patch > 0) {
Self(Bound::Included(Version::new(
version.release().iter().take(2),
)))
} else {
Self(Bound::Excluded(Version::new(
version.release().iter().take(2),
)))
}
}
Bound::Unbounded => Self(Bound::Unbounded),
}
}
/// Returns `true` if the upper bound contains the given version.
pub fn contains(&self, version: &Version) -> bool {
match self.0 {
Bound::Included(ref bound) => bound >= version,
Bound::Excluded(ref bound) => bound > version,
Bound::Unbounded => true,
}
}
/// Returns the [`VersionSpecifier`] for the upper bound.
pub fn specifier(&self) -> Option<VersionSpecifier> {
match &self.0 {
Bound::Included(version) => {
Some(VersionSpecifier::less_than_equal_version(version.clone()))
}
Bound::Excluded(version) => Some(VersionSpecifier::less_than_version(version.clone())),
Bound::Unbounded => None,
}
}
}
impl PartialOrd for UpperBound {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// See: <https://github.com/pubgrub-rs/pubgrub/blob/4b4b44481c5f93f3233221dc736dd23e67e00992/src/range.rs#L324>
impl Ord for UpperBound {
fn cmp(&self, other: &Self) -> Ordering {
let left = self.0.as_ref();
let right = other.0.as_ref();
match (left, right) {
// left: -----β
// right: -----β
(Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
// left: ---]
// right: -----β
(Bound::Included(_left), Bound::Unbounded) => Ordering::Less,
// left: ---[
// right: -----β
(Bound::Excluded(_left), Bound::Unbounded) => Ordering::Less,
// left: -----β
// right: ---]
(Bound::Unbounded, Bound::Included(_right)) => Ordering::Greater,
// left: -----] OR -----] OR ---]
// right: ---] OR -----] OR -----]
(Bound::Included(left), Bound::Included(right)) => left.cmp(right),
(Bound::Excluded(left), Bound::Included(right)) => match left.cmp(right) {
// left: ---[
// right: -----]
Ordering::Less => Ordering::Less,
// left: -----[
// right: -----]
Ordering::Equal => Ordering::Less,
// left: -----[
// right: ---]
Ordering::Greater => Ordering::Greater,
},
(Bound::Unbounded, Bound::Excluded(_right)) => Ordering::Greater,
(Bound::Included(left), Bound::Excluded(right)) => match left.cmp(right) {
// left: ---]
// right: -----[
Ordering::Less => Ordering::Less,
// left: -----]
// right: -----[
Ordering::Equal => Ordering::Greater,
// left: -----]
// right: ---[
Ordering::Greater => Ordering::Greater,
},
// left: -----[ OR -----[ OR ---[
// right: ---[ OR -----[ OR -----[
(Bound::Excluded(left), Bound::Excluded(right)) => left.cmp(right),
}
}
}
impl Default for UpperBound {
fn default() -> Self {
Self(Bound::Unbounded)
}
}
impl Deref for UpperBound {
type Target = Bound<Version>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<UpperBound> for Bound<Version> {
fn from(bound: UpperBound) -> Self {
bound.0
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Test that `<V.postN` excludes pre-releases of the base version but includes
/// earlier post-releases and the final release.
///
/// See: <https://github.com/astral-sh/uv/issues/16868>
#[test]
fn less_than_post_release() {
let specifier: VersionSpecifier = "<0.12.0.post2".parse().unwrap();
let range = Ranges::<Version>::from(specifier);
// Should include versions less than base release.
let v = "0.11.0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.11.0");
// Should exclude pre-releases of the base release.
let v = "0.12.0a1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0a1");
let v = "0.12.0b1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0b1");
let v = "0.12.0rc1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0rc1");
let v = "0.12.0.dev0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.dev0");
// Should also exclude post-releases of pre-releases.
let v = "0.12.0a1.post1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0a1.post1");
let v = "0.12.0b1.post1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0b1.post1");
// Should include the final release.
let v = "0.12.0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.12.0");
// Should include earlier post-releases.
let v = "0.12.0.post1".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.12.0.post1");
// Should exclude the specified post-release.
let v = "0.12.0.post2".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.post2");
// Should exclude later versions.
let v = "0.13.0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.13.0");
}
/// Test that `<V` (non-post-release) correctly excludes pre-releases.
#[test]
fn less_than_final_release() {
let specifier: VersionSpecifier = "<0.12.0".parse().unwrap();
let range = Ranges::<Version>::from(specifier);
// Should include versions less than base release.
let v = "0.11.0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.11.0");
// Should exclude pre-releases of the specified version.
let v = "0.12.0a1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0a1");
let v = "0.12.0.dev0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.dev0");
// Should exclude the specified version.
let v = "0.12.0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0");
// Should exclude post-releases of the specified version.
let v = "0.12.0.post1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.post1");
}
/// Test that `<V.preN` allows earlier pre-releases of the same version.
#[test]
fn less_than_pre_release() {
let specifier: VersionSpecifier = "<0.12.0b1".parse().unwrap();
let range = Ranges::<Version>::from(specifier);
// Should include earlier pre-releases.
let v = "0.12.0a1".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.12.0a1");
let v = "0.12.0.dev0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.12.0.dev0");
// Should exclude the specified pre-release and later.
let v = "0.12.0b1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0b1");
let v = "0.12.0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0");
}
/// Test the edge case where `<V.post0` still includes the final release.
#[test]
fn less_than_post_zero() {
let specifier: VersionSpecifier = "<0.12.0.post0".parse().unwrap();
let range = Ranges::<Version>::from(specifier);
// Should include versions less than base release.
let v = "0.11.0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.11.0");
// Should exclude pre-releases of the base release.
let v = "0.12.0a1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0a1");
// Should include the final release (0.12.0 < 0.12.0.post0).
let v = "0.12.0".parse::<Version>().unwrap();
assert!(range.contains(&v), "should include 0.12.0");
// Should exclude post0 and later.
let v = "0.12.0.post0".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.post0");
let v = "0.12.0.post1".parse::<Version>().unwrap();
assert!(!range.contains(&v), "should exclude 0.12.0.post1");
}
}
| 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-pep440/src/version_specifier.rs | crates/uv-pep440/src/version_specifier.rs | use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt::Formatter;
use std::ops::Bound;
use std::str::FromStr;
use crate::{
Operator, OperatorParseError, Version, VersionPattern, VersionPatternParseError, version,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
#[cfg(feature = "tracing")]
use tracing::warn;
/// Sorted version specifiers, such as `>=2.1,<3`.
///
/// Python requirements can contain multiple version specifier so we need to store them in a list,
/// such as `>1.2,<2.0` being `[">1.2", "<2.0"]`.
///
/// ```rust
/// # use std::str::FromStr;
/// # use uv_pep440::{VersionSpecifiers, Version, Operator};
///
/// let version = Version::from_str("1.19").unwrap();
/// let version_specifiers = VersionSpecifiers::from_str(">=1.16, <2.0").unwrap();
/// assert!(version_specifiers.contains(&version));
/// // VersionSpecifiers derefs into a list of specifiers
/// assert_eq!(version_specifiers.iter().position(|specifier| *specifier.operator() == Operator::LessThan), Some(1));
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug)))]
pub struct VersionSpecifiers(Box<[VersionSpecifier]>);
impl std::ops::Deref for VersionSpecifiers {
type Target = [VersionSpecifier];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl VersionSpecifiers {
/// Matches all versions.
pub fn empty() -> Self {
Self(Box::new([]))
}
/// The number of specifiers.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether all specifiers match the given version.
pub fn contains(&self, version: &Version) -> bool {
self.iter().all(|specifier| specifier.contains(version))
}
/// Returns `true` if there are no specifiers.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Sort the specifiers.
fn from_unsorted(mut specifiers: Vec<VersionSpecifier>) -> Self {
// TODO(konsti): This seems better than sorting on insert and not getting the size hint,
// but i haven't measured it.
specifiers.sort_by(|a, b| a.version().cmp(b.version()));
Self(specifiers.into_boxed_slice())
}
/// Returns the [`VersionSpecifiers`] whose union represents the given range.
///
/// This function is not applicable to ranges involving pre-release versions.
pub fn from_release_only_bounds<'a>(
mut bounds: impl Iterator<Item = (&'a Bound<Version>, &'a Bound<Version>)>,
) -> Self {
let mut specifiers = Vec::new();
let Some((start, mut next)) = bounds.next() else {
return Self::empty();
};
// Add specifiers for the holes between the bounds.
for (lower, upper) in bounds {
let specifier = match (next, lower) {
// Ex) [3.7, 3.8.5), (3.8.5, 3.9] -> >=3.7,!=3.8.5,<=3.9
(Bound::Excluded(prev), Bound::Excluded(lower)) if prev == lower => {
Some(VersionSpecifier::not_equals_version(prev.clone()))
}
// Ex) [3.7, 3.8), (3.8, 3.9] -> >=3.7,!=3.8.*,<=3.9
(Bound::Excluded(prev), Bound::Included(lower)) => {
match *prev.only_release_trimmed().release() {
[major] if *lower.only_release_trimmed().release() == [major, 1] => {
Some(VersionSpecifier::not_equals_star_version(Version::new([
major, 0,
])))
}
[major, minor]
if *lower.only_release_trimmed().release() == [major, minor + 1] =>
{
Some(VersionSpecifier::not_equals_star_version(Version::new([
major, minor,
])))
}
_ => None,
}
}
_ => None,
};
if let Some(specifier) = specifier {
specifiers.push(specifier);
} else {
#[cfg(feature = "tracing")]
warn!(
"Ignoring unsupported gap in `requires-python` version: {next:?} -> {lower:?}"
);
}
next = upper;
}
let end = next;
// Add the specifiers for the bounding range.
specifiers.extend(VersionSpecifier::from_release_only_bounds((start, end)));
Self::from_unsorted(specifiers)
}
}
impl FromIterator<VersionSpecifier> for VersionSpecifiers {
fn from_iter<T: IntoIterator<Item = VersionSpecifier>>(iter: T) -> Self {
Self::from_unsorted(iter.into_iter().collect())
}
}
impl IntoIterator for VersionSpecifiers {
type Item = VersionSpecifier;
type IntoIter = std::vec::IntoIter<VersionSpecifier>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_vec().into_iter()
}
}
impl FromStr for VersionSpecifiers {
type Err = VersionSpecifiersParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_version_specifiers(s).map(Self::from_unsorted)
}
}
impl From<VersionSpecifier> for VersionSpecifiers {
fn from(specifier: VersionSpecifier) -> Self {
Self(Box::new([specifier]))
}
}
impl std::fmt::Display for VersionSpecifiers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (idx, version_specifier) in self.0.iter().enumerate() {
// Separate version specifiers by comma, but we need one comma less than there are
// specifiers
if idx == 0 {
write!(f, "{version_specifier}")?;
} else {
write!(f, ", {version_specifier}")?;
}
}
Ok(())
}
}
impl Default for VersionSpecifiers {
fn default() -> Self {
Self::empty()
}
}
impl<'de> Deserialize<'de> for VersionSpecifiers {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = VersionSpecifiers;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
VersionSpecifiers::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Serialize for VersionSpecifiers {
#[allow(unstable_name_collisions)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(
&self
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(","),
)
}
}
/// Error with span information (unicode width) inside the parsed line
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct VersionSpecifiersParseError {
// Clippy complains about this error type being too big (at time of
// writing, over 150 bytes). That does seem a little big, so we box things.
inner: Box<VersionSpecifiersParseErrorInner>,
}
#[derive(Debug, Eq, PartialEq, Clone)]
struct VersionSpecifiersParseErrorInner {
/// The underlying error that occurred.
err: VersionSpecifierParseError,
/// The string that failed to parse
line: String,
/// The starting byte offset into the original string where the error
/// occurred.
start: usize,
/// The ending byte offset into the original string where the error
/// occurred.
end: usize,
}
impl std::fmt::Display for VersionSpecifiersParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use unicode_width::UnicodeWidthStr;
let VersionSpecifiersParseErrorInner {
ref err,
ref line,
start,
end,
} = *self.inner;
writeln!(f, "Failed to parse version: {err}:")?;
writeln!(f, "{line}")?;
let indent = line[..start].width();
let point = line[start..end].width();
writeln!(f, "{}{}", " ".repeat(indent), "^".repeat(point))?;
Ok(())
}
}
impl VersionSpecifiersParseError {
/// The string that failed to parse
pub fn line(&self) -> &String {
&self.inner.line
}
}
impl std::error::Error for VersionSpecifiersParseError {}
/// A version range such as `>1.2.3`, `<=4!5.6.7-a8.post9.dev0` or `== 4.1.*`. Parse with
/// `VersionSpecifier::from_str`
///
/// ```rust
/// use std::str::FromStr;
/// use uv_pep440::{Version, VersionSpecifier};
///
/// let version = Version::from_str("1.19").unwrap();
/// let version_specifier = VersionSpecifier::from_str("== 1.*").unwrap();
/// assert!(version_specifier.contains(&version));
/// ```
#[derive(Eq, Ord, PartialEq, PartialOrd, Debug, Clone, Hash)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug)))]
pub struct VersionSpecifier {
/// ~=|==|!=|<=|>=|<|>|===, plus whether the version ended with a star
pub(crate) operator: Operator,
/// The whole version part behind the operator
pub(crate) version: Version,
}
impl<'de> Deserialize<'de> for VersionSpecifier {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl de::Visitor<'_> for Visitor {
type Value = VersionSpecifier;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
VersionSpecifier::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl Serialize for VersionSpecifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl VersionSpecifier {
/// Build from parts, validating that the operator is allowed with that version. The last
/// parameter indicates a trailing `.*`, to differentiate between `1.1.*` and `1.1`
pub fn from_pattern(
operator: Operator,
version_pattern: VersionPattern,
) -> Result<Self, VersionSpecifierBuildError> {
let star = version_pattern.is_wildcard();
let version = version_pattern.into_version();
// Check if there are star versions and if so, switch operator to star version
let operator = if star {
match operator.to_star() {
Some(starop) => starop,
None => {
return Err(BuildErrorKind::OperatorWithStar { operator }.into());
}
}
} else {
operator
};
Self::from_version(operator, version)
}
/// Create a new version specifier from an operator and a version.
pub fn from_version(
operator: Operator,
version: Version,
) -> Result<Self, VersionSpecifierBuildError> {
// "Local version identifiers are NOT permitted in this version specifier."
if version.is_local() && !operator.is_local_compatible() {
return Err(BuildErrorKind::OperatorLocalCombo { operator, version }.into());
}
if operator == Operator::TildeEqual && version.release().len() < 2 {
return Err(BuildErrorKind::CompatibleRelease.into());
}
Ok(Self { operator, version })
}
/// Remove all non-release parts of the version.
///
/// The marker decision diagram relies on the assumption that the negation of a marker tree is
/// the complement of the marker space. However, pre-release versions violate this assumption.
///
/// For example, the marker `python_full_version > '3.9' or python_full_version <= '3.9'`
/// does not match `python_full_version == 3.9.0a0` and so cannot simplify to `true`. However,
/// its negation, `python_full_version > '3.9' and python_full_version <= '3.9'`, also does not
/// match `3.9.0a0` and simplifies to `false`, which violates the algebra decision diagrams
/// rely on. For this reason we ignore pre-release versions entirely when evaluating markers.
///
/// Note that `python_version` cannot take on pre-release values as it is truncated to just the
/// major and minor version segments. Thus using release-only specifiers is definitely necessary
/// for `python_version` to fully simplify any ranges, such as
/// `python_version > '3.9' or python_version <= '3.9'`, which is always `true` for
/// `python_version`. For `python_full_version` however, this decision is a semantic change.
///
/// For Python versions, the major.minor is considered the API version, so unlike the rules
/// for package versions in PEP 440, we Python `3.9.0a0` is acceptable for `>= "3.9"`.
#[must_use]
pub fn only_release(self) -> Self {
Self {
operator: self.operator,
version: self.version.only_release(),
}
}
/// Remove all parts of the version beyond the minor segment of the release.
#[must_use]
pub fn only_minor_release(&self) -> Self {
Self {
operator: self.operator,
version: self.version.only_minor_release(),
}
}
/// `==<version>`
pub fn equals_version(version: Version) -> Self {
Self {
operator: Operator::Equal,
version,
}
}
/// `==<version>.*`
pub fn equals_star_version(version: Version) -> Self {
Self {
operator: Operator::EqualStar,
version,
}
}
/// `!=<version>.*`
pub fn not_equals_star_version(version: Version) -> Self {
Self {
operator: Operator::NotEqualStar,
version,
}
}
/// `!=<version>`
pub fn not_equals_version(version: Version) -> Self {
Self {
operator: Operator::NotEqual,
version,
}
}
/// `>=<version>`
pub fn greater_than_equal_version(version: Version) -> Self {
Self {
operator: Operator::GreaterThanEqual,
version,
}
}
/// `><version>`
pub fn greater_than_version(version: Version) -> Self {
Self {
operator: Operator::GreaterThan,
version,
}
}
/// `<=<version>`
pub fn less_than_equal_version(version: Version) -> Self {
Self {
operator: Operator::LessThanEqual,
version,
}
}
/// `<<version>`
pub fn less_than_version(version: Version) -> Self {
Self {
operator: Operator::LessThan,
version,
}
}
/// Get the operator, e.g. `>=` in `>= 2.0.0`
pub fn operator(&self) -> &Operator {
&self.operator
}
/// Get the version, e.g. `2.0.0` in `<= 2.0.0`
pub fn version(&self) -> &Version {
&self.version
}
/// Get the operator and version parts of this specifier.
pub fn into_parts(self) -> (Operator, Version) {
(self.operator, self.version)
}
/// Whether the version marker includes a prerelease.
pub fn any_prerelease(&self) -> bool {
self.version.any_prerelease()
}
/// Returns the version specifiers whose union represents the given range.
///
/// This function is not applicable to ranges involving pre-release versions.
pub fn from_release_only_bounds(
bounds: (&Bound<Version>, &Bound<Version>),
) -> impl Iterator<Item = Self> {
let (b1, b2) = match bounds {
(Bound::Included(v1), Bound::Included(v2)) if v1 == v2 => {
(Some(Self::equals_version(v1.clone())), None)
}
// `v >= 3.7 && v < 3.8` is equivalent to `v == 3.7.*`
(Bound::Included(v1), Bound::Excluded(v2)) => {
match *v1.only_release_trimmed().release() {
[major] if *v2.only_release_trimmed().release() == [major, 1] => {
let version = Version::new([major, 0]);
(Some(Self::equals_star_version(version)), None)
}
[major, minor]
if *v2.only_release_trimmed().release() == [major, minor + 1] =>
{
let version = Version::new([major, minor]);
(Some(Self::equals_star_version(version)), None)
}
_ => (
Self::from_lower_bound(&Bound::Included(v1.clone())),
Self::from_upper_bound(&Bound::Excluded(v2.clone())),
),
}
}
(lower, upper) => (Self::from_lower_bound(lower), Self::from_upper_bound(upper)),
};
b1.into_iter().chain(b2)
}
/// Returns a version specifier representing the given lower bound.
pub fn from_lower_bound(bound: &Bound<Version>) -> Option<Self> {
match bound {
Bound::Included(version) => {
Some(Self::from_version(Operator::GreaterThanEqual, version.clone()).unwrap())
}
Bound::Excluded(version) => {
Some(Self::from_version(Operator::GreaterThan, version.clone()).unwrap())
}
Bound::Unbounded => None,
}
}
/// Returns a version specifier representing the given upper bound.
pub fn from_upper_bound(bound: &Bound<Version>) -> Option<Self> {
match bound {
Bound::Included(version) => {
Some(Self::from_version(Operator::LessThanEqual, version.clone()).unwrap())
}
Bound::Excluded(version) => {
Some(Self::from_version(Operator::LessThan, version.clone()).unwrap())
}
Bound::Unbounded => None,
}
}
/// Whether the given version satisfies the version range.
///
/// For example, `>=1.19,<2.0` contains `1.21`, but not `2.0`.
///
/// See:
/// - <https://peps.python.org/pep-0440/#version-specifiers>
/// - <https://github.com/pypa/packaging/blob/e184feef1a28a5c574ec41f5c263a3a573861f5a/packaging/specifiers.py#L362-L496>
pub fn contains(&self, version: &Version) -> bool {
// "Except where specifically noted below, local version identifiers MUST NOT be permitted
// in version specifiers, and local version labels MUST be ignored entirely when checking
// if candidate versions match a given version specifier."
let this = self.version();
let other = if this.local().is_empty() && !version.local().is_empty() {
Cow::Owned(version.clone().without_local())
} else {
Cow::Borrowed(version)
};
match self.operator {
Operator::Equal => other.as_ref() == this,
Operator::EqualStar => {
this.epoch() == other.epoch()
&& self
.version
.release()
.iter()
.zip(&*other.release())
.all(|(this, other)| this == other)
}
#[allow(deprecated)]
Operator::ExactEqual => {
#[cfg(feature = "tracing")]
{
warn!("Using arbitrary equality (`===`) is discouraged");
}
self.version.to_string() == version.to_string()
}
Operator::NotEqual => this != other.as_ref(),
Operator::NotEqualStar => {
this.epoch() != other.epoch()
|| !this
.release()
.iter()
.zip(&*version.release())
.all(|(this, other)| this == other)
}
Operator::TildeEqual => {
// "For a given release identifier V.N, the compatible release clause is
// approximately equivalent to the pair of comparison clauses: `>= V.N, == V.*`"
// First, we test that every but the last digit matches.
// We know that this must hold true since we checked it in the constructor
assert!(this.release().len() > 1);
if this.epoch() != other.epoch() {
return false;
}
if !this.release()[..this.release().len() - 1]
.iter()
.zip(&*other.release())
.all(|(this, other)| this == other)
{
return false;
}
// According to PEP 440, this ignores the pre-release special rules
// pypa/packaging disagrees: https://github.com/pypa/packaging/issues/617
other.as_ref() >= this
}
Operator::GreaterThan => {
if other.epoch() > this.epoch() {
return true;
}
if version::compare_release(&this.release(), &other.release()) == Ordering::Equal {
// This special case is here so that, unless the specifier itself
// includes is a post-release version, that we do not accept
// post-release versions for the version mentioned in the specifier
// (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
if !this.is_post() && other.is_post() {
return false;
}
// We already checked that self doesn't have a local version
if other.is_local() {
return false;
}
}
other.as_ref() > this
}
Operator::GreaterThanEqual => other.as_ref() >= this,
Operator::LessThan => {
if other.epoch() < this.epoch() {
return true;
}
// The exclusive ordered comparison <V MUST NOT allow a pre-release of the specified
// version unless the specified version is itself a pre-release. E.g., <3.1 should
// not match 3.1.dev0, but should match both 3.0.dev0 and 3.0, while <3.1.dev1 does
// match 3.1.dev0, 3.0.dev0 and 3.0.
if version::compare_release(&this.release(), &other.release()) == Ordering::Equal
&& !this.any_prerelease()
&& other.any_prerelease()
{
return false;
}
other.as_ref() < this
}
Operator::LessThanEqual => other.as_ref() <= this,
}
}
/// Whether this version specifier rejects versions below a lower cutoff.
pub fn has_lower_bound(&self) -> bool {
match self.operator() {
Operator::Equal
| Operator::EqualStar
| Operator::ExactEqual
| Operator::TildeEqual
| Operator::GreaterThan
| Operator::GreaterThanEqual => true,
Operator::LessThanEqual
| Operator::LessThan
| Operator::NotEqualStar
| Operator::NotEqual => false,
}
}
}
impl FromStr for VersionSpecifier {
type Err = VersionSpecifierParseError;
/// Parses a version such as `>= 1.19`, `== 1.1.*`,`~=1.0+abc.5` or `<=1!2012.2`
fn from_str(spec: &str) -> Result<Self, Self::Err> {
let mut s = unscanny::Scanner::new(spec);
s.eat_while(|c: char| c.is_whitespace());
// operator but we don't know yet if it has a star
let operator = s.eat_while(['=', '!', '~', '<', '>']);
if operator.is_empty() {
// Attempt to parse the version from the rest of the scanner to provide a more useful error message in MissingOperator.
// If it is not able to be parsed (i.e. not a valid version), it will just be None and no additional info will be added to the error message.
s.eat_while(|c: char| c.is_whitespace());
let version = s.eat_while(|c: char| !c.is_whitespace());
s.eat_while(|c: char| c.is_whitespace());
return Err(ParseErrorKind::MissingOperator(VersionOperatorBuildError {
version_pattern: VersionPattern::from_str(version).ok(),
})
.into());
}
let operator = Operator::from_str(operator).map_err(ParseErrorKind::InvalidOperator)?;
s.eat_while(|c: char| c.is_whitespace());
let version = s.eat_while(|c: char| !c.is_whitespace());
if version.is_empty() {
return Err(ParseErrorKind::MissingVersion.into());
}
let vpat = version.parse().map_err(ParseErrorKind::InvalidVersion)?;
let version_specifier =
Self::from_pattern(operator, vpat).map_err(ParseErrorKind::InvalidSpecifier)?;
s.eat_while(|c: char| c.is_whitespace());
if !s.done() {
return Err(ParseErrorKind::InvalidTrailing(s.after().to_string()).into());
}
Ok(version_specifier)
}
}
impl std::fmt::Display for VersionSpecifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.operator == Operator::EqualStar || self.operator == Operator::NotEqualStar {
return write!(f, "{}{}.*", self.operator, self.version);
}
write!(f, "{}{}", self.operator, self.version)
}
}
/// An error that can occur when constructing a version specifier.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionSpecifierBuildError {
// We box to shrink the error type's size. This in turn keeps Result<T, E>
// smaller and should lead to overall better codegen.
kind: Box<BuildErrorKind>,
}
impl std::error::Error for VersionSpecifierBuildError {}
impl std::fmt::Display for VersionSpecifierBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self.kind {
BuildErrorKind::OperatorLocalCombo {
operator: ref op,
ref version,
} => {
let local = version.local();
write!(
f,
"Operator {op} is incompatible with versions \
containing non-empty local segments (`+{local}`)",
)
}
BuildErrorKind::OperatorWithStar { operator: ref op } => {
write!(
f,
"Operator {op} cannot be used with a wildcard version specifier",
)
}
BuildErrorKind::CompatibleRelease => {
write!(
f,
"The ~= operator requires at least two segments in the release version"
)
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct VersionOperatorBuildError {
version_pattern: Option<VersionPattern>,
}
impl std::error::Error for VersionOperatorBuildError {}
impl std::fmt::Display for VersionOperatorBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Unexpected end of version specifier, expected operator")?;
if let Some(version_pattern) = &self.version_pattern {
let version_specifier =
VersionSpecifier::from_pattern(Operator::Equal, version_pattern.clone()).unwrap();
write!(f, ". Did you mean `{version_specifier}`?")?;
}
Ok(())
}
}
/// The specific kind of error that can occur when building a version specifier
/// from an operator and version pair.
#[derive(Clone, Debug, Eq, PartialEq)]
enum BuildErrorKind {
/// Occurs when one attempts to build a version specifier with
/// a version containing a non-empty local segment with and an
/// incompatible operator.
OperatorLocalCombo {
/// The operator given.
operator: Operator,
/// The version given.
version: Version,
},
/// Occurs when a version specifier contains a wildcard, but is used with
/// an incompatible operator.
OperatorWithStar {
/// The operator given.
operator: Operator,
},
/// Occurs when the compatible release operator (`~=`) is used with a
/// version that has fewer than 2 segments in its release version.
CompatibleRelease,
}
impl From<BuildErrorKind> for VersionSpecifierBuildError {
fn from(kind: BuildErrorKind) -> Self {
Self {
kind: Box::new(kind),
}
}
}
/// An error that can occur when parsing or constructing a version specifier.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionSpecifierParseError {
// We box to shrink the error type's size. This in turn keeps Result<T, E>
// smaller and should lead to overall better codegen.
kind: Box<ParseErrorKind>,
}
impl std::error::Error for VersionSpecifierParseError {}
impl std::fmt::Display for VersionSpecifierParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// Note that even though we have nested error types here, since we
// don't expose them through std::error::Error::source, we emit them
// as part of the error message here. This makes the error a bit
// more self-contained. And it's not clear how useful it is exposing
// internal errors.
match *self.kind {
ParseErrorKind::InvalidOperator(ref err) => err.fmt(f),
ParseErrorKind::InvalidVersion(ref err) => err.fmt(f),
ParseErrorKind::InvalidSpecifier(ref err) => err.fmt(f),
ParseErrorKind::MissingOperator(ref err) => err.fmt(f),
ParseErrorKind::MissingVersion => {
write!(f, "Unexpected end of version specifier, expected version")
}
ParseErrorKind::InvalidTrailing(ref trail) => {
write!(f, "Trailing `{trail}` is not allowed")
}
}
}
}
/// The specific kind of error that occurs when parsing a single version
/// specifier from a string.
#[derive(Clone, Debug, Eq, PartialEq)]
enum ParseErrorKind {
InvalidOperator(OperatorParseError),
InvalidVersion(VersionPatternParseError),
InvalidSpecifier(VersionSpecifierBuildError),
MissingOperator(VersionOperatorBuildError),
MissingVersion,
InvalidTrailing(String),
}
impl From<ParseErrorKind> for VersionSpecifierParseError {
fn from(kind: ParseErrorKind) -> Self {
Self {
kind: Box::new(kind),
}
}
}
/// Parse a list of specifiers such as `>= 1.0, != 1.3.*, < 2.0`.
pub(crate) fn parse_version_specifiers(
spec: &str,
) -> Result<Vec<VersionSpecifier>, VersionSpecifiersParseError> {
let mut version_ranges = Vec::new();
if spec.is_empty() {
return Ok(version_ranges);
}
let mut start: usize = 0;
let separator = ",";
for version_range_spec in spec.split(separator) {
match VersionSpecifier::from_str(version_range_spec) {
Err(err) => {
return Err(VersionSpecifiersParseError {
inner: Box::new(VersionSpecifiersParseErrorInner {
err,
line: spec.to_string(),
start,
end: start + version_range_spec.len(),
}),
});
}
Ok(version_range) => {
version_ranges.push(version_range);
}
}
start += version_range_spec.len();
start += separator.len();
}
Ok(version_ranges)
}
/// A simple `~=` version specifier with a major, minor and (optional) patch version, e.g., `~=3.13`
/// or `~=3.13.0`.
#[derive(Clone, Debug)]
pub struct TildeVersionSpecifier<'a> {
inner: Cow<'a, VersionSpecifier>,
}
impl<'a> TildeVersionSpecifier<'a> {
/// Create a new [`TildeVersionSpecifier`] from a [`VersionSpecifier`] value.
///
| 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/lib.rs | crates/uv-auth/src/lib.rs | pub use access_token::AccessToken;
pub use cache::CredentialsCache;
pub use credentials::{Credentials, Username};
pub use index::{AuthPolicy, Index, Indexes};
pub use keyring::KeyringProvider;
pub use middleware::AuthMiddleware;
pub use pyx::{
DEFAULT_TOLERANCE_SECS, PyxJwt, PyxOAuthTokens, PyxTokenStore, PyxTokens, TokenStoreError,
};
pub use realm::{Realm, RealmRef};
pub use service::{Service, ServiceParseError};
pub use store::{AuthBackend, AuthScheme, TextCredentialStore, TomlCredentialError};
mod access_token;
mod cache;
mod credentials;
mod index;
mod keyring;
mod middleware;
mod providers;
mod pyx;
mod realm;
mod service;
mod store;
| 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.