repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/extras.rs
crates/uv-requirements/src/extras.rs
use std::sync::Arc; use futures::{TryStreamExt, stream::FuturesOrdered}; use uv_distribution::{DistributionDatabase, Reporter}; use uv_distribution_types::DistributionMetadata; use uv_distribution_types::Requirement; use uv_resolver::{InMemoryIndex, MetadataResponse}; use uv_types::{BuildContext, HashStrategy}; use crate::{Error, required_dist}; /// A resolver to expand the requested extras for a set of requirements to include all defined /// extras. pub struct ExtrasResolver<'a, Context: BuildContext> { /// Whether to check hashes for distributions. hasher: &'a HashStrategy, /// The in-memory index for resolving dependencies. index: &'a InMemoryIndex, /// The database for fetching and building distributions. database: DistributionDatabase<'a, Context>, } impl<'a, Context: BuildContext> ExtrasResolver<'a, Context> { /// Instantiate a new [`ExtrasResolver`] for a given set of requirements. pub fn new( hasher: &'a HashStrategy, index: &'a InMemoryIndex, database: DistributionDatabase<'a, Context>, ) -> Self { Self { hasher, index, database, } } /// Set the [`Reporter`] to use for this resolver. #[must_use] pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self { Self { database: self.database.with_reporter(reporter), ..self } } /// Expand the set of available extras for a given set of requirements. pub async fn resolve( self, requirements: impl Iterator<Item = Requirement>, ) -> Result<Vec<Requirement>, Error> { let Self { hasher, index, database, } = self; requirements .map(async |requirement| { Self::resolve_requirement(requirement, hasher, index, &database).await }) .collect::<FuturesOrdered<_>>() .try_collect() .await } /// Expand the set of available extras for a given [`Requirement`]. async fn resolve_requirement( requirement: Requirement, hasher: &HashStrategy, index: &InMemoryIndex, database: &DistributionDatabase<'a, Context>, ) -> Result<Requirement, Error> { // Determine whether the requirement represents a local distribution and convert to a // buildable distribution. let Some(dist) = required_dist(&requirement)? else { return Ok(requirement); }; // Fetch the metadata for the distribution. let metadata = { let id = dist.version_id(); if let Some(archive) = index .distributions() .get(&id) .as_deref() .and_then(|response| { if let MetadataResponse::Found(archive, ..) = response { Some(archive) } else { None } }) { // If the metadata is already in the index, return it. archive.metadata.clone() } else { // Run the PEP 517 build process to extract metadata from the source distribution. let archive = database .get_or_build_wheel_metadata(&dist, hasher.get(&dist)) .await .map_err(|err| Error::from_dist(dist, err))?; let metadata = archive.metadata.clone(); // Insert the metadata into the index. index .distributions() .done(id, Arc::new(MetadataResponse::Found(archive))); metadata } }; // Sort extras for consistency. let extras = { let mut extras = metadata.provides_extra.to_vec(); extras.sort_unstable(); extras }; Ok(Requirement { extras: extras.into_boxed_slice(), ..requirement }) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/source_tree.rs
crates/uv-requirements/src/source_tree.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::{Context, Result}; use futures::TryStreamExt; use futures::stream::FuturesOrdered; use url::Url; use uv_configuration::ExtrasSpecification; use uv_distribution::{DistributionDatabase, FlatRequiresDist, Reporter, RequiresDist}; use uv_distribution_types::Requirement; use uv_distribution_types::{ BuildableSource, DirectorySourceUrl, HashGeneration, HashPolicy, SourceUrl, VersionId, }; use uv_fs::Simplified; use uv_normalize::{ExtraName, PackageName}; use uv_pep508::RequirementOrigin; use uv_pypi_types::PyProjectToml; use uv_redacted::DisplaySafeUrl; use uv_resolver::{InMemoryIndex, MetadataResponse}; use uv_types::{BuildContext, HashStrategy}; #[derive(Debug, Clone)] pub enum SourceTree { PyProjectToml(PathBuf, PyProjectToml), SetupPy(PathBuf), SetupCfg(PathBuf), } impl SourceTree { /// Return the [`Path`] to the file representing the source tree (e.g., the `pyproject.toml`). pub fn path(&self) -> &Path { match self { Self::PyProjectToml(path, ..) => path, Self::SetupPy(path) => path, Self::SetupCfg(path) => path, } } /// Return the [`PyProjectToml`] if this is a `pyproject.toml`-based source tree. pub fn pyproject_toml(&self) -> Option<&PyProjectToml> { match self { Self::PyProjectToml(.., toml) => Some(toml), _ => None, } } } #[derive(Debug, Clone)] pub struct SourceTreeResolution { /// The requirements sourced from the source trees. pub requirements: Box<[Requirement]>, /// The names of the projects that were resolved. pub project: PackageName, /// The extras used when resolving the requirements. pub extras: Box<[ExtraName]>, } /// A resolver for requirements specified via source trees. /// /// Used, e.g., to determine the input requirements when a user specifies a `pyproject.toml` /// file, which may require running PEP 517 build hooks to extract metadata. pub struct SourceTreeResolver<'a, Context: BuildContext> { /// The extras to include when resolving requirements. extras: &'a ExtrasSpecification, /// The hash policy to enforce. hasher: &'a HashStrategy, /// The in-memory index for resolving dependencies. index: &'a InMemoryIndex, /// The database for fetching and building distributions. database: DistributionDatabase<'a, Context>, } impl<'a, Context: BuildContext> SourceTreeResolver<'a, Context> { /// Instantiate a new [`SourceTreeResolver`] for a given set of `source_trees`. pub fn new( extras: &'a ExtrasSpecification, hasher: &'a HashStrategy, index: &'a InMemoryIndex, database: DistributionDatabase<'a, Context>, ) -> Self { Self { extras, hasher, index, database, } } /// Set the [`Reporter`] to use for this resolver. #[must_use] pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self { Self { database: self.database.with_reporter(reporter), ..self } } /// Resolve the requirements from the provided source trees. pub async fn resolve( self, source_trees: impl Iterator<Item = &SourceTree>, ) -> Result<Vec<SourceTreeResolution>> { let resolutions: Vec<_> = source_trees .map(async |source_tree| self.resolve_source_tree(source_tree).await) .collect::<FuturesOrdered<_>>() .try_collect() .await?; Ok(resolutions) } /// Infer the dependencies for a directory dependency. async fn resolve_source_tree(&self, source_tree: &SourceTree) -> Result<SourceTreeResolution> { let metadata = self.resolve_requires_dist(source_tree).await?; let origin = RequirementOrigin::Project(source_tree.path().to_path_buf(), metadata.name.clone()); // Determine the extras to include when resolving the requirements. let extras = self .extras .extra_names(metadata.provides_extra.iter()) .cloned() .collect::<Vec<_>>(); let mut requirements = Vec::new(); // Flatten any transitive extras and include dependencies // (unless something like --only-group was passed) requirements.extend( FlatRequiresDist::from_requirements(metadata.requires_dist, &metadata.name) .into_iter() .map(|requirement| Requirement { origin: Some(origin.clone()), marker: requirement.marker.simplify_extras(&extras), ..requirement }), ); let requirements = requirements.into_boxed_slice(); let project = metadata.name; let extras = metadata.provides_extra; Ok(SourceTreeResolution { requirements, project, extras, }) } /// Resolve the [`RequiresDist`] metadata for a given source tree. Attempts to resolve the /// requirements without building the distribution, even if the project contains (e.g.) a /// dynamic version since, critically, we don't need to install the package itself; only its /// dependencies. async fn resolve_requires_dist(&self, source_tree: &SourceTree) -> Result<RequiresDist> { // Convert to a buildable source. let path = fs_err::canonicalize(source_tree.path()).with_context(|| { format!( "Failed to canonicalize path to source tree: {}", source_tree.path().user_display() ) })?; let path = path.parent().ok_or_else(|| { anyhow::anyhow!( "The file `{}` appears to be a `pyproject.toml`, `setup.py`, or `setup.cfg` file, which must be in a directory", path.user_display() ) })?; // If the path is a `pyproject.toml`, attempt to extract the requirements statically. The // distribution database will do this too, but we can be even more aggressive here since we // _only_ need the requirements. So, for example, even if the version is dynamic, we can // still extract the requirements without performing a build, unlike in the database where // we typically construct a "complete" metadata object. if let Some(pyproject_toml) = source_tree.pyproject_toml() { if let Some(metadata) = self.database.requires_dist(path, pyproject_toml).await? { return Ok(metadata); } } let Ok(url) = Url::from_directory_path(path).map(DisplaySafeUrl::from_url) else { return Err(anyhow::anyhow!("Failed to convert path to URL")); }; let source = SourceUrl::Directory(DirectorySourceUrl { url: &url, install_path: Cow::Borrowed(path), editable: None, }); // Determine the hash policy. Since we don't have a package name, we perform a // manual match. let hashes = match self.hasher { HashStrategy::None => HashPolicy::None, HashStrategy::Generate(mode) => HashPolicy::Generate(*mode), HashStrategy::Verify(_) => HashPolicy::Generate(HashGeneration::All), HashStrategy::Require(_) => { return Err(anyhow::anyhow!( "Hash-checking is not supported for local directories: {}", path.user_display() )); } }; // Fetch the metadata for the distribution. let metadata = { let id = VersionId::from_url(source.url()); if self.index.distributions().register(id.clone()) { // Run the PEP 517 build process to extract metadata from the source distribution. let source = BuildableSource::Url(source); let archive = self.database.build_wheel_metadata(&source, hashes).await?; let metadata = archive.metadata.clone(); // Insert the metadata into the index. self.index .distributions() .done(id, Arc::new(MetadataResponse::Found(archive))); metadata } else { let response = self .index .distributions() .wait(&id) .await .expect("missing value for registered task"); let MetadataResponse::Found(archive) = &*response else { panic!("Failed to find metadata for: {}", path.user_display()); }; archive.metadata.clone() } }; Ok(RequiresDist::from(metadata)) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/upgrade.rs
crates/uv-requirements/src/upgrade.rs
use std::path::Path; use anyhow::Result; use uv_configuration::Upgrade; use uv_fs::CWD; use uv_git::ResolvedRepositoryReference; use uv_requirements_txt::RequirementsTxt; use uv_resolver::{Lock, LockError, Preference, PreferenceError, PylockToml, PylockTomlErrorKind}; #[derive(Debug, Default)] pub struct LockedRequirements { /// The pinned versions from the lockfile. pub preferences: Vec<Preference>, /// The pinned Git SHAs from the lockfile. pub git: Vec<ResolvedRepositoryReference>, } impl LockedRequirements { /// Create a [`LockedRequirements`] from a list of preferences. pub fn from_preferences(preferences: Vec<Preference>) -> Self { Self { preferences, ..Self::default() } } } /// Load the preferred requirements from an existing `requirements.txt`, applying the upgrade strategy. pub async fn read_requirements_txt( output_file: &Path, upgrade: &Upgrade, ) -> Result<Vec<Preference>> { // As an optimization, skip reading the lockfile is we're upgrading all packages anyway. if upgrade.is_all() { return Ok(Vec::new()); } // Parse the requirements from the lockfile. let requirements_txt = RequirementsTxt::parse(output_file, &*CWD).await?; // Map each entry in the lockfile to a preference. let preferences = requirements_txt .requirements .into_iter() .map(Preference::from_entry) .filter_map(Result::transpose) .collect::<Result<Vec<_>, PreferenceError>>()?; // Apply the upgrade strategy to the requirements. Ok(match upgrade { // Respect all pinned versions from the existing lockfile. Upgrade::None => preferences, // Ignore all pinned versions from the existing lockfile. Upgrade::All => vec![], // Ignore pinned versions for the specified packages. Upgrade::Packages(packages) => preferences .into_iter() .filter(|preference| !packages.contains_key(preference.name())) .collect(), }) } /// Load the preferred requirements from an existing lockfile, applying the upgrade strategy. pub fn read_lock_requirements( lock: &Lock, install_path: &Path, upgrade: &Upgrade, ) -> Result<LockedRequirements, LockError> { // As an optimization, skip iterating over the lockfile is we're upgrading all packages anyway. if upgrade.is_all() { return Ok(LockedRequirements::default()); } let mut preferences = Vec::new(); let mut git = Vec::new(); for package in lock.packages() { // Skip the distribution if it's not included in the upgrade strategy. if upgrade.contains(package.name()) { continue; } // Map each entry in the lockfile to a preference. if let Some(preference) = Preference::from_lock(package, install_path)? { preferences.push(preference); } // Map each entry in the lockfile to a Git SHA. if let Some(git_ref) = package.as_git_ref()? { git.push(git_ref); } } Ok(LockedRequirements { preferences, git }) } /// Load the preferred requirements from an existing `pylock.toml` file, applying the upgrade strategy. pub async fn read_pylock_toml_requirements( output_file: &Path, upgrade: &Upgrade, ) -> Result<LockedRequirements, PylockTomlErrorKind> { // As an optimization, skip iterating over the lockfile is we're upgrading all packages anyway. if upgrade.is_all() { return Ok(LockedRequirements::default()); } // Read the `pylock.toml` from disk, and deserialize it from TOML. let content = fs_err::tokio::read_to_string(&output_file).await?; let lock = toml::from_str::<PylockToml>(&content)?; let mut preferences = Vec::new(); let mut git = Vec::new(); for package in &lock.packages { // Skip the distribution if it's not included in the upgrade strategy. if upgrade.contains(&package.name) { continue; } // Map each entry in the lockfile to a preference. if let Some(preference) = Preference::from_pylock_toml(package)? { preferences.push(preference); } // Map each entry in the lockfile to a Git SHA. if let Some(git_ref) = package.as_git_ref() { git.push(git_ref); } } Ok(LockedRequirements { preferences, git }) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/lookahead.rs
crates/uv-requirements/src/lookahead.rs
use std::{collections::VecDeque, sync::Arc}; use futures::StreamExt; use futures::stream::FuturesUnordered; use rustc_hash::FxHashSet; use tracing::trace; use uv_configuration::{Constraints, Overrides}; use uv_distribution::{DistributionDatabase, Reporter}; use uv_distribution_types::{Dist, DistributionMetadata, Requirement, RequirementSource}; use uv_resolver::{InMemoryIndex, MetadataResponse, ResolverEnvironment}; use uv_types::{BuildContext, HashStrategy, RequestedRequirements}; use crate::{Error, required_dist}; /// A resolver for resolving lookahead requirements from direct URLs. /// /// The resolver extends certain privileges to "first-party" requirements. For example, first-party /// requirements are allowed to contain direct URL references. /// /// The lookahead resolver resolves requirements recursively for direct URLs, so that the resolver /// can treat them as first-party dependencies for the purpose of analyzing their specifiers. /// Namely, this enables transitive direct URL dependencies, since we can tell the resolver all of /// the known URLs upfront. /// /// This strategy relies on the assumption that direct URLs are only introduced by other direct /// URLs, and not by PyPI dependencies. (If a direct URL _is_ introduced by a PyPI dependency, then /// the resolver will (correctly) reject it later on with a conflict error.) Further, it's only /// possible because a direct URL points to a _specific_ version of a package, and so we know that /// any correct resolution will _have_ to include it (unlike with PyPI dependencies, which may /// require a range of versions and backtracking). pub struct LookaheadResolver<'a, Context: BuildContext> { /// The direct requirements for the project. requirements: &'a [Requirement], /// The constraints for the project. constraints: &'a Constraints, /// The overrides for the project. overrides: &'a Overrides, /// The required hashes for the project. hasher: &'a HashStrategy, /// The in-memory index for resolving dependencies. index: &'a InMemoryIndex, /// The database for fetching and building distributions. database: DistributionDatabase<'a, Context>, } impl<'a, Context: BuildContext> LookaheadResolver<'a, Context> { /// Instantiate a new [`LookaheadResolver`] for a given set of requirements. pub fn new( requirements: &'a [Requirement], constraints: &'a Constraints, overrides: &'a Overrides, hasher: &'a HashStrategy, index: &'a InMemoryIndex, database: DistributionDatabase<'a, Context>, ) -> Self { Self { requirements, constraints, overrides, hasher, index, database, } } /// Set the [`Reporter`] to use for this resolver. #[must_use] pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self { Self { database: self.database.with_reporter(reporter), ..self } } /// Resolve the requirements from the provided source trees. /// /// When the environment is not given, this treats all marker expressions /// that reference the environment as true. In other words, it does /// environment independent expression evaluation. (Which in turn devolves /// to "only evaluate marker expressions that reference an extra name.") pub async fn resolve( self, env: &ResolverEnvironment, ) -> Result<Vec<RequestedRequirements>, Error> { let mut results = Vec::new(); let mut futures = FuturesUnordered::new(); let mut seen = FxHashSet::default(); // Queue up the initial requirements. let mut queue: VecDeque<_> = self .constraints .apply(self.overrides.apply(self.requirements)) .filter(|requirement| requirement.evaluate_markers(env.marker_environment(), &[])) .map(|requirement| (*requirement).clone()) .collect(); while !queue.is_empty() || !futures.is_empty() { while let Some(requirement) = queue.pop_front() { if !matches!(requirement.source, RequirementSource::Registry { .. }) { if seen.insert(requirement.clone()) { futures.push(self.lookahead(requirement)); } } } while let Some(result) = futures.next().await { if let Some(lookahead) = result? { for requirement in self .constraints .apply(self.overrides.apply(lookahead.requirements())) { if requirement .evaluate_markers(env.marker_environment(), lookahead.extras()) { queue.push_back((*requirement).clone()); } } results.push(lookahead); } } } Ok(results) } /// Infer the package name for a given "unnamed" requirement. async fn lookahead( &self, requirement: Requirement, ) -> Result<Option<RequestedRequirements>, Error> { trace!("Performing lookahead for {requirement}"); // Determine whether the requirement represents a local distribution and convert to a // buildable distribution. let Some(dist) = required_dist(&requirement)? else { return Ok(None); }; // Consider the dependencies to be "direct" if the requirement is a local source tree. let direct = if let Dist::Source(source_dist) = &dist { source_dist.as_path().is_some_and(std::path::Path::is_dir) } else { false }; // Fetch the metadata for the distribution. let metadata = { let id = dist.version_id(); if self.index.distributions().register(id.clone()) { // Run the PEP 517 build process to extract metadata from the source distribution. let archive = self .database .get_or_build_wheel_metadata(&dist, self.hasher.get(&dist)) .await .map_err(|err| Error::from_dist(dist, err))?; let metadata = archive.metadata.clone(); // Insert the metadata into the index. self.index .distributions() .done(id, Arc::new(MetadataResponse::Found(archive))); metadata } else { let response = self .index .distributions() .wait(&id) .await .expect("missing value for registered task"); let MetadataResponse::Found(archive) = &*response else { panic!("Failed to find metadata for: {requirement}"); }; archive.metadata.clone() } }; // Respect recursive extras by propagating the source extras to the dependencies. let requires_dist = Box::into_iter(metadata.requires_dist) .chain( metadata .dependency_groups .into_iter() .filter_map(|(group, dependencies)| { if requirement.groups.contains(&group) { Some(dependencies) } else { None } }) .flatten(), ) .map(|dependency| { if dependency.name == requirement.name { Requirement { source: requirement.source.clone(), ..dependency } } else { dependency } }) .collect(); // Return the requirements from the metadata. Ok(Some(RequestedRequirements::new( requirement.extras, requires_dist, direct, ))) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/unnamed.rs
crates/uv-requirements/src/unnamed.rs
use std::borrow::Cow; use std::path::Path; use std::str::FromStr; use std::sync::Arc; use configparser::ini::Ini; use futures::{TryStreamExt, stream::FuturesOrdered}; use serde::Deserialize; use tracing::debug; use url::Host; use uv_distribution::{DistributionDatabase, Reporter}; use uv_distribution_filename::{DistExtension, SourceDistFilename, WheelFilename}; use uv_distribution_types::{ BuildableSource, DirectSourceUrl, DirectorySourceUrl, GitSourceUrl, PathSourceUrl, RemoteSource, Requirement, SourceUrl, VersionId, }; use uv_normalize::PackageName; use uv_pep508::{UnnamedRequirement, VersionOrUrl}; use uv_pypi_types::Metadata10; use uv_pypi_types::{ParsedUrl, VerbatimParsedUrl}; use uv_resolver::{InMemoryIndex, MetadataResponse}; use uv_types::{BuildContext, HashStrategy}; use crate::Error; /// Like [`RequirementsSpecification`], but with concrete names for all requirements. pub struct NamedRequirementsResolver<'a, Context: BuildContext> { /// Whether to check hashes for distributions. hasher: &'a HashStrategy, /// The in-memory index for resolving dependencies. index: &'a InMemoryIndex, /// The database for fetching and building distributions. database: DistributionDatabase<'a, Context>, } impl<'a, Context: BuildContext> NamedRequirementsResolver<'a, Context> { /// Instantiate a new [`NamedRequirementsResolver`]. pub fn new( hasher: &'a HashStrategy, index: &'a InMemoryIndex, database: DistributionDatabase<'a, Context>, ) -> Self { Self { hasher, index, database, } } /// Set the [`Reporter`] to use for this resolver. #[must_use] pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self { Self { database: self.database.with_reporter(reporter), ..self } } /// Resolve any unnamed requirements in the specification. pub async fn resolve( self, requirements: impl Iterator<Item = UnnamedRequirement<VerbatimParsedUrl>>, ) -> Result<Vec<Requirement>, Error> { let Self { hasher, index, database, } = self; requirements .map(async |requirement| { Self::resolve_requirement(requirement, hasher, index, &database) .await .map(Requirement::from) }) .collect::<FuturesOrdered<_>>() .try_collect() .await } /// Infer the package name for a given "unnamed" requirement. async fn resolve_requirement( requirement: UnnamedRequirement<VerbatimParsedUrl>, hasher: &HashStrategy, index: &InMemoryIndex, database: &DistributionDatabase<'a, Context>, ) -> Result<uv_pep508::Requirement<VerbatimParsedUrl>, Error> { // If the requirement is a wheel, extract the package name from the wheel filename. // // Ex) `anyio-4.3.0-py3-none-any.whl` if Path::new(requirement.url.verbatim.path()) .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("whl")) { let filename = WheelFilename::from_str(&requirement.url.verbatim.filename()?)?; return Ok(uv_pep508::Requirement { name: filename.name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } // If the requirement is a source archive, try to extract the package name from the archive // filename. This isn't guaranteed to work. // // Ex) `anyio-4.3.0.tar.gz` if let Some(filename) = requirement .url .verbatim .filename() .ok() .and_then(|filename| SourceDistFilename::parsed_normalized_filename(&filename).ok()) { // But ignore GitHub archives, like: // https://github.com/python/mypy/archive/refs/heads/release-1.11.zip // // These have auto-generated filenames that will almost never match the package name. if requirement.url.verbatim.host() == Some(Host::Domain("github.com")) && requirement .url .verbatim .path_segments() .is_some_and(|mut path_segments| { path_segments.any(|segment| segment == "archive") }) { debug!( "Rejecting inferred name from GitHub archive: {}", requirement.url.verbatim ); } else { return Ok(uv_pep508::Requirement { name: filename.name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } } let source = match &requirement.url.parsed_url { // If the path points to a directory, attempt to read the name from static metadata. ParsedUrl::Directory(parsed_directory_url) => { // Attempt to read a `PKG-INFO` from the directory. if let Some(metadata) = fs_err::read(parsed_directory_url.install_path.join("PKG-INFO")) .ok() .and_then(|contents| Metadata10::parse_pkg_info(&contents).ok()) { debug!( "Found PKG-INFO metadata for {path} ({name})", path = parsed_directory_url.install_path.display(), name = metadata.name ); return Ok(uv_pep508::Requirement { name: metadata.name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } // Attempt to read a `pyproject.toml` file. let project_path = parsed_directory_url.install_path.join("pyproject.toml"); if let Some(pyproject) = fs_err::read_to_string(project_path) .ok() .and_then(|contents| toml::from_str::<PyProjectToml>(&contents).ok()) { // Read PEP 621 metadata from the `pyproject.toml`. if let Some(project) = pyproject.project { debug!( "Found PEP 621 metadata for {path} in `pyproject.toml` ({name})", path = parsed_directory_url.install_path.display(), name = project.name ); return Ok(uv_pep508::Requirement { name: project.name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } // Read Poetry-specific metadata from the `pyproject.toml`. if let Some(tool) = pyproject.tool { if let Some(poetry) = tool.poetry { if let Some(name) = poetry.name { debug!( "Found Poetry metadata for {path} in `pyproject.toml` ({name})", path = parsed_directory_url.install_path.display(), name = name ); return Ok(uv_pep508::Requirement { name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } } } } // Attempt to read a `setup.cfg` from the directory. if let Some(setup_cfg) = fs_err::read_to_string(parsed_directory_url.install_path.join("setup.cfg")) .ok() .and_then(|contents| { let mut ini = Ini::new_cs(); ini.set_multiline(true); ini.read(contents).ok() }) { if let Some(section) = setup_cfg.get("metadata") { if let Some(Some(name)) = section.get("name") { if let Ok(name) = PackageName::from_str(name) { debug!( "Found setuptools metadata for {path} in `setup.cfg` ({name})", path = parsed_directory_url.install_path.display(), name = name ); return Ok(uv_pep508::Requirement { name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }); } } } } SourceUrl::Directory(DirectorySourceUrl { url: &requirement.url.verbatim, install_path: Cow::Borrowed(&parsed_directory_url.install_path), editable: parsed_directory_url.editable, }) } ParsedUrl::Path(parsed_path_url) => { let ext = match parsed_path_url.ext { DistExtension::Source(ext) => ext, DistExtension::Wheel => unreachable!(), }; SourceUrl::Path(PathSourceUrl { url: &requirement.url.verbatim, path: Cow::Borrowed(&parsed_path_url.install_path), ext, }) } ParsedUrl::Archive(parsed_archive_url) => { let ext = match parsed_archive_url.ext { DistExtension::Source(ext) => ext, DistExtension::Wheel => unreachable!(), }; SourceUrl::Direct(DirectSourceUrl { url: &parsed_archive_url.url, subdirectory: parsed_archive_url.subdirectory.as_deref(), ext, }) } ParsedUrl::Git(parsed_git_url) => SourceUrl::Git(GitSourceUrl { url: &requirement.url.verbatim, git: &parsed_git_url.url, subdirectory: parsed_git_url.subdirectory.as_deref(), }), }; // Fetch the metadata for the distribution. let name = { let id = VersionId::from_url(source.url()); if let Some(archive) = index .distributions() .get(&id) .as_deref() .and_then(|response| { if let MetadataResponse::Found(archive) = response { Some(archive) } else { None } }) { // If the metadata is already in the index, return it. archive.metadata.name.clone() } else { // Run the PEP 517 build process to extract metadata from the source distribution. let hashes = hasher.get_url(source.url()); let source = BuildableSource::Url(source); let archive = database.build_wheel_metadata(&source, hashes).await?; let name = archive.metadata.name.clone(); // Insert the metadata into the index. index .distributions() .done(id, Arc::new(MetadataResponse::Found(archive))); name } }; Ok(uv_pep508::Requirement { name, extras: requirement.extras, version_or_url: Some(VersionOrUrl::Url(requirement.url)), marker: requirement.marker, origin: requirement.origin, }) } } /// A pyproject.toml as specified in PEP 517. #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct PyProjectToml { project: Option<Project>, tool: Option<Tool>, } #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct Project { name: PackageName, } #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct Tool { poetry: Option<ToolPoetry>, } #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct ToolPoetry { name: Option<PackageName>, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/specification.rs
crates/uv-requirements/src/specification.rs
//! Collecting the requirements to compile, sync or install. //! //! # `requirements.txt` format //! //! The `requirements.txt` format (also known as `requirements.in`) is static except for the //! possibility of making network requests. //! //! All entries are stored as `requirements` and `editables` or `constraints` depending on the kind //! of inclusion (`uv pip install -r` and `uv pip compile` vs. `uv pip install -c` and //! `uv pip compile -c`). //! //! # `pyproject.toml` and directory source. //! //! `pyproject.toml` files come in two forms: PEP 621 compliant with static dependencies and non-PEP 621 //! compliant or PEP 621 compliant with dynamic metadata. There are different ways how the requirements are evaluated: //! * `uv pip install -r pyproject.toml` or `uv pip compile requirements.in`: The `pyproject.toml` //! must be valid (in other circumstances we allow invalid `dependencies` e.g. for hatch's //! relative path support), but it can be dynamic. We set the `project` from the `name` entry. If it is static, we add //! all `dependencies` from the pyproject.toml as `requirements` (and drop the directory). If it //! is dynamic, we add the directory to `source_trees`. //! * `uv pip install .` in a directory with `pyproject.toml` or `uv pip compile requirements.in` //! where the `requirements.in` points to that directory: The directory is listed in //! `requirements`. The lookahead resolver reads the static metadata from `pyproject.toml` if //! available, otherwise it calls PEP 517 to resolve. //! * `uv pip install -e`: We add the directory in `editables` instead of `requirements`. The //! lookahead resolver resolves it the same. //! * `setup.py` or `setup.cfg` instead of `pyproject.toml`: Directory is an entry in //! `source_trees`. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use rustc_hash::FxHashSet; use tracing::instrument; use url::Url; use uv_cache_key::CanonicalUrl; use uv_client::BaseClientBuilder; use uv_configuration::{DependencyGroups, NoBinary, NoBuild}; use uv_distribution_types::{Index, Requirement}; use uv_distribution_types::{ IndexUrl, NameRequirementSpecification, UnresolvedRequirement, UnresolvedRequirementSpecification, }; use uv_fs::{CWD, Simplified}; use uv_normalize::{ExtraName, PackageName, PipGroupName}; use uv_pypi_types::PyProjectToml; use uv_redacted::DisplaySafeUrl; use uv_requirements_txt::{RequirementsTxt, RequirementsTxtRequirement, SourceCache}; use uv_scripts::Pep723Metadata; use uv_warnings::warn_user; use crate::{RequirementsSource, SourceTree}; #[derive(Debug, Default, Clone)] pub struct RequirementsSpecification { /// The name of the project specifying requirements. pub project: Option<PackageName>, /// The requirements for the project. pub requirements: Vec<UnresolvedRequirementSpecification>, /// The constraints for the project. pub constraints: Vec<NameRequirementSpecification>, /// The overrides for the project. pub overrides: Vec<UnresolvedRequirementSpecification>, /// The excludes for the project. pub excludes: Vec<PackageName>, /// The `pylock.toml` file from which to extract the resolution. pub pylock: Option<PathBuf>, /// The source trees from which to extract requirements. pub source_trees: Vec<SourceTree>, /// The groups to use for `source_trees` pub groups: BTreeMap<PathBuf, DependencyGroups>, /// The extras used to collect requirements. pub extras: FxHashSet<ExtraName>, /// The index URL to use for fetching packages. pub index_url: Option<IndexUrl>, /// The extra index URLs to use for fetching packages. pub extra_index_urls: Vec<IndexUrl>, /// Whether to disallow index usage. pub no_index: bool, /// The `--find-links` locations to use for fetching packages. pub find_links: Vec<IndexUrl>, /// The `--no-binary` flags to enforce when selecting distributions. pub no_binary: NoBinary, /// The `--no-build` flags to enforce when selecting distributions. pub no_build: NoBuild, } impl RequirementsSpecification { /// Read the requirements and constraints from a source. #[instrument(skip_all, level = tracing::Level::DEBUG, fields(source = % source))] pub async fn from_source( source: &RequirementsSource, client_builder: &BaseClientBuilder<'_>, ) -> Result<Self> { Self::from_source_with_cache(source, client_builder, &mut SourceCache::default()).await } /// Create a [`RequirementsSpecification`] from PEP 723 script metadata. fn from_pep723_metadata(metadata: &Pep723Metadata) -> Self { let requirements = metadata .dependencies .as_ref() .map(|dependencies| { dependencies .iter() .map(|dependency| { UnresolvedRequirementSpecification::from(Requirement::from( dependency.to_owned(), )) }) .collect::<Vec<UnresolvedRequirementSpecification>>() }) .unwrap_or_default(); if let Some(tool_uv) = metadata.tool.as_ref().and_then(|tool| tool.uv.as_ref()) { let constraints = tool_uv .constraint_dependencies .as_ref() .map(|dependencies| { dependencies .iter() .map(|dependency| { NameRequirementSpecification::from(Requirement::from( dependency.to_owned(), )) }) .collect::<Vec<NameRequirementSpecification>>() }) .unwrap_or_default(); let overrides = tool_uv .override_dependencies .as_ref() .map(|dependencies| { dependencies .iter() .map(|dependency| { UnresolvedRequirementSpecification::from(Requirement::from( dependency.to_owned(), )) }) .collect::<Vec<UnresolvedRequirementSpecification>>() }) .unwrap_or_default(); Self { requirements, constraints, overrides, index_url: tool_uv .top_level .index_url .as_ref() .map(|index| Index::from(index.clone()).url), extra_index_urls: tool_uv .top_level .extra_index_url .as_ref() .into_iter() .flat_map(|urls| urls.iter().map(|index| Index::from(index.clone()).url)) .collect(), no_index: tool_uv.top_level.no_index.unwrap_or_default(), find_links: tool_uv .top_level .find_links .as_ref() .into_iter() .flat_map(|urls| urls.iter().map(|index| Index::from(index.clone()).url)) .collect(), no_binary: NoBinary::from_args( tool_uv.top_level.no_binary, tool_uv .top_level .no_binary_package .clone() .unwrap_or_default(), ), no_build: NoBuild::from_args( tool_uv.top_level.no_build, tool_uv .top_level .no_build_package .clone() .unwrap_or_default(), ), ..Self::default() } } else { Self { requirements, ..Self::default() } } } /// Create a [`RequirementsSpecification`] from a parsed `requirements.txt` file. fn from_requirements_txt(requirements_txt: RequirementsTxt) -> Self { Self { requirements: requirements_txt .requirements .into_iter() .map(UnresolvedRequirementSpecification::from) .chain( requirements_txt .editables .into_iter() .map(UnresolvedRequirementSpecification::from), ) .collect(), constraints: requirements_txt .constraints .into_iter() .map(Requirement::from) .map(NameRequirementSpecification::from) .collect(), index_url: requirements_txt.index_url.map(IndexUrl::from), extra_index_urls: requirements_txt .extra_index_urls .into_iter() .map(IndexUrl::from) .collect(), no_index: requirements_txt.no_index, find_links: requirements_txt .find_links .into_iter() .map(IndexUrl::from) .collect(), no_binary: requirements_txt.no_binary, no_build: requirements_txt.only_binary, ..Self::default() } } /// Read the requirements and constraints from a source, using a cache for file contents. #[instrument(skip_all, level = tracing::Level::DEBUG, fields(source = % source))] pub async fn from_source_with_cache( source: &RequirementsSource, client_builder: &BaseClientBuilder<'_>, cache: &mut SourceCache, ) -> Result<Self> { Ok(match source { RequirementsSource::Package(requirement) => Self { requirements: vec![UnresolvedRequirementSpecification::from( requirement.clone(), )], ..Self::default() }, RequirementsSource::Editable(requirement) => Self { requirements: vec![UnresolvedRequirementSpecification::from( requirement.clone().into_editable()?, )], ..Self::default() }, RequirementsSource::RequirementsTxt(path) => { if !(path.starts_with("http://") || path.starts_with("https://") || path.exists()) { return Err(anyhow::anyhow!("File not found: `{}`", path.user_display())); } let requirements_txt = RequirementsTxt::parse_with_cache(path, &*CWD, client_builder, cache).await?; if requirements_txt == RequirementsTxt::default() { warn_user!( "Requirements file `{}` does not contain any dependencies", path.user_display() ); } Self::from_requirements_txt(requirements_txt) } RequirementsSource::PyprojectToml(path) => { let content = match fs_err::tokio::read_to_string(&path).await { Ok(content) => content, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { return Err(anyhow::anyhow!("File not found: `{}`", path.user_display())); } Err(err) => { return Err(anyhow::anyhow!( "Failed to read `{}`: {}", path.user_display(), err )); } }; let pyproject_toml = toml::from_str::<PyProjectToml>(&content) .with_context(|| format!("Failed to parse: `{}`", path.user_display()))?; Self { source_trees: vec![SourceTree::PyProjectToml(path.clone(), pyproject_toml)], ..Self::default() } } RequirementsSource::Pep723Script(path) => { let content = if let Some(content) = cache.get(path.as_path()) { content.clone() } else { let content = read_file(path, client_builder).await?; cache.insert(path.clone(), content.clone()); content }; let metadata = match Pep723Metadata::parse(content.as_bytes()) { Ok(Some(script)) => script, Ok(None) => { return Err(anyhow::anyhow!( "`{}` does not contain inline script metadata", path.user_display(), )); } Err(err) => return Err(err.into()), }; Self::from_pep723_metadata(&metadata) } RequirementsSource::SetupPy(path) => { if !path.is_file() { return Err(anyhow::anyhow!("File not found: `{}`", path.user_display())); } Self { source_trees: vec![SourceTree::SetupPy(path.clone())], ..Self::default() } } RequirementsSource::SetupCfg(path) => { if !path.is_file() { return Err(anyhow::anyhow!("File not found: `{}`", path.user_display())); } Self { source_trees: vec![SourceTree::SetupCfg(path.clone())], ..Self::default() } } RequirementsSource::PylockToml(path) => { if !(path.starts_with("http://") || path.starts_with("https://") || path.exists()) { return Err(anyhow::anyhow!("File not found: `{}`", path.user_display())); } Self { pylock: Some(path.clone()), ..Self::default() } } RequirementsSource::EnvironmentYml(path) => { return Err(anyhow::anyhow!( "Conda environment files (i.e., `{}`) are not supported", path.user_display() )); } RequirementsSource::Extensionless(path) => { let content = if let Some(content) = cache.get(path.as_path()) { content.clone() } else { let content = read_file(path, client_builder).await?; cache.insert(path.clone(), content.clone()); content }; // Detect if it's a PEP 723 script. if let Some(metadata) = Pep723Metadata::parse(content.as_bytes())? { Self::from_pep723_metadata(&metadata) } else { // If it's not a PEP 723 script, assume it's a `requirements.txt` file. let requirements_txt = RequirementsTxt::parse_str(&content, &path, &*CWD, client_builder, cache) .await?; if requirements_txt == RequirementsTxt::default() { if path == Path::new("-") { warn_user!("No dependencies found in stdin"); } else { warn_user!( "Requirements file `{}` does not contain any dependencies", path.user_display() ); } } Self::from_requirements_txt(requirements_txt) } } }) } /// Read the combined requirements and constraints from a set of sources. pub async fn from_sources( requirements: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], excludes: &[RequirementsSource], groups: Option<&GroupsSpecification>, client_builder: &BaseClientBuilder<'_>, ) -> Result<Self> { let mut spec = Self::default(); let mut cache = SourceCache::default(); // Disallow `pylock.toml` files as constraints. if let Some(pylock_toml) = constraints.iter().find_map(|source| { if let RequirementsSource::PylockToml(path) = source { Some(path) } else { None } }) { return Err(anyhow::anyhow!( "Cannot use `{}` as a constraint file", pylock_toml.user_display() )); } // Disallow `pylock.toml` files as overrides. if let Some(pylock_toml) = overrides.iter().find_map(|source| { if let RequirementsSource::PylockToml(path) = source { Some(path) } else { None } }) { return Err(anyhow::anyhow!( "Cannot use `{}` as an override file", pylock_toml.user_display() )); } // Disallow `pylock.toml` files as excludes. if let Some(pylock_toml) = excludes.iter().find_map(|source| { if let RequirementsSource::PylockToml(path) = source { Some(path) } else { None } }) { return Err(anyhow::anyhow!( "Cannot use `{}` as an exclude file", pylock_toml.user_display() )); } // If we have a `pylock.toml`, don't allow additional requirements, constraints, or // overrides. if let Some(pylock_toml) = requirements.iter().find_map(|source| { if let RequirementsSource::PylockToml(path) = source { Some(path) } else { None } }) { if requirements .iter() .any(|source| !matches!(source, RequirementsSource::PylockToml(..))) { return Err(anyhow::anyhow!( "Cannot specify additional requirements alongside a `pylock.toml` file", )); } if !constraints.is_empty() { return Err(anyhow::anyhow!( "Cannot specify constraints with a `pylock.toml` file" )); } if !overrides.is_empty() { return Err(anyhow::anyhow!( "Cannot specify overrides with a `pylock.toml` file" )); } // If we have a `pylock.toml`, disallow specifying paths for groups; instead, require // that all groups refer to the `pylock.toml` file. if let Some(groups) = groups { let mut names = Vec::new(); for group in &groups.groups { if group.path.is_some() { return Err(anyhow::anyhow!( "Cannot specify paths for groups with a `pylock.toml` file; all groups must refer to the `pylock.toml` file" )); } names.push(group.name.clone()); } if !names.is_empty() { spec.groups.insert( pylock_toml.clone(), DependencyGroups::from_args( false, false, false, Vec::new(), Vec::new(), false, names, false, ), ); } } } else if let Some(groups) = groups { // pip `--group` flags specify their own sources, which we need to process here. // First, we collect all groups by their path. let mut groups_by_path = BTreeMap::new(); for group in &groups.groups { // If there's no path provided, expect a pyproject.toml in the project-dir // (Which is typically the current working directory, matching pip's behaviour) let pyproject_path = group .path .clone() .unwrap_or_else(|| groups.root.join("pyproject.toml")); groups_by_path .entry(pyproject_path) .or_insert_with(Vec::new) .push(group.name.clone()); } let mut group_specs = BTreeMap::new(); for (path, groups) in groups_by_path { let group_spec = DependencyGroups::from_args( false, false, false, Vec::new(), Vec::new(), false, groups, false, ); group_specs.insert(path, group_spec); } spec.groups = group_specs; } // Resolve sources into specifications so we know their `source_tree`. let mut requirement_sources = Vec::new(); for source in requirements { let source = Self::from_source_with_cache(source, client_builder, &mut cache).await?; requirement_sources.push(source); } // Read all requirements, and keep track of all requirements _and_ constraints. // A `requirements.txt` can contain a `-c constraints.txt` directive within it, so reading // a requirements file can also add constraints. for source in requirement_sources { spec.requirements.extend(source.requirements); spec.constraints.extend(source.constraints); spec.overrides.extend(source.overrides); spec.extras.extend(source.extras); spec.source_trees.extend(source.source_trees); // Allow at most one `pylock.toml`. if let Some(pylock) = source.pylock { if let Some(existing) = spec.pylock { return Err(anyhow::anyhow!( "Multiple `pylock.toml` files specified: `{}` vs. `{}`", existing.user_display(), pylock.user_display() )); } spec.pylock = Some(pylock); } // Use the first project name discovered. if spec.project.is_none() { spec.project = source.project; } if let Some(index_url) = source.index_url { if let Some(existing) = spec.index_url { if CanonicalUrl::new(index_url.url()) != CanonicalUrl::new(existing.url()) { return Err(anyhow::anyhow!( "Multiple index URLs specified: `{existing}` vs. `{index_url}`", )); } } spec.index_url = Some(index_url); } spec.no_index |= source.no_index; spec.extra_index_urls.extend(source.extra_index_urls); spec.find_links.extend(source.find_links); spec.no_binary.extend(source.no_binary); spec.no_build.extend(source.no_build); } // Read all constraints, treating both requirements _and_ constraints as constraints. // Overrides are ignored. for source in constraints { let source = Self::from_source_with_cache(source, client_builder, &mut cache).await?; for entry in source.requirements { match entry.requirement { UnresolvedRequirement::Named(requirement) => { spec.constraints.push(NameRequirementSpecification { requirement, hashes: entry.hashes, }); } UnresolvedRequirement::Unnamed(requirement) => { return Err(anyhow::anyhow!( "Unnamed requirements are not allowed as constraints (found: `{requirement}`)" )); } } } spec.constraints.extend(source.constraints); if let Some(index_url) = source.index_url { if let Some(existing) = spec.index_url { if CanonicalUrl::new(index_url.url()) != CanonicalUrl::new(existing.url()) { return Err(anyhow::anyhow!( "Multiple index URLs specified: `{existing}` vs. `{index_url}`", )); } } spec.index_url = Some(index_url); } spec.no_index |= source.no_index; spec.extra_index_urls.extend(source.extra_index_urls); spec.find_links.extend(source.find_links); spec.no_binary.extend(source.no_binary); spec.no_build.extend(source.no_build); } // Read all overrides, treating both requirements _and_ overrides as overrides. // Constraints are ignored. for source in overrides { let source = Self::from_source_with_cache(source, client_builder, &mut cache).await?; spec.overrides.extend(source.requirements); spec.overrides.extend(source.overrides); if let Some(index_url) = source.index_url { if let Some(existing) = spec.index_url { if CanonicalUrl::new(index_url.url()) != CanonicalUrl::new(existing.url()) { return Err(anyhow::anyhow!( "Multiple index URLs specified: `{existing}` vs. `{index_url}`", )); } } spec.index_url = Some(index_url); } spec.no_index |= source.no_index; spec.extra_index_urls.extend(source.extra_index_urls); spec.find_links.extend(source.find_links); spec.no_binary.extend(source.no_binary); spec.no_build.extend(source.no_build); } // Collect excludes. for source in excludes { let source = Self::from_source_with_cache(source, client_builder, &mut cache).await?; for req_spec in source.requirements { match req_spec.requirement { UnresolvedRequirement::Named(requirement) => { spec.excludes.push(requirement.name); } UnresolvedRequirement::Unnamed(requirement) => { return Err(anyhow::anyhow!( "Unnamed requirements are not allowed as exclusions (found: `{requirement}`)" )); } } } spec.excludes.extend(source.excludes.into_iter()); } Ok(spec) } /// Parse an individual package requirement. pub fn parse_package(name: &str) -> Result<UnresolvedRequirementSpecification> { let requirement = RequirementsTxtRequirement::parse(name, &*CWD, false) .with_context(|| format!("Failed to parse: `{name}`"))?; Ok(UnresolvedRequirementSpecification::from(requirement)) } /// Read the requirements from a set of sources. pub async fn from_simple_sources( requirements: &[RequirementsSource], client_builder: &BaseClientBuilder<'_>, ) -> Result<Self> { Self::from_sources(requirements, &[], &[], &[], None, client_builder).await } /// Initialize a [`RequirementsSpecification`] from a list of [`Requirement`]. pub fn from_requirements(requirements: Vec<Requirement>) -> Self { Self { requirements: requirements .into_iter() .map(UnresolvedRequirementSpecification::from) .collect(), ..Self::default() } } /// Initialize a [`RequirementsSpecification`] from a list of [`Requirement`], including /// constraints. pub fn from_constraints(requirements: Vec<Requirement>, constraints: Vec<Requirement>) -> Self { Self { requirements: requirements .into_iter() .map(UnresolvedRequirementSpecification::from) .collect(), constraints: constraints .into_iter() .map(NameRequirementSpecification::from) .collect(), ..Self::default() } } /// Initialize a [`RequirementsSpecification`] from a list of [`Requirement`], including /// constraints and overrides. pub fn from_overrides( requirements: Vec<Requirement>, constraints: Vec<Requirement>, overrides: Vec<Requirement>, ) -> Self { Self { requirements: requirements .into_iter() .map(UnresolvedRequirementSpecification::from) .collect(), constraints: constraints .into_iter() .map(NameRequirementSpecification::from) .collect(), overrides: overrides .into_iter() .map(UnresolvedRequirementSpecification::from) .collect(), ..Self::default() } } /// Return true if the specification does not include any requirements to install. pub fn is_empty(&self) -> bool { self.requirements.is_empty() && self.source_trees.is_empty() && self.overrides.is_empty() } } #[derive(Debug, Default, Clone)] pub struct GroupsSpecification { /// The path to the project root, relative to which the default `pyproject.toml` file is /// located. pub root: PathBuf, /// The enabled groups. pub groups: Vec<PipGroupName>, } /// Read the contents of a path, fetching over HTTP(S) if necessary. async fn read_file(path: &Path, client_builder: &BaseClientBuilder<'_>) -> Result<String> { // If the path is a URL, fetch it over HTTP(S). if path.starts_with("http://") || path.starts_with("https://") { // Only continue if we are absolutely certain no local file exists. // // We don't do this check on Windows since the file path would // be invalid anyway, and thus couldn't refer to a local file. if !cfg!(unix) || matches!(path.try_exists(), Ok(false)) { let url = DisplaySafeUrl::parse(&path.to_string_lossy())?; let client = client_builder.build(); let response = client .for_host(&url) .get(Url::from(url.clone())) .send() .await?; response.error_for_status_ref()?; return Ok(response.text().await?); } } // Read the file content. let content = uv_fs::read_to_string_transcode(path).await?; Ok(content) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements/src/sources.rs
crates/uv-requirements/src/sources.rs
use std::ffi::OsStr; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use console::Term; use uv_fs::{CWD, Simplified}; use uv_requirements_txt::RequirementsTxtRequirement; #[derive(Debug, Clone)] pub enum RequirementsSource { /// A package was provided on the command line (e.g., `pip install flask`). Package(RequirementsTxtRequirement), /// An editable path was provided on the command line (e.g., `pip install -e ../flask`). Editable(RequirementsTxtRequirement), /// Dependencies were provided via a PEP 723 script. Pep723Script(PathBuf), /// Dependencies were provided via a `pylock.toml` file. PylockToml(PathBuf), /// Dependencies were provided via a `requirements.txt` file (e.g., `pip install -r requirements.txt`). RequirementsTxt(PathBuf), /// Dependencies were provided via a `pyproject.toml` file (e.g., `pip-compile pyproject.toml`). PyprojectToml(PathBuf), /// Dependencies were provided via a `setup.py` file (e.g., `pip-compile setup.py`). SetupPy(PathBuf), /// Dependencies were provided via a `setup.cfg` file (e.g., `pip-compile setup.cfg`). SetupCfg(PathBuf), /// Dependencies were provided via an unsupported Conda `environment.yml` file (e.g., `pip install -r environment.yml`). EnvironmentYml(PathBuf), /// An extensionless file that could be either a PEP 723 script or a requirements.txt file. /// We detect the format when reading the file. Extensionless(PathBuf), } impl RequirementsSource { /// Parse a [`RequirementsSource`] from a [`PathBuf`]. The file type is determined by the file /// extension and, in some cases, the file contents. pub fn from_requirements_file(path: PathBuf) -> Result<Self> { if path.ends_with("pyproject.toml") { Ok(Self::PyprojectToml(path)) } else if path.ends_with("setup.py") { Ok(Self::SetupPy(path)) } else if path.ends_with("setup.cfg") { Ok(Self::SetupCfg(path)) } else if path.ends_with("environment.yml") { Ok(Self::EnvironmentYml(path)) } else if path .file_name() .is_some_and(|file_name| file_name.to_str().is_some_and(is_pylock_toml)) { Ok(Self::PylockToml(path)) } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("py") || ext.eq_ignore_ascii_case("pyw")) { Ok(Self::Pep723Script(path)) } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) { Err(anyhow::anyhow!( "`{}` is not a valid PEP 751 filename: expected TOML file to start with `pylock.` and end with `.toml` (e.g., `pylock.toml`, `pylock.dev.toml`)", path.user_display(), )) } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("txt") || ext.eq_ignore_ascii_case("in")) { Ok(Self::RequirementsTxt(path)) } else if path.extension().is_none() { // If we don't have an extension, mark it as extensionless so we can detect // the format later (either a PEP 723 script or a requirements.txt file). Ok(Self::Extensionless(path)) } else { Ok(Self::RequirementsTxt(path)) } } /// Parse a [`RequirementsSource`] from a `requirements.txt` file. pub fn from_requirements_txt(path: PathBuf) -> Result<Self> { if path == Path::new("-") { return Ok(Self::Extensionless(path)); } for file_name in ["pyproject.toml", "setup.py", "setup.cfg"] { if path.ends_with(file_name) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `{}` file, but requirements must be specified in `requirements.txt` format", path.user_display(), file_name )); } } if path .file_name() .and_then(OsStr::to_str) .is_some_and(is_pylock_toml) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `pylock.toml` file, but requirements must be specified in `requirements.txt` format", path.user_display(), )); } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) { return Err(anyhow::anyhow!( "The file `{}` appears to be a TOML file, but requirements must be specified in `requirements.txt` format", path.user_display(), )); } Ok(Self::RequirementsTxt(path)) } /// Parse a [`RequirementsSource`] from a `constraints.txt` file. pub fn from_constraints_txt(path: PathBuf) -> Result<Self> { if path == Path::new("-") { return Ok(Self::Extensionless(path)); } for file_name in ["pyproject.toml", "setup.py", "setup.cfg"] { if path.ends_with(file_name) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `{}` file, but constraints must be specified in `requirements.txt` format", path.user_display(), file_name )); } } if path .file_name() .and_then(OsStr::to_str) .is_some_and(is_pylock_toml) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `pylock.toml` file, but constraints must be specified in `requirements.txt` format", path.user_display(), )); } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) { return Err(anyhow::anyhow!( "The file `{}` appears to be a TOML file, but constraints must be specified in `requirements.txt` format", path.user_display(), )); } Ok(Self::RequirementsTxt(path)) } /// Parse a [`RequirementsSource`] from an `overrides.txt` file. pub fn from_overrides_txt(path: PathBuf) -> Result<Self> { if path == Path::new("-") { return Ok(Self::Extensionless(path)); } for file_name in ["pyproject.toml", "setup.py", "setup.cfg"] { if path.ends_with(file_name) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `{}` file, but overrides must be specified in `requirements.txt` format", path.user_display(), file_name )); } } if path .file_name() .and_then(OsStr::to_str) .is_some_and(is_pylock_toml) { return Err(anyhow::anyhow!( "The file `{}` appears to be a `pylock.toml` file, but overrides must be specified in `requirements.txt` format", path.user_display(), )); } else if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) { return Err(anyhow::anyhow!( "The file `{}` appears to be a TOML file, but overrides must be specified in `requirements.txt` format", path.user_display(), )); } Ok(Self::RequirementsTxt(path)) } /// Parse a [`RequirementsSource`] from a user-provided string, assumed to be a positional /// package (e.g., `uv pip install flask`). /// /// If the user provided a value that appears to be a `requirements.txt` file or a local /// directory, prompt them to correct it (if the terminal is interactive). pub fn from_package_argument(name: &str) -> Result<Self> { // If the user provided a `requirements.txt` file without `-r` (as in // `uv pip install requirements.txt`), prompt them to correct it. #[allow(clippy::case_sensitive_file_extension_comparisons)] if (name.ends_with(".txt") || name.ends_with(".in")) && Path::new(&name).is_file() { let term = Term::stderr(); if term.is_term() { let prompt = format!( "`{name}` looks like a local requirements file but was passed as a package name. Did you mean `-r {name}`?" ); let confirmation = uv_console::confirm(&prompt, &term, true).context("Confirm prompt failed")?; if confirmation { return Self::from_requirements_file(name.into()); } } } // Similarly, if the user provided a `pyproject.toml` file without `-r` (as in // `uv pip install pyproject.toml`), prompt them to correct it. if (name == "pyproject.toml" || name == "setup.py" || name == "setup.cfg" || is_pylock_toml(name)) && Path::new(&name).is_file() { let term = Term::stderr(); if term.is_term() { let prompt = format!( "`{name}` looks like a local metadata file but was passed as a package name. Did you mean `-r {name}`?" ); let confirmation = uv_console::confirm(&prompt, &term, true).context("Confirm prompt failed")?; if confirmation { return Self::from_requirements_file(name.into()); } } } let requirement = RequirementsTxtRequirement::parse(name, &*CWD, false) .with_context(|| format!("Failed to parse: `{name}`"))?; Ok(Self::Package(requirement)) } /// Parse a [`RequirementsSource`] from a user-provided string, assumed to be a `--with` /// package (e.g., `uvx --with flask ruff`). /// /// If the user provided a value that appears to be a `requirements.txt` file or a local /// directory, prompt them to correct it (if the terminal is interactive). pub fn from_with_package_argument(name: &str) -> Result<Self> { // If the user provided a `requirements.txt` file without `--with-requirements` (as in // `uvx --with requirements.txt ruff`), prompt them to correct it. #[allow(clippy::case_sensitive_file_extension_comparisons)] if (name.ends_with(".txt") || name.ends_with(".in")) && Path::new(&name).is_file() { let term = Term::stderr(); if term.is_term() { let prompt = format!( "`{name}` looks like a local requirements file but was passed as a package name. Did you mean `--with-requirements {name}`?" ); let confirmation = uv_console::confirm(&prompt, &term, true).context("Confirm prompt failed")?; if confirmation { return Self::from_requirements_file(name.into()); } } } // Similarly, if the user provided a `pyproject.toml` file without `--with-requirements` (as in // `uvx --with pyproject.toml ruff`), prompt them to correct it. if (name == "pyproject.toml" || name == "setup.py" || name == "setup.cfg" || is_pylock_toml(name)) && Path::new(&name).is_file() { let term = Term::stderr(); if term.is_term() { let prompt = format!( "`{name}` looks like a local metadata file but was passed as a package name. Did you mean `--with-requirements {name}`?" ); let confirmation = uv_console::confirm(&prompt, &term, true).context("Confirm prompt failed")?; if confirmation { return Self::from_requirements_file(name.into()); } } } let requirement = RequirementsTxtRequirement::parse(name, &*CWD, false) .with_context(|| format!("Failed to parse: `{name}`"))?; Ok(Self::Package(requirement)) } /// Parse an editable [`RequirementsSource`] (e.g., `uv pip install -e .`). pub fn from_editable(name: &str) -> Result<Self> { let requirement = RequirementsTxtRequirement::parse(name, &*CWD, true) .with_context(|| format!("Failed to parse: `{name}`"))?; Ok(Self::Editable(requirement)) } /// Parse a package [`RequirementsSource`] (e.g., `uv pip install ruff`). pub fn from_package(name: &str) -> Result<Self> { let requirement = RequirementsTxtRequirement::parse(name, &*CWD, false) .with_context(|| format!("Failed to parse: `{name}`"))?; Ok(Self::Package(requirement)) } /// Returns `true` if the source allows extras to be specified. pub fn allows_extras(&self) -> bool { matches!( self, Self::PylockToml(_) | Self::PyprojectToml(_) | Self::SetupPy(_) | Self::SetupCfg(_) ) } /// Returns `true` if the source allows groups to be specified. pub fn allows_groups(&self) -> bool { matches!(self, Self::PylockToml(_) | Self::PyprojectToml(_)) } } impl std::fmt::Display for RequirementsSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Package(package) => write!(f, "{package:?}"), Self::Editable(path) => write!(f, "-e {path:?}"), Self::PylockToml(path) | Self::RequirementsTxt(path) | Self::Pep723Script(path) | Self::PyprojectToml(path) | Self::SetupPy(path) | Self::SetupCfg(path) | Self::EnvironmentYml(path) | Self::Extensionless(path) => { write!(f, "{}", path.simplified_display()) } } } } /// Returns `true` if a file name matches the `pylock.toml` pattern defined in PEP 751. #[allow(clippy::case_sensitive_file_extension_comparisons)] pub fn is_pylock_toml(file_name: &str) -> bool { file_name.starts_with("pylock.") && file_name.ends_with(".toml") }
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-install-wheel/src/uninstall.rs
crates/uv-install-wheel/src/uninstall.rs
use std::collections::BTreeSet; use std::path::{Component, Path, PathBuf}; use std::sync::{LazyLock, Mutex}; use tracing::trace; use uv_fs::write_atomic_sync; use crate::Error; use crate::wheel::read_record_file; /// Uninstall the wheel represented by the given `.dist-info` directory. pub fn uninstall_wheel(dist_info: &Path) -> Result<Uninstall, Error> { let Some(site_packages) = dist_info.parent() else { return Err(Error::BrokenVenv( "dist-info directory is not in a site-packages directory".to_string(), )); }; // Read the RECORD file. let record = { let record_path = dist_info.join("RECORD"); let mut record_file = match fs_err::File::open(&record_path) { Ok(record_file) => record_file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { return Err(Error::MissingRecord(record_path)); } Err(err) => return Err(err.into()), }; read_record_file(&mut record_file)? }; let mut file_count = 0usize; let mut dir_count = 0usize; #[cfg(windows)] let itself = std::env::current_exe().ok(); // Uninstall the files, keeping track of any directories that are left empty. let mut visited = BTreeSet::new(); for entry in &record { let path = site_packages.join(&entry.path); // On Windows, deleting the current executable is a special case. #[cfg(windows)] if let Some(itself) = itself.as_ref() { if itself .file_name() .is_some_and(|itself| path.file_name().is_some_and(|path| itself == path)) { if same_file::is_same_file(itself, &path).unwrap_or(false) { tracing::debug!("Detected self-delete of executable: {}", path.display()); match self_replace::self_delete_outside_path(site_packages) { Ok(()) => { trace!("Removed file: {}", path.display()); file_count += 1; if let Some(parent) = path.parent() { visited.insert(normalize_path(parent)); } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } continue; } } } match fs_err::remove_file(&path) { Ok(()) => { trace!("Removed file: {}", path.display()); file_count += 1; if let Some(parent) = path.parent() { visited.insert(normalize_path(parent)); } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => match fs_err::remove_dir_all(&path) { Ok(()) => { trace!("Removed directory: {}", path.display()); dir_count += 1; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return Err(err.into()), }, } } // If any directories were left empty, remove them. Iterate in reverse order such that we visit // the deepest directories first. for path in visited.iter().rev() { // No need to look at directories outside of `site-packages` (like `bin`). if !path.starts_with(site_packages) { continue; } // Iterate up the directory tree, removing any empty directories. It's insufficient to // rely on `visited` alone here, because we may end up removing a directory whose parent // directory doesn't contain any files, leaving the _parent_ directory empty. let mut path = path.as_path(); loop { // If we reach the site-packages directory, we're done. if path == site_packages { break; } // If the directory contains a `__pycache__` directory, always remove it. `__pycache__` // may or may not be listed in the RECORD, but installers are expected to be smart // enough to remove it either way. let pycache = path.join("__pycache__"); match fs_err::remove_dir_all(&pycache) { Ok(()) => { trace!("Removed directory: {}", pycache.display()); dir_count += 1; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } // Try to read from the directory. If it doesn't exist, assume we deleted it in a // previous iteration. let mut read_dir = match fs_err::read_dir(path) { Ok(read_dir) => read_dir, Err(err) if err.kind() == std::io::ErrorKind::NotFound => break, Err(err) => return Err(err.into()), }; // If the directory is not empty, we're done. if read_dir.next().is_some() { break; } fs_err::remove_dir(path)?; trace!("Removed directory: {}", path.display()); dir_count += 1; if let Some(parent) = path.parent() { path = parent; } else { break; } } } Ok(Uninstall { file_count, dir_count, }) } /// Uninstall the egg represented by the `.egg-info` directory. /// /// See: <https://github.com/pypa/pip/blob/41587f5e0017bcd849f42b314dc8a34a7db75621/src/pip/_internal/req/req_uninstall.py#L483> pub fn uninstall_egg(egg_info: &Path) -> Result<Uninstall, Error> { let mut file_count = 0usize; let mut dir_count = 0usize; let dist_location = egg_info .parent() .expect("egg-info directory is not in a site-packages directory"); // Read the `namespace_packages.txt` file. let namespace_packages = { let namespace_packages_path = egg_info.join("namespace_packages.txt"); match fs_err::read_to_string(namespace_packages_path) { Ok(namespace_packages) => namespace_packages .lines() .map(ToString::to_string) .collect::<Vec<_>>(), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { vec![] } Err(err) => return Err(err.into()), } }; // Read the `top_level.txt` file, ignoring anything in `namespace_packages.txt`. let top_level = { let top_level_path = egg_info.join("top_level.txt"); match fs_err::read_to_string(&top_level_path) { Ok(top_level) => top_level .lines() .map(ToString::to_string) .filter(|line| !namespace_packages.contains(line)) .collect::<Vec<_>>(), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { return Err(Error::MissingTopLevel(top_level_path)); } Err(err) => return Err(err.into()), } }; // Remove everything in `top_level.txt`. for entry in top_level { let path = dist_location.join(&entry); // Remove as a directory. match fs_err::remove_dir_all(&path) { Ok(()) => { trace!("Removed directory: {}", path.display()); dir_count += 1; continue; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } // Remove as a `.py`, `.pyc`, or `.pyo` file. for extension in &["py", "pyc", "pyo"] { let path = path.with_extension(extension); match fs_err::remove_file(&path) { Ok(()) => { trace!("Removed file: {}", path.display()); file_count += 1; break; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } } } // Remove the `.egg-info` directory. match fs_err::remove_dir_all(egg_info) { Ok(()) => { trace!("Removed directory: {}", egg_info.display()); dir_count += 1; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => { return Err(err.into()); } } Ok(Uninstall { file_count, dir_count, }) } fn normcase(s: &str) -> String { if cfg!(windows) { s.replace('/', "\\").to_lowercase() } else { s.to_owned() } } static EASY_INSTALL_PTH: LazyLock<Mutex<i32>> = LazyLock::new(Mutex::default); /// Uninstall the legacy editable represented by the `.egg-link` file. /// /// See: <https://github.com/pypa/pip/blob/41587f5e0017bcd849f42b314dc8a34a7db75621/src/pip/_internal/req/req_uninstall.py#L534-L552> pub fn uninstall_legacy_editable(egg_link: &Path) -> Result<Uninstall, Error> { let mut file_count = 0usize; // Find the target line in the `.egg-link` file. let contents = fs_err::read_to_string(egg_link)?; let target_line = contents .lines() .find_map(|line| { let line = line.trim(); if line.is_empty() { None } else { Some(line) } }) .ok_or_else(|| Error::InvalidEggLink(egg_link.to_path_buf()))?; // This comes from `pkg_resources.normalize_path` let target_line = normcase(target_line); match fs_err::remove_file(egg_link) { Ok(()) => { trace!("Removed file: {}", egg_link.display()); file_count += 1; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } let site_package = egg_link.parent().ok_or(Error::BrokenVenv( "`.egg-link` file is not in a directory".to_string(), ))?; let easy_install = site_package.join("easy-install.pth"); // Since uv has an environment lock, it's enough to add a mutex here to ensure we never // lose writes to `easy-install.pth` (this is the only place in uv where `easy-install.pth` // is modified). let _guard = EASY_INSTALL_PTH.lock().unwrap(); let content = fs_err::read_to_string(&easy_install)?; let mut new_content = String::with_capacity(content.len()); let mut removed = false; // https://github.com/pypa/pip/blob/41587f5e0017bcd849f42b314dc8a34a7db75621/src/pip/_internal/req/req_uninstall.py#L634 for line in content.lines() { if !removed && line.trim() == target_line { removed = true; } else { new_content.push_str(line); new_content.push('\n'); } } if removed { write_atomic_sync(&easy_install, new_content)?; trace!("Removed line from `easy-install.pth`: {target_line}"); } Ok(Uninstall { file_count, dir_count: 0usize, }) } #[derive(Debug, Default)] pub struct Uninstall { /// The number of files that were removed during the uninstallation. pub file_count: usize, /// The number of directories that were removed during the uninstallation. pub dir_count: usize, } /// Normalize a path, removing things like `.` and `..`. /// /// Source: <https://github.com/rust-lang/cargo/blob/b48c41aedbd69ee3990d62a0e2006edbb506a480/crates/cargo-util/src/paths.rs#L76C1-L109C2> fn normalize_path(path: &Path) -> PathBuf { let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { ret.pop(); } Component::Normal(c) => { ret.push(c); } } } ret }
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-install-wheel/src/lib.rs
crates/uv-install-wheel/src/lib.rs
//! Takes a wheel and installs it into a venv. use std::io; use std::path::PathBuf; use owo_colors::OwoColorize; use thiserror::Error; use uv_fs::Simplified; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pypi_types::Scheme; pub use install::install_wheel; pub use linker::{LinkMode, Locks}; pub use uninstall::{Uninstall, uninstall_egg, uninstall_legacy_editable, uninstall_wheel}; pub use wheel::{LibKind, WheelFile, read_record_file}; mod install; mod linker; mod record; mod script; mod uninstall; mod wheel; /// The layout of the target environment into which a wheel can be installed. #[derive(Debug, Clone)] pub struct Layout { /// The Python interpreter, as returned by `sys.executable`. pub sys_executable: PathBuf, /// The Python version, as returned by `sys.version_info`. pub python_version: (u8, u8), /// The `os.name` value for the current platform. pub os_name: String, /// The [`Scheme`] paths for the interpreter. pub scheme: Scheme, } /// Note: The caller is responsible for adding the path of the wheel we're installing. #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), /// Custom error type to add a path to error reading a file from a zip #[error("Failed to reflink {} to {}", from.user_display(), to.user_display())] Reflink { from: PathBuf, to: PathBuf, #[source] err: io::Error, }, /// The wheel is broken #[error("The wheel is invalid: {0}")] InvalidWheel(String), /// Doesn't follow file name schema #[error("Failed to move data files")] WalkDir(#[from] walkdir::Error), #[error("RECORD file doesn't match wheel contents: {0}")] RecordFile(String), #[error("RECORD file is invalid")] RecordCsv(#[from] csv::Error), #[error("Broken virtual environment: {0}")] BrokenVenv(String), #[error( "Unable to create Windows launcher for: {0} (only x86_64, x86, and arm64 are supported)" )] UnsupportedWindowsArch(&'static str), #[error("Unable to create Windows launcher on non-Windows platform")] NotWindows, #[error("Invalid `direct_url.json`")] DirectUrlJson(#[from] serde_json::Error), #[error("Cannot uninstall package; `RECORD` file not found at: {}", _0.user_display())] MissingRecord(PathBuf), #[error("Cannot uninstall package; `top_level.txt` file not found at: {}", _0.user_display())] MissingTopLevel(PathBuf), #[error("Invalid package version")] InvalidVersion(#[from] uv_pep440::VersionParseError), #[error("Wheel package name does not match filename ({0} != {1}), which indicates a malformed wheel. If this is intentional, set `{env_var}`.", env_var = "UV_SKIP_WHEEL_FILENAME_CHECK=1".green())] MismatchedName(PackageName, PackageName), #[error("Wheel version does not match filename ({0} != {1}), which indicates a malformed wheel. If this is intentional, set `{env_var}`.", env_var = "UV_SKIP_WHEEL_FILENAME_CHECK=1".green())] MismatchedVersion(Version, Version), #[error("Invalid egg-link")] InvalidEggLink(PathBuf), #[error(transparent)] LauncherError(#[from] uv_trampoline_builder::Error), #[error("Scripts must not use the reserved name {0}")] ReservedScriptName(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-install-wheel/src/install.rs
crates/uv-install-wheel/src/install.rs
//! Like `wheel.rs`, but for installing wheels that have already been unzipped, rather than //! reading from a zip file. use std::path::Path; use std::str::FromStr; use fs_err::File; use tracing::{instrument, trace}; use uv_distribution_filename::WheelFilename; use uv_pep440::Version; use uv_pypi_types::{DirectUrl, Metadata10}; use crate::linker::{LinkMode, Locks}; use crate::wheel::{ LibKind, WheelFile, dist_info_metadata, find_dist_info, install_data, parse_scripts, read_record_file, write_installer_metadata, write_script_entrypoints, }; use crate::{Error, Layout}; /// Install the given wheel to the given venv /// /// The caller must ensure that the wheel is compatible to the environment. /// /// <https://packaging.python.org/en/latest/specifications/binary-distribution-format/#installing-a-wheel-distribution-1-0-py32-none-any-whl> /// /// Wheel 1.0: <https://www.python.org/dev/peps/pep-0427/> #[instrument(skip_all, fields(wheel = %filename))] pub fn install_wheel<Cache: serde::Serialize, Build: serde::Serialize>( layout: &Layout, relocatable: bool, wheel: impl AsRef<Path>, filename: &WheelFilename, direct_url: Option<&DirectUrl>, cache_info: Option<&Cache>, build_info: Option<&Build>, installer: Option<&str>, installer_metadata: bool, link_mode: LinkMode, locks: &Locks, ) -> Result<(), Error> { let dist_info_prefix = find_dist_info(&wheel)?; let metadata = dist_info_metadata(&dist_info_prefix, &wheel)?; let Metadata10 { name, version } = Metadata10::parse_pkg_info(&metadata) .map_err(|err| Error::InvalidWheel(err.to_string()))?; let version = Version::from_str(&version)?; // Validate the wheel name and version. if !uv_flags::contains(uv_flags::EnvironmentFlags::SKIP_WHEEL_FILENAME_CHECK) { if name != filename.name { return Err(Error::MismatchedName(name, filename.name.clone())); } if version != filename.version && version != filename.version.clone().without_local() { return Err(Error::MismatchedVersion(version, filename.version.clone())); } } // We're going step by step though // https://packaging.python.org/en/latest/specifications/binary-distribution-format/#installing-a-wheel-distribution-1-0-py32-none-any-whl // > 1.a Parse distribution-1.0.dist-info/WHEEL. // > 1.b Check that installer is compatible with Wheel-Version. Warn if minor version is greater, abort if major version is greater. let wheel_file_path = wheel .as_ref() .join(format!("{dist_info_prefix}.dist-info/WHEEL")); let wheel_text = fs_err::read_to_string(wheel_file_path)?; let lib_kind = WheelFile::parse(&wheel_text)?.lib_kind(); // > 1.c If Root-Is-Purelib == ‘true’, unpack archive into purelib (site-packages). // > 1.d Else unpack archive into platlib (site-packages). trace!(?name, "Extracting file"); let site_packages = match lib_kind { LibKind::Pure => &layout.scheme.purelib, LibKind::Plat => &layout.scheme.platlib, }; let num_unpacked = link_mode.link_wheel_files(site_packages, &wheel, locks, filename)?; trace!(?name, "Extracted {num_unpacked} files"); // Read the RECORD file. let mut record_file = File::open( wheel .as_ref() .join(format!("{dist_info_prefix}.dist-info/RECORD")), )?; let mut record = read_record_file(&mut record_file)?; let (console_scripts, gui_scripts) = parse_scripts(&wheel, &dist_info_prefix, None, layout.python_version.1)?; if console_scripts.is_empty() && gui_scripts.is_empty() { trace!(?name, "No entrypoints"); } else { trace!(?name, "Writing entrypoints"); fs_err::create_dir_all(&layout.scheme.scripts)?; write_script_entrypoints( layout, relocatable, site_packages, &console_scripts, &mut record, false, )?; write_script_entrypoints( layout, relocatable, site_packages, &gui_scripts, &mut record, true, )?; } // 2.a Unpacked archive includes distribution-1.0.dist-info/ and (if there is data) distribution-1.0.data/. // 2.b Move each subtree of distribution-1.0.data/ onto its destination path. Each subdirectory of distribution-1.0.data/ is a key into a dict of destination directories, such as distribution-1.0.data/(purelib|platlib|headers|scripts|data). The initially supported paths are taken from distutils.command.install. let data_dir = site_packages.join(format!("{dist_info_prefix}.data")); if data_dir.is_dir() { install_data( layout, relocatable, site_packages, &data_dir, &name, &console_scripts, &gui_scripts, &mut record, )?; // 2.c If applicable, update scripts starting with #!python to point to the correct interpreter. // Script are unsupported through data // 2.e Remove empty distribution-1.0.data directory. fs_err::remove_dir_all(data_dir)?; } else { trace!(?name, "No data"); } if installer_metadata { trace!(?name, "Writing installer metadata"); write_installer_metadata( site_packages, &dist_info_prefix, true, direct_url, cache_info, build_info, installer, &mut record, )?; } trace!(?name, "Writing record"); let mut record_writer = csv::WriterBuilder::new() .has_headers(false) .escape(b'"') .from_path(site_packages.join(format!("{dist_info_prefix}.dist-info/RECORD")))?; record.sort(); for entry in record { record_writer.serialize(entry)?; } 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-install-wheel/src/wheel.rs
crates/uv-install-wheel/src/wheel.rs
use std::collections::HashMap; use std::io; use std::io::{BufReader, Read, Write}; use std::path::{Path, PathBuf}; use data_encoding::BASE64URL_NOPAD; use fs_err as fs; use fs_err::{DirEntry, File}; use mailparse::parse_headers; use rustc_hash::FxHashMap; use sha2::{Digest, Sha256}; use tracing::{debug, instrument, trace, warn}; use walkdir::WalkDir; use uv_fs::{Simplified, persist_with_retry_sync, relative_to}; use uv_normalize::PackageName; use uv_pypi_types::DirectUrl; use uv_shell::escape_posix_for_single_quotes; use uv_trampoline_builder::windows_script_launcher; use uv_warnings::warn_user_once; use crate::record::RecordEntry; use crate::script::{Script, scripts_from_ini}; use crate::{Error, Layout}; /// Wrapper script template function /// /// <https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/distlib/scripts.py#L41-L48> /// /// Script template slightly modified: removed `import re`, allowing scripts that never import `re` to load faster. fn get_script_launcher(entry_point: &Script, shebang: &str) -> String { let Script { module, function, .. } = entry_point; let import_name = entry_point.import_name(); format!( r#"{shebang} # -*- coding: utf-8 -*- import sys from {module} import {import_name} if __name__ == "__main__": if sys.argv[0].endswith("-script.pyw"): sys.argv[0] = sys.argv[0][:-11] elif sys.argv[0].endswith(".exe"): sys.argv[0] = sys.argv[0][:-4] sys.exit({function}()) "# ) } /// Part of entrypoints parsing pub(crate) fn read_scripts_from_section( scripts_section: &HashMap<String, Option<String>>, section_name: &str, extras: Option<&[String]>, ) -> Result<Vec<Script>, Error> { let mut scripts = Vec::new(); for (script_name, python_location) in scripts_section { match python_location { Some(value) => { if let Some(script) = Script::from_value(script_name, value, extras)? { scripts.push(script); } } None => { return Err(Error::InvalidWheel(format!( "[{section_name}] key {script_name} must have a value" ))); } } } Ok(scripts) } /// Shamelessly stolen (and updated for recent sha2) /// <https://github.com/richo/hashing-copy/blob/d8dd2fdb63c6faf198de0c9e5713d6249cbb5323/src/lib.rs#L10-L52> /// which in turn got it from std /// <https://doc.rust-lang.org/1.58.0/src/std/io/copy.rs.html#128-156> fn copy_and_hash(reader: &mut impl Read, writer: &mut impl Write) -> io::Result<(u64, String)> { // TODO: Do we need to support anything besides sha256? let mut hasher = Sha256::new(); // Same buf size as std. Note that this number is important for performance let mut buf = vec![0; 8 * 1024]; let mut written = 0; loop { let len = match reader.read(&mut buf) { Ok(0) => break, Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; hasher.update(&buf[..len]); writer.write_all(&buf[..len])?; written += len as u64; } Ok(( written, format!("sha256={}", BASE64URL_NOPAD.encode(&hasher.finalize())), )) } /// Format the shebang for a given Python executable. /// /// Like pip, if a shebang is non-simple (too long or contains spaces), we use `/bin/sh` as the /// executable. /// /// See: <https://github.com/pypa/pip/blob/0ad4c94be74cc24874c6feb5bb3c2152c398a18e/src/pip/_vendor/distlib/scripts.py#L136-L165> fn format_shebang(executable: impl AsRef<Path>, os_name: &str, relocatable: bool) -> String { // Convert the executable to a simplified path. let executable = executable.as_ref().simplified_display().to_string(); // Validate the shebang. if os_name == "posix" { // The length of the full line: the shebang, plus the leading `#` and `!`, and a trailing // newline. let shebang_length = 2 + executable.len() + 1; // If the shebang is too long, or contains spaces, wrap it in `/bin/sh`. // Same applies for relocatable scripts (executable is relative to script dir, hence `dirname` trick) // (note: the Windows trampoline binaries natively support relative paths to executable) if shebang_length > 127 || executable.contains(' ') || relocatable { let prefix = if relocatable { r#""$(dirname -- "$(realpath -- "$0")")"/"# } else { "" }; let executable = format!( "{}'{}'", prefix, escape_posix_for_single_quotes(&executable) ); return format!("#!/bin/sh\n'''exec' {executable} \"$0\" \"$@\"\n' '''"); } } format!("#!{executable}") } /// Returns a [`PathBuf`] to `python[w].exe` for script execution. /// /// <https://github.com/pypa/pip/blob/76e82a43f8fb04695e834810df64f2d9a2ff6020/src/pip/_vendor/distlib/scripts.py#L121-L126> fn get_script_executable(python_executable: &Path, is_gui: bool) -> PathBuf { // Only check for `pythonw.exe` on Windows. if cfg!(windows) && is_gui { python_executable .file_name() .map(|name| { let new_name = name.to_string_lossy().replace("python", "pythonw"); python_executable.with_file_name(new_name) }) .filter(|path| path.is_file()) .unwrap_or_else(|| python_executable.to_path_buf()) } else { python_executable.to_path_buf() } } /// Determine the absolute path to an entrypoint script. fn entrypoint_path(entrypoint: &Script, layout: &Layout) -> PathBuf { if cfg!(windows) { // On windows we actually build an .exe wrapper let script_name = entrypoint .name // FIXME: What are the in-reality rules here for names? .strip_suffix(".py") .unwrap_or(&entrypoint.name) .to_string() + ".exe"; layout.scheme.scripts.join(script_name) } else { layout.scheme.scripts.join(&entrypoint.name) } } /// Create the wrapper scripts in the bin folder of the venv for launching console scripts. pub(crate) fn write_script_entrypoints( layout: &Layout, relocatable: bool, site_packages: &Path, entrypoints: &[Script], record: &mut Vec<RecordEntry>, is_gui: bool, ) -> Result<(), Error> { for entrypoint in entrypoints { let warn_names = ["activate", "activate_this.py"]; if warn_names.contains(&entrypoint.name.as_str()) || entrypoint.name.starts_with("activate.") { warn_user_once!( "The script name `{}` is reserved for virtual environment activation scripts.", entrypoint.name ); } let reserved_names = ["python", "pythonw", "python3"]; if reserved_names.contains(&entrypoint.name.as_str()) || entrypoint .name .strip_prefix("python3.") .is_some_and(|suffix| suffix.parse::<u8>().is_ok()) { return Err(Error::ReservedScriptName(entrypoint.name.clone())); } let entrypoint_absolute = entrypoint_path(entrypoint, layout); let entrypoint_relative = pathdiff::diff_paths(&entrypoint_absolute, site_packages) .ok_or_else(|| { Error::Io(io::Error::other(format!( "Could not find relative path for: {}", entrypoint_absolute.simplified_display() ))) })?; // Generate the launcher script. let launcher_executable = get_script_executable(&layout.sys_executable, is_gui); let launcher_executable = get_relocatable_executable(launcher_executable, layout, relocatable)?; let launcher_python_script = get_script_launcher( entrypoint, &format_shebang(&launcher_executable, &layout.os_name, relocatable), ); // If necessary, wrap the launcher script in a Windows launcher binary. if cfg!(windows) { write_file_recorded( site_packages, &entrypoint_relative, &windows_script_launcher(&launcher_python_script, is_gui, &launcher_executable)?, record, )?; } else { write_file_recorded( site_packages, &entrypoint_relative, &launcher_python_script, record, )?; // Make the launcher executable. #[cfg(unix)] { use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; let path = site_packages.join(entrypoint_relative); let permissions = fs::metadata(&path)?.permissions(); if permissions.mode() & 0o111 != 0o111 { fs::set_permissions(path, Permissions::from_mode(permissions.mode() | 0o111))?; } } } } Ok(()) } /// A parsed `WHEEL` file. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WheelFile(FxHashMap<String, Vec<String>>); impl WheelFile { /// Parse `WHEEL` file. /// /// > {distribution}-{version}.dist-info/WHEEL is metadata about the archive itself in the same /// > email message format: pub fn parse(wheel_text: &str) -> Result<Self, Error> { // {distribution}-{version}.dist-info/WHEEL is metadata about the archive itself in the same email message format: let data = parse_email_message_file(&mut wheel_text.as_bytes(), "WHEEL")?; // mkl_fft-1.3.6-58-cp310-cp310-manylinux2014_x86_64.whl has multiple Wheel-Version entries, we have to ignore that // like pip let wheel_version = data .get("Wheel-Version") .and_then(|wheel_versions| wheel_versions.first()); let wheel_version = wheel_version .and_then(|wheel_version| wheel_version.split_once('.')) .ok_or_else(|| { Error::InvalidWheel(format!( "Invalid Wheel-Version in WHEEL file: {wheel_version:?}" )) })?; // pip has some test wheels that use that ancient version, // and technically we only need to check that the version is not higher if wheel_version == ("0", "1") { warn!("Ancient wheel version 0.1 (expected is 1.0)"); return Ok(Self(data)); } // Check that installer is compatible with Wheel-Version. Warn if minor version is greater, abort if major version is greater. // Wheel-Version: 1.0 if wheel_version.0 != "1" { return Err(Error::InvalidWheel(format!( "Unsupported wheel major version (expected {}, got {})", 1, wheel_version.0 ))); } if wheel_version.1 > "0" { warn!( "Warning: Unsupported wheel minor version (expected {}, got {})", 0, wheel_version.1 ); } Ok(Self(data)) } /// Whether the wheel should be installed into the `purelib` or `platlib` directory. pub fn lib_kind(&self) -> LibKind { // Determine whether Root-Is-Purelib == ‘true’. // If it is, the wheel is pure, and should be installed into purelib. let root_is_purelib = self .0 .get("Root-Is-Purelib") .and_then(|root_is_purelib| root_is_purelib.first()) .is_some_and(|root_is_purelib| root_is_purelib == "true"); if root_is_purelib { LibKind::Pure } else { LibKind::Plat } } /// Return the list of wheel tags. pub fn tags(&self) -> Option<&[String]> { self.0.get("Tag").map(Vec::as_slice) } } /// Whether the wheel should be installed into the `purelib` or `platlib` directory. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LibKind { /// Install into the `purelib` directory. Pure, /// Install into the `platlib` directory. Plat, } /// Moves the files and folders in src to dest, updating the RECORD in the process pub(crate) fn move_folder_recorded( src_dir: &Path, dest_dir: &Path, site_packages: &Path, record: &mut [RecordEntry], ) -> Result<(), Error> { let mut rename_or_copy = RenameOrCopy::default(); fs::create_dir_all(dest_dir)?; for entry in WalkDir::new(src_dir) { let entry = entry?; let src = entry.path(); // This is the base path for moving to the actual target for the data // e.g. for data it's without <..>.data/data/ let relative_to_data = src .strip_prefix(src_dir) .expect("walkdir prefix must not change"); // This is the path stored in RECORD // e.g. for data it's with .data/data/ let relative_to_site_packages = src .strip_prefix(site_packages) .expect("prefix must not change"); let target = dest_dir.join(relative_to_data); if entry.file_type().is_dir() { fs::create_dir_all(&target)?; } else { rename_or_copy.rename_or_copy(src, &target)?; let entry = record .iter_mut() .find(|entry| Path::new(&entry.path) == relative_to_site_packages) .ok_or_else(|| { Error::RecordFile(format!( "Could not find entry for {} ({})", relative_to_site_packages.simplified_display(), src.simplified_display() )) })?; entry.path = relative_to(&target, site_packages)?.display().to_string(); } } Ok(()) } /// Installs a single script (not an entrypoint). /// /// Binary files are moved with a copy fallback, while we rewrite scripts' shebangs if applicable. fn install_script( layout: &Layout, relocatable: bool, site_packages: &Path, record: &mut [RecordEntry], file: &DirEntry, #[allow(unused)] rename_or_copy: &mut RenameOrCopy, ) -> Result<(), Error> { let file_type = file.file_type()?; if file_type.is_dir() { return Err(Error::InvalidWheel(format!( "Wheel contains an invalid entry (directory) in the `scripts` directory: {}", file.path().simplified_display() ))); } if file_type.is_symlink() { let Ok(target) = file.path().canonicalize() else { return Err(Error::InvalidWheel(format!( "Wheel contains an invalid entry (broken symlink) in the `scripts` directory: {}", file.path().simplified_display(), ))); }; if target.is_dir() { return Err(Error::InvalidWheel(format!( "Wheel contains an invalid entry (directory symlink) in the `scripts` directory: {} ({})", file.path().simplified_display(), target.simplified_display() ))); } } let script_absolute = layout.scheme.scripts.join(file.file_name()); let script_relative = pathdiff::diff_paths(&script_absolute, site_packages).ok_or_else(|| { Error::Io(io::Error::other(format!( "Could not find relative path for: {}", script_absolute.simplified_display() ))) })?; let path = file.path(); let mut script = File::open(&path)?; // https://sphinx-locales.github.io/peps/pep-0427/#recommended-installer-features // > In wheel, scripts are packaged in {distribution}-{version}.data/scripts/. // > If the first line of a file in scripts/ starts with exactly b'#!python', // > rewrite to point to the correct interpreter. Unix installers may need to // > add the +x bit to these files if the archive was created on Windows. // // > The b'#!pythonw' convention is allowed. b'#!pythonw' indicates a GUI script // > instead of a console script. let placeholder_python = b"#!python"; // scripts might be binaries, so we read an exact number of bytes instead of the first line as string let mut start = vec![0; placeholder_python.len()]; match script.read_exact(&mut start) { Ok(()) => {} // Ignore scripts shorter than the buffer. Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => {} Err(err) => return Err(Error::Io(err)), } let size_and_encoded_hash = if start == placeholder_python { // Read the rest of the first line, one byte at a time, until we hit a newline. let mut is_gui = false; let mut first = true; let mut byte = [0u8; 1]; loop { match script.read_exact(&mut byte) { Ok(()) => { if byte[0] == b'\n' || byte[0] == b'\r' { break; } // Check if this is a GUI script (starts with 'w'). if first { is_gui = byte[0] == b'w'; first = false; } } Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break, Err(err) => return Err(Error::Io(err)), } } let executable = get_script_executable(&layout.sys_executable, is_gui); let executable = get_relocatable_executable(executable, layout, relocatable)?; let mut start = format_shebang(&executable, &layout.os_name, relocatable) .as_bytes() .to_vec(); // Use appropriate line ending for the platform. if layout.os_name == "nt" { start.extend_from_slice(b"\r\n"); } else { start.push(b'\n'); } let mut target = uv_fs::tempfile_in(&layout.scheme.scripts)?; let size_and_encoded_hash = copy_and_hash(&mut start.chain(script), &mut target)?; persist_with_retry_sync(target, &script_absolute)?; fs::remove_file(&path)?; // Make the script executable. We just created the file, so we can set permissions directly. #[cfg(unix)] { use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; let permissions = fs::metadata(&script_absolute)?.permissions(); if permissions.mode() & 0o111 != 0o111 { fs::set_permissions( script_absolute, Permissions::from_mode(permissions.mode() | 0o111), )?; } } Some(size_and_encoded_hash) } else { // Reading and writing is slow (especially for large binaries), so we move them instead, if // we can. This also retains the file permissions. We _can't_ move (and must copy) if the // file permissions need to be changed, since we might not own the file. drop(script); #[cfg(unix)] { use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; let permissions = fs::metadata(&path)?.permissions(); if permissions.mode() & 0o111 == 0o111 { // If the permissions are already executable, we don't need to change them. // We fall back to copy when the file is on another drive. rename_or_copy.rename_or_copy(&path, &script_absolute)?; } else { // If we have to modify the permissions, copy the file, since we might not own it, // and we may not be allowed to change permissions on an unowned moved file. warn!( "Copying script from {} to {} (permissions: {:o})", path.simplified_display(), script_absolute.simplified_display(), permissions.mode() ); uv_fs::copy_atomic_sync(&path, &script_absolute)?; fs::set_permissions( script_absolute, Permissions::from_mode(permissions.mode() | 0o111), )?; } } #[cfg(not(unix))] { // Here, two wrappers over rename are clashing: We want to retry for security software // blocking the file, but we also need the copy fallback is the problem was trying to // move a file cross-drive. match uv_fs::with_retry_sync(&path, &script_absolute, "renaming", || { fs_err::rename(&path, &script_absolute) }) { Ok(()) => (), Err(err) => { debug!("Failed to rename, falling back to copy: {err}"); uv_fs::with_retry_sync(&path, &script_absolute, "copying", || { fs_err::copy(&path, &script_absolute)?; Ok(()) })?; } } } None }; // Find the existing entry in the `RECORD`. let relative_to_site_packages = path .strip_prefix(site_packages) .expect("Prefix must no change"); let entry = record .iter_mut() .find(|entry| Path::new(&entry.path) == relative_to_site_packages) .ok_or_else(|| { // This should be possible to occur at this point, but filesystems and such Error::RecordFile(format!( "Could not find entry for {} ({})", relative_to_site_packages.simplified_display(), path.simplified_display() )) })?; // Update the entry in the `RECORD`. entry.path = script_relative.simplified_display().to_string(); if let Some((size, encoded_hash)) = size_and_encoded_hash { entry.size = Some(size); entry.hash = Some(encoded_hash); } Ok(()) } /// Move the files from the .data directory to the right location in the venv #[instrument(skip_all)] pub(crate) fn install_data( layout: &Layout, relocatable: bool, site_packages: &Path, data_dir: &Path, dist_name: &PackageName, console_scripts: &[Script], gui_scripts: &[Script], record: &mut [RecordEntry], ) -> Result<(), Error> { for entry in fs::read_dir(data_dir)? { let entry = entry?; let path = entry.path(); match path.file_name().and_then(|name| name.to_str()) { Some("data") => { trace!( ?dist_name, "Installing data/data to {}", layout.scheme.data.user_display() ); // Move the content of the folder to the root of the venv move_folder_recorded(&path, &layout.scheme.data, site_packages, record)?; } Some("scripts") => { trace!( ?dist_name, "Installing data/scripts to {}", layout.scheme.scripts.user_display() ); let mut rename_or_copy = RenameOrCopy::default(); let mut initialized = false; for file in fs::read_dir(path)? { let file = file?; // Couldn't find any docs for this, took it directly from // https://github.com/pypa/pip/blob/b5457dfee47dd9e9f6ec45159d9d410ba44e5ea1/src/pip/_internal/operations/install/wheel.py#L565-L583 let name = file.file_name().to_string_lossy().to_string(); let match_name = name .strip_suffix(".exe") .or_else(|| name.strip_suffix("-script.py")) .or_else(|| name.strip_suffix(".pya")) .unwrap_or(&name); if console_scripts .iter() .chain(gui_scripts) .any(|script| script.name == match_name) { continue; } // Create the scripts directory, if it doesn't exist. if !initialized { fs::create_dir_all(&layout.scheme.scripts)?; initialized = true; } install_script( layout, relocatable, site_packages, record, &file, &mut rename_or_copy, )?; } } Some("headers") => { let target_path = layout.scheme.include.join(dist_name.as_str()); trace!( ?dist_name, "Installing data/headers to {}", target_path.user_display() ); move_folder_recorded(&path, &target_path, site_packages, record)?; } Some("purelib") => { trace!( ?dist_name, "Installing data/purelib to {}", layout.scheme.purelib.user_display() ); move_folder_recorded(&path, &layout.scheme.purelib, site_packages, record)?; } Some("platlib") => { trace!( ?dist_name, "Installing data/platlib to {}", layout.scheme.platlib.user_display() ); move_folder_recorded(&path, &layout.scheme.platlib, site_packages, record)?; } _ => { return Err(Error::InvalidWheel(format!( "Unknown wheel data type: {}", entry.file_name().display() ))); } } } Ok(()) } /// Write the content to a file and add the hash to the RECORD list /// /// We still the path in the absolute path to the site packages and the relative path in the /// site packages because we must only record the relative path in RECORD pub(crate) fn write_file_recorded( site_packages: &Path, relative_path: &Path, content: impl AsRef<[u8]>, record: &mut Vec<RecordEntry>, ) -> Result<(), Error> { debug_assert!( !relative_path.is_absolute(), "Path must be relative: {}", relative_path.display() ); uv_fs::write_atomic_sync(site_packages.join(relative_path), content.as_ref())?; let hash = Sha256::new().chain_update(content.as_ref()).finalize(); let encoded_hash = format!("sha256={}", BASE64URL_NOPAD.encode(&hash)); record.push(RecordEntry { path: relative_path.portable_display().to_string(), hash: Some(encoded_hash), size: Some(content.as_ref().len() as u64), }); Ok(()) } /// Adds `INSTALLER`, `REQUESTED` and `direct_url.json` to the .dist-info dir pub(crate) fn write_installer_metadata<Cache: serde::Serialize, Build: serde::Serialize>( site_packages: &Path, dist_info_prefix: &str, requested: bool, direct_url: Option<&DirectUrl>, cache_info: Option<&Cache>, build_info: Option<&Build>, installer: Option<&str>, record: &mut Vec<RecordEntry>, ) -> Result<(), Error> { let dist_info_dir = PathBuf::from(format!("{dist_info_prefix}.dist-info")); if requested { write_file_recorded(site_packages, &dist_info_dir.join("REQUESTED"), "", record)?; } if let Some(direct_url) = direct_url { write_file_recorded( site_packages, &dist_info_dir.join("direct_url.json"), serde_json::to_string(direct_url)?.as_bytes(), record, )?; } if let Some(cache_info) = cache_info { write_file_recorded( site_packages, &dist_info_dir.join("uv_cache.json"), serde_json::to_string(cache_info)?.as_bytes(), record, )?; } if let Some(build_info) = build_info { write_file_recorded( site_packages, &dist_info_dir.join("uv_build.json"), serde_json::to_string(build_info)?.as_bytes(), record, )?; } if let Some(installer) = installer { write_file_recorded( site_packages, &dist_info_dir.join("INSTALLER"), installer, record, )?; } Ok(()) } /// Get the path to the Python executable for the [`Layout`], based on whether the wheel should /// be relocatable. /// /// Returns `sys.executable` if the wheel is not relocatable; otherwise, returns a path relative /// to the scripts directory. pub(crate) fn get_relocatable_executable( executable: PathBuf, layout: &Layout, relocatable: bool, ) -> Result<PathBuf, Error> { Ok(if relocatable { pathdiff::diff_paths(&executable, &layout.scheme.scripts).ok_or_else(|| { Error::Io(io::Error::other(format!( "Could not find relative path for: {}", executable.simplified_display() ))) })? } else { executable }) } /// Reads the record file /// <https://www.python.org/dev/peps/pep-0376/#record> pub fn read_record_file(record: &mut impl Read) -> Result<Vec<RecordEntry>, Error> { csv::ReaderBuilder::new() .has_headers(false) .escape(Some(b'"')) .from_reader(record) .deserialize() .map(|entry| { let entry: RecordEntry = entry?; Ok(RecordEntry { // selenium uses absolute paths for some reason path: entry.path.trim_start_matches('/').to_string(), ..entry }) }) .collect() } /// Parse a file with email message format such as WHEEL and METADATA fn parse_email_message_file( file: impl Read, debug_filename: &str, ) -> Result<FxHashMap<String, Vec<String>>, Error> { let mut data: FxHashMap<String, Vec<String>> = FxHashMap::default(); let file = BufReader::new(file); let content = file.bytes().collect::<Result<Vec<u8>, _>>()?; let headers = parse_headers(content.as_slice()) .map_err(|err| { Error::InvalidWheel(format!("Failed to parse {debug_filename} file: {err}")) })? .0; for header in headers { let name = header.get_key(); // Will not be trimmed because if it contains space, mailparse will skip the header let mut value = header.get_value(); // Trim the value only if needed let trimmed_value = value.trim(); if value != trimmed_value { value = trimmed_value.to_string(); } data.entry(name).or_default().push(value); } Ok(data) } /// Find the `dist-info` directory in an unzipped wheel. /// /// See: <https://github.com/PyO3/python-pkginfo-rs> /// /// See: <https://github.com/pypa/pip/blob/36823099a9cdd83261fdbc8c1d2a24fa2eea72ca/src/pip/_internal/utils/wheel.py#L38> pub(crate) fn find_dist_info(path: impl AsRef<Path>) -> Result<String, Error> { // Iterate over `path` to find the `.dist-info` directory. It should be at the top-level. let Some(dist_info) = fs::read_dir(path.as_ref())?.find_map(|entry| { let entry = entry.ok()?; let file_type = entry.file_type().ok()?; if file_type.is_dir() { let path = entry.path(); if path.extension().is_some_and(|ext| ext == "dist-info") { Some(path) } else { None } } else { None } }) else { return Err(Error::InvalidWheel( "Missing .dist-info directory".to_string(), )); }; let Some(dist_info_prefix) = dist_info.file_stem() else { return Err(Error::InvalidWheel( "Missing .dist-info directory".to_string(), )); }; Ok(dist_info_prefix.to_string_lossy().to_string()) } /// Read the `dist-info` metadata from a directory. pub(crate) fn dist_info_metadata( dist_info_prefix: &str, wheel: impl AsRef<Path>, ) -> Result<Vec<u8>, Error> { let metadata_file = wheel .as_ref() .join(format!("{dist_info_prefix}.dist-info/METADATA")); Ok(fs::read(metadata_file)?) } /// Parses the `entry_points.txt` entry in the wheel for console scripts /// /// Returns (`script_name`, module, function) ///
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-install-wheel/src/record.rs
crates/uv-install-wheel/src/record.rs
use serde::{Deserialize, Serialize}; /// Line in a RECORD file /// <https://www.python.org/dev/peps/pep-0376/#record> /// /// ```csv /// tqdm/cli.py,sha256=x_c8nmc4Huc-lKEsAXj78ZiyqSJ9hJ71j7vltY67icw,10509 /// tqdm-4.62.3.dist-info/RECORD,, /// ``` #[derive(Deserialize, Serialize, PartialOrd, PartialEq, Ord, Eq)] pub struct RecordEntry { pub path: String, pub hash: Option<String>, #[allow(dead_code)] pub size: Option<u64>, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-install-wheel/src/script.rs
crates/uv-install-wheel/src/script.rs
use configparser::ini::Ini; use regex::Regex; use rustc_hash::FxHashSet; use serde::Serialize; use std::sync::LazyLock; use crate::{Error, wheel}; /// A script defining the name of the runnable entrypoint and the module and function that should be /// run. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)] pub(crate) struct Script { pub(crate) name: String, pub(crate) module: String, pub(crate) function: String, } impl Script { /// Parses a script definition like `foo.bar:main` or `foomod:main_bar [bar,baz]` /// /// <https://packaging.python.org/en/latest/specifications/entry-points/> /// /// Extras are supposed to be ignored, which happens if you pass None for extras pub(crate) fn from_value( script_name: &str, value: &str, extras: Option<&[String]>, ) -> Result<Option<Self>, Error> { // "Within a value, readers must accept and ignore spaces (including multiple consecutive spaces) before or after the colon, // between the object reference and the left square bracket, between the extra names and the square brackets and colons delimiting them, // and after the right square bracket." // – https://packaging.python.org/en/latest/specifications/entry-points/#file-format static SCRIPT_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"^(?P<module>[\w\d_\-.]+)\s*:\s*(?P<function>[\w\d_\-.]+)(?:\s*\[\s*(?P<extras>(?:[^,]+,?\s*)+)\])?\s*$").unwrap() }); let captures = SCRIPT_REGEX .captures(value) .ok_or_else(|| Error::InvalidWheel(format!("invalid console script: '{value}'")))?; if let Some(script_extras) = captures.name("extras") { if let Some(extras) = extras { let script_extras = script_extras .as_str() .split(',') .map(|extra| extra.trim().to_string()) .collect::<FxHashSet<String>>(); if !script_extras.is_subset(&extras.iter().cloned().collect()) { return Ok(None); } } } Ok(Some(Self { name: script_name.to_string(), module: captures.name("module").unwrap().as_str().to_string(), function: captures.name("function").unwrap().as_str().to_string(), })) } pub(crate) fn import_name(&self) -> &str { self.function .split_once('.') .map_or(&self.function, |(import_name, _)| import_name) } } pub(crate) fn scripts_from_ini( extras: Option<&[String]>, python_minor: u8, ini: String, ) -> Result<(Vec<Script>, Vec<Script>), Error> { let entry_points_mapping = Ini::new_cs() .read(ini) .map_err(|err| Error::InvalidWheel(format!("entry_points.txt is invalid: {err}")))?; // TODO: handle extras let mut console_scripts = match entry_points_mapping.get("console_scripts") { Some(console_scripts) => { wheel::read_scripts_from_section(console_scripts, "console_scripts", extras)? } None => Vec::new(), }; let gui_scripts = match entry_points_mapping.get("gui_scripts") { Some(gui_scripts) => wheel::read_scripts_from_section(gui_scripts, "gui_scripts", extras)?, None => Vec::new(), }; // Special case to generate versioned pip launchers. // https://github.com/pypa/pip/blob/3898741e29b7279e7bffe044ecfbe20f6a438b1e/src/pip/_internal/operations/install/wheel.py#L283 // https://github.com/astral-sh/uv/issues/1593 // Older pip versions have a wrong `pip3.x` launcher we have to remove, while newer pip versions // (post https://github.com/pypa/pip/pull/12536) don't, ... console_scripts.retain(|script| { let Some((left, right)) = script.name.split_once('.') else { return true; }; !(left == "pip3" && right.parse::<u8>().is_ok()) }); // ... either has a `pip3` launcher we can use as template for the `pip3.x` users expect. if let Some(pip_script) = console_scripts.iter().find(|script| script.name == "pip3") { console_scripts.push(Script { name: format!("pip3.{python_minor}"), ..pip_script.clone() }); } Ok((console_scripts, gui_scripts)) } #[cfg(test)] mod test { use crate::script::{Script, scripts_from_ini}; #[test] fn test_valid_script_names() { for case in [ "foomod:main", "foomod:main_bar [bar,baz]", "pylutron_caseta.cli:lap_pair[cli]", ] { assert!(Script::from_value("script", case, None).is_ok()); } } #[test] fn test_invalid_script_names() { for case in [ "", // Empty ":weh", // invalid module "foomod:main_bar [bar", // extras malformed "pylutron_caseta", // missing function part "weh:", // invalid function ] { assert!( Script::from_value("script", case, None).is_err(), "case: {case}" ); } } #[test] fn test_split_of_import_name_from_function() { let entrypoint = "foomod:mod_bar.sub_foo.func_baz"; let script = Script::from_value("script", entrypoint, None) .unwrap() .unwrap(); assert_eq!(script.function, "mod_bar.sub_foo.func_baz"); assert_eq!(script.import_name(), "mod_bar"); } #[test] fn test_pip3_entry_point_modification() { // Notably pip only applies the modification hack to entry points // called "pip" and "easy_install" -- if there are abi3 style wheels // that contain other versioned entry points, they keep their (probably // incorrect) suffixes. let sample_ini = " [console_scripts] pip = a:b1 pip3 = a:b2 pip3.11 = a:b3 pip3.x = a:b4 pip4.11 = a:b5 memray = a:b6 memray3.11 = a:b7 "; let (mut console_scripts, _gui_scripts) = scripts_from_ini(None, 99, sample_ini.to_string()).unwrap(); console_scripts.sort(); assert_eq!( Some(&Script { name: "memray".to_string(), module: "a".to_string(), function: "b6".to_string() }), console_scripts.first() ); assert_eq!( Some(&Script { name: "memray3.11".to_string(), module: "a".to_string(), function: "b7".to_string() }), console_scripts.get(1) ); assert_eq!( Some(&Script { name: "pip".to_string(), module: "a".to_string(), function: "b1".to_string() }), console_scripts.get(2) ); assert_eq!( Some(&Script { name: "pip3".to_string(), module: "a".to_string(), function: "b2".to_string() }), console_scripts.get(3) ); assert_eq!( Some(&Script { name: "pip3.99".to_string(), module: "a".to_string(), function: "b2".to_string() }), console_scripts.get(4) ); assert_eq!( Some(&Script { name: "pip3.x".to_string(), module: "a".to_string(), function: "b4".to_string() }), console_scripts.get(5) ); } }
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-install-wheel/src/linker.rs
crates/uv-install-wheel/src/linker.rs
use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::SystemTime; use fs_err as fs; use fs_err::DirEntry; use reflink_copy as reflink; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use tempfile::tempdir_in; use tracing::{debug, instrument, trace}; use walkdir::WalkDir; use uv_distribution_filename::WheelFilename; use uv_fs::Simplified; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::{warn_user, warn_user_once}; use crate::Error; #[allow(clippy::struct_field_names)] #[derive(Debug, Default)] pub struct Locks { /// The parent directory of a file in a synchronized copy copy_dir_locks: Mutex<FxHashMap<PathBuf, Arc<Mutex<()>>>>, /// Top level modules (excluding namespaces) we write to. modules: Mutex<FxHashMap<OsString, WheelFilename>>, /// Preview settings for feature flags. preview: Preview, } impl Locks { /// Create a new Locks instance with the given preview settings. pub fn new(preview: Preview) -> Self { Self { copy_dir_locks: Mutex::new(FxHashMap::default()), modules: Mutex::new(FxHashMap::default()), preview, } } /// Warn when a module exists in multiple packages. fn warn_module_conflict(&self, module: &OsStr, wheel_a: &WheelFilename) { if let Some(wheel_b) = self .modules .lock() .unwrap() .insert(module.to_os_string(), wheel_a.clone()) { // Only warn if the preview feature is enabled if !self .preview .is_enabled(PreviewFeatures::DETECT_MODULE_CONFLICTS) { return; } // Sort for consistent output, at least with two packages let (wheel_a, wheel_b) = if wheel_b.name > wheel_a.name { (&wheel_b, wheel_a) } else { (wheel_a, &wheel_b) }; warn_user!( "The module `{}` is provided by more than one package, \ which causes an install race condition and can result in a broken module. \ Consider removing your dependency on either `{}` ({}) or `{}` ({}).", module.simplified_display().green(), wheel_a.name.cyan(), format!("v{}", wheel_a.version).cyan(), wheel_b.name.cyan(), format!("v{}", wheel_b.version).cyan() ); } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum LinkMode { /// Clone (i.e., copy-on-write) packages from the wheel into the `site-packages` directory. Clone, /// Copy packages from the wheel into the `site-packages` directory. Copy, /// Hard link packages from the wheel into the `site-packages` directory. Hardlink, /// Symbolically link packages from the wheel into the `site-packages` directory. Symlink, } impl Default for LinkMode { fn default() -> Self { if cfg!(any(target_os = "macos", target_os = "ios")) { Self::Clone } else { Self::Hardlink } } } impl LinkMode { /// Extract a wheel by linking all of its files into site packages. #[instrument(skip_all)] pub fn link_wheel_files( self, site_packages: impl AsRef<Path>, wheel: impl AsRef<Path>, locks: &Locks, filename: &WheelFilename, ) -> Result<usize, Error> { match self { Self::Clone => clone_wheel_files(site_packages, wheel, locks, filename), Self::Copy => copy_wheel_files(site_packages, wheel, locks, filename), Self::Hardlink => hardlink_wheel_files(site_packages, wheel, locks, filename), Self::Symlink => symlink_wheel_files(site_packages, wheel, locks, filename), } } /// Returns `true` if the link mode is [`LinkMode::Symlink`]. pub fn is_symlink(&self) -> bool { matches!(self, Self::Symlink) } } /// Extract a wheel by cloning all of its files into site packages. The files will be cloned /// via copy-on-write, which is similar to a hard link, but allows the files to be modified /// independently (that is, the file is copied upon modification). /// /// This method uses `clonefile` on macOS, and `reflink` on Linux. See [`clone_recursive`] for /// details. fn clone_wheel_files( site_packages: impl AsRef<Path>, wheel: impl AsRef<Path>, locks: &Locks, filename: &WheelFilename, ) -> Result<usize, Error> { let wheel = wheel.as_ref(); let mut count = 0usize; let mut attempt = Attempt::default(); for entry in fs::read_dir(wheel)? { let entry = entry?; if entry.path().join("__init__.py").is_file() { locks.warn_module_conflict( entry .path() .strip_prefix(wheel) .expect("wheel path starts with wheel root") .as_os_str(), filename, ); } clone_recursive(site_packages.as_ref(), wheel, locks, &entry, &mut attempt)?; count += 1; } // The directory mtime is not updated when cloning and the mtime is used by CPython's // import mechanisms to determine if it should look for new packages in a directory. // Here, we force the mtime to be updated to ensure that packages are importable without // manual cache invalidation. // // <https://github.com/python/cpython/blob/8336cb2b6f428246803b02a4e97fce49d0bb1e09/Lib/importlib/_bootstrap_external.py#L1601> let now = SystemTime::now(); // `File.set_modified` is not available in `fs_err` yet #[allow(clippy::disallowed_types)] match std::fs::File::open(site_packages.as_ref()) { Ok(dir) => { if let Err(err) = dir.set_modified(now) { debug!( "Failed to update mtime for {}: {err}", site_packages.as_ref().display() ); } } Err(err) => debug!( "Failed to open {} to update mtime: {err}", site_packages.as_ref().display() ), } Ok(count) } // Hard linking / reflinking might not be supported but we (afaik) can't detect this ahead of time, // so we'll try hard linking / reflinking the first file - if this succeeds we'll know later // errors are not due to lack of os/fs support. If it fails, we'll switch to copying for the rest of the // install. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] enum Attempt { #[default] Initial, Subsequent, UseCopyFallback, } /// Recursively clone the contents of `from` into `to`. /// /// Note the behavior here is platform-dependent. /// /// On macOS, directories can be recursively copied with a single `clonefile` call. So we only /// need to iterate over the top-level of the directory, and copy each file or subdirectory /// unless the subdirectory exists already in which case we'll need to recursively merge its /// contents with the existing directory. /// /// On Linux, we need to always reflink recursively, as `FICLONE` ioctl does not support /// directories. Also note, that reflink is only supported on certain filesystems (btrfs, xfs, /// ...), and only when it does not cross filesystem boundaries. /// /// On Windows, we also always need to reflink recursively, as `FSCTL_DUPLICATE_EXTENTS_TO_FILE` /// ioctl is not supported on directories. Also, it is only supported on certain filesystems /// (ReFS, SMB, ...). fn clone_recursive( site_packages: &Path, wheel: &Path, locks: &Locks, entry: &DirEntry, attempt: &mut Attempt, ) -> Result<(), Error> { // Determine the existing and destination paths. let from = entry.path(); let to = site_packages.join( from.strip_prefix(wheel) .expect("wheel path starts with wheel root"), ); trace!("Cloning {} to {}", from.display(), to.display()); if (cfg!(windows) || cfg!(target_os = "linux")) && from.is_dir() { fs::create_dir_all(&to)?; for entry in fs::read_dir(from)? { clone_recursive(site_packages, wheel, locks, &entry?, attempt)?; } return Ok(()); } match attempt { Attempt::Initial => { if let Err(err) = reflink::reflink(&from, &to) { if err.kind() == std::io::ErrorKind::AlreadyExists { // If cloning or copying fails and the directory exists already, it must be // merged recursively. if entry.file_type()?.is_dir() { for entry in fs::read_dir(from)? { clone_recursive(site_packages, wheel, locks, &entry?, attempt)?; } } else { // If file already exists, overwrite it. let tempdir = tempdir_in(site_packages)?; let tempfile = tempdir.path().join(from.file_name().unwrap()); if reflink::reflink(&from, &tempfile).is_ok() { fs::rename(&tempfile, to)?; } else { debug!( "Failed to clone `{}` to temporary location `{}`, attempting to copy files as a fallback", from.display(), tempfile.display(), ); *attempt = Attempt::UseCopyFallback; synchronized_copy(&from, &to, locks)?; } } } else { debug!( "Failed to clone `{}` to `{}`, attempting to copy files as a fallback", from.display(), to.display() ); // Fallback to copying *attempt = Attempt::UseCopyFallback; clone_recursive(site_packages, wheel, locks, entry, attempt)?; } } } Attempt::Subsequent => { if let Err(err) = reflink::reflink(&from, &to) { if err.kind() == std::io::ErrorKind::AlreadyExists { // If cloning/copying fails and the directory exists already, it must be merged recursively. if entry.file_type()?.is_dir() { for entry in fs::read_dir(from)? { clone_recursive(site_packages, wheel, locks, &entry?, attempt)?; } } else { // If file already exists, overwrite it. let tempdir = tempdir_in(site_packages)?; let tempfile = tempdir.path().join(from.file_name().unwrap()); reflink::reflink(&from, &tempfile)?; fs::rename(&tempfile, to)?; } } else { return Err(Error::Reflink { from, to, err }); } } } Attempt::UseCopyFallback => { if entry.file_type()?.is_dir() { fs::create_dir_all(&to)?; for entry in fs::read_dir(from)? { clone_recursive(site_packages, wheel, locks, &entry?, attempt)?; } } else { synchronized_copy(&from, &to, locks)?; } warn_user_once!( "Failed to clone files; falling back to full copy. This may lead to degraded performance.\n If the cache and target directories are on different filesystems, reflinking may not be supported.\n If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning." ); } } if *attempt == Attempt::Initial { *attempt = Attempt::Subsequent; } Ok(()) } /// Extract a wheel by copying all of its files into site packages. fn copy_wheel_files( site_packages: impl AsRef<Path>, wheel: impl AsRef<Path>, locks: &Locks, filename: &WheelFilename, ) -> Result<usize, Error> { let mut count = 0usize; // Walk over the directory. for entry in WalkDir::new(&wheel) { let entry = entry?; let path = entry.path(); let relative = path.strip_prefix(&wheel).expect("walkdir starts with root"); let out_path = site_packages.as_ref().join(relative); warn_module_conflict(locks, filename, relative); if entry.file_type().is_dir() { fs::create_dir_all(&out_path)?; continue; } synchronized_copy(path, &out_path, locks)?; count += 1; } Ok(count) } /// Extract a wheel by hard-linking all of its files into site packages. fn hardlink_wheel_files( site_packages: impl AsRef<Path>, wheel: impl AsRef<Path>, locks: &Locks, filename: &WheelFilename, ) -> Result<usize, Error> { let mut attempt = Attempt::default(); let mut count = 0usize; // Walk over the directory. for entry in WalkDir::new(&wheel) { let entry = entry?; let path = entry.path(); let relative = path.strip_prefix(&wheel).expect("walkdir starts with root"); let out_path = site_packages.as_ref().join(relative); warn_module_conflict(locks, filename, relative); if entry.file_type().is_dir() { fs::create_dir_all(&out_path)?; continue; } // The `RECORD` file is modified during installation, so we copy it instead of hard-linking. if path.ends_with("RECORD") { synchronized_copy(path, &out_path, locks)?; count += 1; continue; } // Fallback to copying if hardlinks aren't supported for this installation. match attempt { Attempt::Initial => { // Once https://github.com/rust-lang/rust/issues/86442 is stable, use that. attempt = Attempt::Subsequent; if let Err(err) = fs::hard_link(path, &out_path) { // If the file already exists, remove it and try again. if err.kind() == std::io::ErrorKind::AlreadyExists { debug!( "File already exists (initial attempt), overwriting: {}", out_path.display() ); // Removing and recreating would lead to race conditions. let tempdir = tempdir_in(&site_packages)?; let tempfile = tempdir.path().join(entry.file_name()); if fs::hard_link(path, &tempfile).is_ok() { fs_err::rename(&tempfile, &out_path)?; } else { debug!( "Failed to hardlink `{}` to `{}`, attempting to copy files as a fallback", out_path.display(), path.display() ); synchronized_copy(path, &out_path, locks)?; attempt = Attempt::UseCopyFallback; } } else { debug!( "Failed to hardlink `{}` to `{}`, attempting to copy files as a fallback", out_path.display(), path.display() ); synchronized_copy(path, &out_path, locks)?; attempt = Attempt::UseCopyFallback; } } } Attempt::Subsequent => { if let Err(err) = fs::hard_link(path, &out_path) { // If the file already exists, remove it and try again. if err.kind() == std::io::ErrorKind::AlreadyExists { debug!( "File already exists (subsequent attempt), overwriting: {}", out_path.display() ); // Removing and recreating would lead to race conditions. let tempdir = tempdir_in(&site_packages)?; let tempfile = tempdir.path().join(entry.file_name()); fs::hard_link(path, &tempfile)?; fs_err::rename(&tempfile, &out_path)?; } else { return Err(err.into()); } } } Attempt::UseCopyFallback => { synchronized_copy(path, &out_path, locks)?; warn_user_once!( "Failed to hardlink files; falling back to full copy. This may lead to degraded performance.\n If the cache and target directories are on different filesystems, hardlinking may not be supported.\n If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning." ); } } count += 1; } Ok(count) } /// Extract a wheel by symbolically-linking all of its files into site packages. fn symlink_wheel_files( site_packages: impl AsRef<Path>, wheel: impl AsRef<Path>, locks: &Locks, filename: &WheelFilename, ) -> Result<usize, Error> { let mut attempt = Attempt::default(); let mut count = 0usize; // Walk over the directory. for entry in WalkDir::new(&wheel) { let entry = entry?; let path = entry.path(); let relative = path.strip_prefix(&wheel).unwrap(); let out_path = site_packages.as_ref().join(relative); warn_module_conflict(locks, filename, relative); if entry.file_type().is_dir() { fs::create_dir_all(&out_path)?; continue; } // The `RECORD` file is modified during installation, so we copy it instead of symlinking. if path.ends_with("RECORD") { synchronized_copy(path, &out_path, locks)?; count += 1; continue; } // Fallback to copying if symlinks aren't supported for this installation. match attempt { Attempt::Initial => { // Once https://github.com/rust-lang/rust/issues/86442 is stable, use that. attempt = Attempt::Subsequent; if let Err(err) = create_symlink(path, &out_path) { // If the file already exists, remove it and try again. if err.kind() == std::io::ErrorKind::AlreadyExists { debug!( "File already exists (initial attempt), overwriting: {}", out_path.display() ); // Removing and recreating would lead to race conditions. let tempdir = tempdir_in(&site_packages)?; let tempfile = tempdir.path().join(entry.file_name()); if create_symlink(path, &tempfile).is_ok() { fs::rename(&tempfile, &out_path)?; } else { debug!( "Failed to symlink `{}` to `{}`, attempting to copy files as a fallback", out_path.display(), path.display() ); synchronized_copy(path, &out_path, locks)?; attempt = Attempt::UseCopyFallback; } } else { debug!( "Failed to symlink `{}` to `{}`, attempting to copy files as a fallback", out_path.display(), path.display() ); synchronized_copy(path, &out_path, locks)?; attempt = Attempt::UseCopyFallback; } } } Attempt::Subsequent => { if let Err(err) = create_symlink(path, &out_path) { // If the file already exists, remove it and try again. if err.kind() == std::io::ErrorKind::AlreadyExists { debug!( "File already exists (subsequent attempt), overwriting: {}", out_path.display() ); // Removing and recreating would lead to race conditions. let tempdir = tempdir_in(&site_packages)?; let tempfile = tempdir.path().join(entry.file_name()); create_symlink(path, &tempfile)?; fs::rename(&tempfile, &out_path)?; } else { return Err(err.into()); } } } Attempt::UseCopyFallback => { synchronized_copy(path, &out_path, locks)?; warn_user_once!( "Failed to symlink files; falling back to full copy. This may lead to degraded performance.\n If the cache and target directories are on different filesystems, symlinking may not be supported.\n If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning." ); } } count += 1; } Ok(count) } /// Copy from `from` to `to`, ensuring that the parent directory is locked. Avoids simultaneous /// writes to the same file, which can lead to corruption. /// /// See: <https://github.com/astral-sh/uv/issues/4831> fn synchronized_copy(from: &Path, to: &Path, locks: &Locks) -> std::io::Result<()> { // Ensure we have a lock for the directory. let dir_lock = { let mut locks_guard = locks.copy_dir_locks.lock().unwrap(); locks_guard .entry(to.parent().unwrap().to_path_buf()) .or_insert_with(|| Arc::new(Mutex::new(()))) .clone() }; // Acquire a lock on the directory. let _dir_guard = dir_lock.lock().unwrap(); // Copy the file, which will also set its permissions. fs::copy(from, to)?; Ok(()) } /// Warn when a module exists in multiple packages. fn warn_module_conflict(locks: &Locks, filename: &WheelFilename, relative: &Path) { // Check for `__init__.py` to account for namespace packages. // TODO(konsti): We need to warn for overlapping namespace packages, too. if relative.components().count() == 2 && relative.components().next_back().unwrap().as_os_str() == "__init__.py" { // Modules must be UTF-8, but we can skip the conversion using OsStr. locks.warn_module_conflict(relative.components().next().unwrap().as_os_str(), filename); } } #[cfg(unix)] fn create_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> std::io::Result<()> { fs_err::os::unix::fs::symlink(original, link) } #[cfg(windows)] fn create_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> std::io::Result<()> { if original.as_ref().is_dir() { fs_err::os::windows::fs::symlink_dir(original, link) } else { fs_err::os::windows::fs::symlink_file(original, link) } }
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-scripts/src/lib.rs
crates/uv-scripts/src/lib.rs
use std::collections::BTreeMap; use std::io; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::LazyLock; use memchr::memmem::Finder; use serde::Deserialize; use thiserror::Error; use url::Url; use uv_configuration::SourceStrategy; use uv_normalize::PackageName; use uv_pep440::VersionSpecifiers; use uv_pypi_types::VerbatimParsedUrl; use uv_redacted::DisplaySafeUrl; use uv_settings::{GlobalOptions, ResolverInstallerSchema}; use uv_warnings::warn_user; use uv_workspace::pyproject::{ExtraBuildDependency, Sources}; static FINDER: LazyLock<Finder> = LazyLock::new(|| Finder::new(b"# /// script")); /// A PEP 723 item, either read from a script on disk or provided via `stdin`. #[derive(Debug)] pub enum Pep723Item { /// A PEP 723 script read from disk. Script(Pep723Script), /// A PEP 723 script provided via `stdin`. Stdin(Pep723Metadata), /// A PEP 723 script provided via a remote URL. Remote(Pep723Metadata, DisplaySafeUrl), } impl Pep723Item { /// Return the [`Pep723Metadata`] associated with the item. pub fn metadata(&self) -> &Pep723Metadata { match self { Self::Script(script) => &script.metadata, Self::Stdin(metadata) => metadata, Self::Remote(metadata, ..) => metadata, } } /// Consume the item and return the associated [`Pep723Metadata`]. pub fn into_metadata(self) -> Pep723Metadata { match self { Self::Script(script) => script.metadata, Self::Stdin(metadata) => metadata, Self::Remote(metadata, ..) => metadata, } } /// Return the path of the PEP 723 item, if any. pub fn path(&self) -> Option<&Path> { match self { Self::Script(script) => Some(&script.path), Self::Stdin(..) => None, Self::Remote(..) => None, } } /// Return the PEP 723 script, if any. pub fn as_script(&self) -> Option<&Pep723Script> { match self { Self::Script(script) => Some(script), _ => None, } } } /// A reference to a PEP 723 item. #[derive(Debug, Copy, Clone)] pub enum Pep723ItemRef<'item> { /// A PEP 723 script read from disk. Script(&'item Pep723Script), /// A PEP 723 script provided via `stdin`. Stdin(&'item Pep723Metadata), /// A PEP 723 script provided via a remote URL. Remote(&'item Pep723Metadata, &'item Url), } impl Pep723ItemRef<'_> { /// Return the [`Pep723Metadata`] associated with the item. pub fn metadata(&self) -> &Pep723Metadata { match self { Self::Script(script) => &script.metadata, Self::Stdin(metadata) => metadata, Self::Remote(metadata, ..) => metadata, } } /// Return the path of the PEP 723 item, if any. pub fn path(&self) -> Option<&Path> { match self { Self::Script(script) => Some(&script.path), Self::Stdin(..) => None, Self::Remote(..) => None, } } /// Determine the working directory for the script. pub fn directory(&self) -> Result<PathBuf, io::Error> { match self { Self::Script(script) => Ok(std::path::absolute(&script.path)? .parent() .expect("script path has no parent") .to_owned()), Self::Stdin(..) | Self::Remote(..) => std::env::current_dir(), } } /// Collect any `tool.uv.index` from the script. pub fn indexes(&self, source_strategy: SourceStrategy) -> &[uv_distribution_types::Index] { match source_strategy { SourceStrategy::Enabled => self .metadata() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.top_level.index.as_deref()) .unwrap_or(&[]), SourceStrategy::Disabled => &[], } } /// Collect any `tool.uv.sources` from the script. pub fn sources(&self, source_strategy: SourceStrategy) -> &BTreeMap<PackageName, Sources> { static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new(); match source_strategy { SourceStrategy::Enabled => self .metadata() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.sources.as_ref()) .unwrap_or(&EMPTY), SourceStrategy::Disabled => &EMPTY, } } } impl<'item> From<&'item Pep723Item> for Pep723ItemRef<'item> { fn from(item: &'item Pep723Item) -> Self { match item { Pep723Item::Script(script) => Self::Script(script), Pep723Item::Stdin(metadata) => Self::Stdin(metadata), Pep723Item::Remote(metadata, url) => Self::Remote(metadata, url), } } } impl<'item> From<&'item Pep723Script> for Pep723ItemRef<'item> { fn from(script: &'item Pep723Script) -> Self { Self::Script(script) } } /// A PEP 723 script, including its [`Pep723Metadata`]. #[derive(Debug, Clone)] pub struct Pep723Script { /// The path to the Python script. pub path: PathBuf, /// The parsed [`Pep723Metadata`] table from the script. pub metadata: Pep723Metadata, /// The content of the script before the metadata table. pub prelude: String, /// The content of the script after the metadata table. pub postlude: String, } impl Pep723Script { /// Read the PEP 723 `script` metadata from a Python file, if it exists. /// /// Returns `None` if the file is missing a PEP 723 metadata block. /// /// See: <https://peps.python.org/pep-0723/> pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> { let contents = fs_err::tokio::read(&file).await?; // Extract the `script` tag. let ScriptTag { prelude, metadata, postlude, } = match ScriptTag::parse(&contents) { Ok(Some(tag)) => tag, Ok(None) => return Ok(None), Err(err) => return Err(err), }; // Parse the metadata. let metadata = Pep723Metadata::from_str(&metadata)?; Ok(Some(Self { path: std::path::absolute(file)?, metadata, prelude, postlude, })) } /// Reads a Python script and generates a default PEP 723 metadata table. /// /// See: <https://peps.python.org/pep-0723/> pub async fn init( file: impl AsRef<Path>, requires_python: &VersionSpecifiers, ) -> Result<Self, Pep723Error> { let contents = fs_err::tokio::read(&file).await?; let (prelude, metadata, postlude) = Self::init_metadata(&contents, requires_python)?; Ok(Self { path: std::path::absolute(file)?, metadata, prelude, postlude, }) } /// Generates a default PEP 723 metadata table from the provided script contents. /// /// See: <https://peps.python.org/pep-0723/> pub fn init_metadata( contents: &[u8], requires_python: &VersionSpecifiers, ) -> Result<(String, Pep723Metadata, String), Pep723Error> { // Define the default metadata. let default_metadata = if requires_python.is_empty() { indoc::formatdoc! {r" dependencies = [] ", } } else { indoc::formatdoc! {r#" requires-python = "{requires_python}" dependencies = [] "#, requires_python = requires_python, } }; let metadata = Pep723Metadata::from_str(&default_metadata)?; // Extract the shebang and script content. let (shebang, postlude) = extract_shebang(contents)?; // Add a newline to the beginning if it starts with a valid metadata comment line. let postlude = if postlude.strip_prefix('#').is_some_and(|postlude| { postlude .chars() .next() .is_some_and(|c| matches!(c, ' ' | '\r' | '\n')) }) { format!("\n{postlude}") } else { postlude }; Ok(( if shebang.is_empty() { String::new() } else { format!("{shebang}\n") }, metadata, postlude, )) } /// Create a PEP 723 script at the given path. pub async fn create( file: impl AsRef<Path>, requires_python: &VersionSpecifiers, existing_contents: Option<Vec<u8>>, bare: bool, ) -> Result<(), Pep723Error> { let file = file.as_ref(); let script_name = file .file_name() .and_then(|name| name.to_str()) .ok_or_else(|| Pep723Error::InvalidFilename(file.to_string_lossy().to_string()))?; let default_metadata = indoc::formatdoc! {r#" requires-python = "{requires_python}" dependencies = [] "#, }; let metadata = serialize_metadata(&default_metadata); let script = if let Some(existing_contents) = existing_contents { let (mut shebang, contents) = extract_shebang(&existing_contents)?; if !shebang.is_empty() { shebang.push_str("\n#\n"); // If the shebang doesn't contain `uv`, it's probably something like // `#! /usr/bin/env python`, which isn't going to respect the inline metadata. // Issue a warning for users who might not know that. // TODO: There are a lot of mistakes we could consider detecting here, like // `uv run` without `--script` when the file doesn't end in `.py`. if !regex::Regex::new(r"\buv\b").unwrap().is_match(&shebang) { warn_user!( "If you execute {} directly, it might ignore its inline metadata.\nConsider replacing its shebang with: {}", file.to_string_lossy().cyan(), "#!/usr/bin/env -S uv run --script".cyan(), ); } } indoc::formatdoc! {r" {shebang}{metadata} {contents}" } } else if bare { metadata } else { indoc::formatdoc! {r#" {metadata} def main() -> None: print("Hello from {name}!") if __name__ == "__main__": main() "#, metadata = metadata, name = script_name, } }; Ok(fs_err::tokio::write(file, script).await?) } /// Replace the existing metadata in the file with new metadata and write the updated content. pub fn write(&self, metadata: &str) -> Result<(), io::Error> { let content = format!( "{}{}{}", self.prelude, serialize_metadata(metadata), self.postlude ); fs_err::write(&self.path, content)?; Ok(()) } /// Return the [`Sources`] defined in the PEP 723 metadata. pub fn sources(&self) -> &BTreeMap<PackageName, Sources> { static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new(); self.metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.sources.as_ref()) .unwrap_or(&EMPTY) } } /// PEP 723 metadata as parsed from a `script` comment block. /// /// See: <https://peps.python.org/pep-0723/> #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "kebab-case")] pub struct Pep723Metadata { pub dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>, pub requires_python: Option<VersionSpecifiers>, pub tool: Option<Tool>, /// The raw unserialized document. #[serde(skip)] pub raw: String, } impl Pep723Metadata { /// Parse the PEP 723 metadata from `stdin`. pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> { // Extract the `script` tag. let ScriptTag { metadata, .. } = match ScriptTag::parse(contents) { Ok(Some(tag)) => tag, Ok(None) => return Ok(None), Err(err) => return Err(err), }; // Parse the metadata. Ok(Some(Self::from_str(&metadata)?)) } /// Read the PEP 723 `script` metadata from a Python file, if it exists. /// /// Returns `None` if the file is missing a PEP 723 metadata block. /// /// See: <https://peps.python.org/pep-0723/> pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> { let contents = fs_err::tokio::read(&file).await?; // Extract the `script` tag. let ScriptTag { metadata, .. } = match ScriptTag::parse(&contents) { Ok(Some(tag)) => tag, Ok(None) => return Ok(None), Err(err) => return Err(err), }; // Parse the metadata. Ok(Some(Self::from_str(&metadata)?)) } } impl FromStr for Pep723Metadata { type Err = toml::de::Error; /// Parse `Pep723Metadata` from a raw TOML string. fn from_str(raw: &str) -> Result<Self, Self::Err> { let metadata = toml::from_str(raw)?; Ok(Self { raw: raw.to_string(), ..metadata }) } } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct Tool { pub uv: Option<ToolUv>, } #[derive(Debug, Deserialize, Clone)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct ToolUv { #[serde(flatten)] pub globals: GlobalOptions, #[serde(flatten)] pub top_level: ResolverInstallerSchema, pub override_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>, pub exclude_dependencies: Option<Vec<uv_normalize::PackageName>>, pub constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>, pub build_constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>, pub extra_build_dependencies: Option<BTreeMap<PackageName, Vec<ExtraBuildDependency>>>, pub sources: Option<BTreeMap<PackageName, Sources>>, } #[derive(Debug, Error)] pub enum Pep723Error { #[error( "An opening tag (`# /// script`) was found without a closing tag (`# ///`). Ensure that every line between the opening and closing tags (including empty lines) starts with a leading `#`." )] UnclosedBlock, #[error("The PEP 723 metadata block is missing from the script.")] MissingTag, #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), #[error(transparent)] Toml(#[from] toml::de::Error), #[error("Invalid filename `{0}` supplied")] InvalidFilename(String), } #[derive(Debug, Clone, Eq, PartialEq)] pub struct ScriptTag { /// The content of the script before the metadata block. prelude: String, /// The metadata block. metadata: String, /// The content of the script after the metadata block. postlude: String, } impl ScriptTag { /// Given the contents of a Python file, extract the `script` metadata block with leading /// comment hashes removed, any preceding shebang or content (prelude), and the remaining Python /// script. /// /// Given the following input string representing the contents of a Python script: /// /// ```python /// #!/usr/bin/env python3 /// # /// script /// # requires-python = '>=3.11' /// # dependencies = [ /// # 'requests<3', /// # 'rich', /// # ] /// # /// /// /// import requests /// /// print("Hello, World!") /// ``` /// /// This function would return: /// /// - Preamble: `#!/usr/bin/env python3\n` /// - Metadata: `requires-python = '>=3.11'\ndependencies = [\n 'requests<3',\n 'rich',\n]` /// - Postlude: `import requests\n\nprint("Hello, World!")\n` /// /// See: <https://peps.python.org/pep-0723/> pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> { // Identify the opening pragma. let Some(index) = FINDER.find(contents) else { return Ok(None); }; // The opening pragma must be the first line, or immediately preceded by a newline. if !(index == 0 || matches!(contents[index - 1], b'\r' | b'\n')) { return Ok(None); } // Extract the preceding content. let prelude = std::str::from_utf8(&contents[..index])?; // Decode as UTF-8. let contents = &contents[index..]; let contents = std::str::from_utf8(contents)?; let mut lines = contents.lines(); // Ensure that the first line is exactly `# /// script`. if lines.next().is_none_or(|line| line != "# /// script") { return Ok(None); } // > Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting // > with #. If there are characters after the # then the first character MUST be a space. The // > embedded content is formed by taking away the first two characters of each line if the // > second character is a space, otherwise just the first character (which means the line // > consists of only a single #). let mut toml = vec![]; for line in lines { // Remove the leading `#`. let Some(line) = line.strip_prefix('#') else { break; }; // If the line is empty, continue. if line.is_empty() { toml.push(""); continue; } // Otherwise, the line _must_ start with ` `. let Some(line) = line.strip_prefix(' ') else { break; }; toml.push(line); } // Find the closing `# ///`. The precedence is such that we need to identify the _last_ such // line. // // For example, given: // ```python // # /// script // # // # /// // # // # /// // ``` // // The latter `///` is the closing pragma let Some(index) = toml.iter().rev().position(|line| *line == "///") else { return Err(Pep723Error::UnclosedBlock); }; let index = toml.len() - index; // Discard any lines after the closing `# ///`. // // For example, given: // ```python // # /// script // # // # /// // # // # // ``` // // We need to discard the last two lines. toml.truncate(index - 1); // Join the lines into a single string. let prelude = prelude.to_string(); let metadata = toml.join("\n") + "\n"; let postlude = contents .lines() .skip(index + 1) .collect::<Vec<_>>() .join("\n") + "\n"; Ok(Some(Self { prelude, metadata, postlude, })) } } /// Extracts the shebang line from the given file contents and returns it along with the remaining /// content. fn extract_shebang(contents: &[u8]) -> Result<(String, String), Pep723Error> { let contents = std::str::from_utf8(contents)?; if contents.starts_with("#!") { // Find the first newline. let bytes = contents.as_bytes(); let index = bytes .iter() .position(|&b| b == b'\r' || b == b'\n') .unwrap_or(bytes.len()); // Support `\r`, `\n`, and `\r\n` line endings. let width = match bytes.get(index) { Some(b'\r') => { if bytes.get(index + 1) == Some(&b'\n') { 2 } else { 1 } } Some(b'\n') => 1, _ => 0, }; // Extract the shebang line. let shebang = contents[..index].to_string(); let script = contents[index + width..].to_string(); Ok((shebang, script)) } else { Ok((String::new(), contents.to_string())) } } /// Formats the provided metadata by prefixing each line with `#` and wrapping it with script markers. fn serialize_metadata(metadata: &str) -> String { let mut output = String::with_capacity(metadata.len() + 32); output.push_str("# /// script"); output.push('\n'); for line in metadata.lines() { output.push('#'); if !line.is_empty() { output.push(' '); output.push_str(line); } output.push('\n'); } output.push_str("# ///"); output.push('\n'); output } #[cfg(test)] mod tests { use crate::{Pep723Error, Pep723Script, ScriptTag, serialize_metadata}; use std::str::FromStr; #[test] fn missing_space() { let contents = indoc::indoc! {r" # /// script #requires-python = '>=3.11' # /// "}; assert!(matches!( ScriptTag::parse(contents.as_bytes()), Err(Pep723Error::UnclosedBlock) )); } #[test] fn no_closing_pragma() { let contents = indoc::indoc! {r" # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] "}; assert!(matches!( ScriptTag::parse(contents.as_bytes()), Err(Pep723Error::UnclosedBlock) )); } #[test] fn leading_content() { let contents = indoc::indoc! {r" pass # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # /// # # "}; assert_eq!(ScriptTag::parse(contents.as_bytes()).unwrap(), None); } #[test] fn simple() { let contents = indoc::indoc! {r" # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # /// import requests from rich.pretty import pprint resp = requests.get('https://peps.python.org/api/peps.json') data = resp.json() "}; let expected_metadata = indoc::indoc! {r" requires-python = '>=3.11' dependencies = [ 'requests<3', 'rich', ] "}; let expected_data = indoc::indoc! {r" import requests from rich.pretty import pprint resp = requests.get('https://peps.python.org/api/peps.json') data = resp.json() "}; let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap(); assert_eq!(actual.prelude, String::new()); assert_eq!(actual.metadata, expected_metadata); assert_eq!(actual.postlude, expected_data); } #[test] fn simple_with_shebang() { let contents = indoc::indoc! {r" #!/usr/bin/env python3 # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # /// import requests from rich.pretty import pprint resp = requests.get('https://peps.python.org/api/peps.json') data = resp.json() "}; let expected_metadata = indoc::indoc! {r" requires-python = '>=3.11' dependencies = [ 'requests<3', 'rich', ] "}; let expected_data = indoc::indoc! {r" import requests from rich.pretty import pprint resp = requests.get('https://peps.python.org/api/peps.json') data = resp.json() "}; let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap(); assert_eq!(actual.prelude, "#!/usr/bin/env python3\n".to_string()); assert_eq!(actual.metadata, expected_metadata); assert_eq!(actual.postlude, expected_data); } #[test] fn embedded_comment() { let contents = indoc::indoc! {r" # /// script # embedded-csharp = ''' # /// <summary> # /// text # /// # /// </summary> # public class MyClass { } # ''' # /// "}; let expected = indoc::indoc! {r" embedded-csharp = ''' /// <summary> /// text /// /// </summary> public class MyClass { } ''' "}; let actual = ScriptTag::parse(contents.as_bytes()) .unwrap() .unwrap() .metadata; assert_eq!(actual, expected); } #[test] fn trailing_lines() { let contents = indoc::indoc! {r" # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # /// # # "}; let expected = indoc::indoc! {r" requires-python = '>=3.11' dependencies = [ 'requests<3', 'rich', ] "}; let actual = ScriptTag::parse(contents.as_bytes()) .unwrap() .unwrap() .metadata; assert_eq!(actual, expected); } #[test] fn serialize_metadata_formatting() { let metadata = indoc::indoc! {r" requires-python = '>=3.11' dependencies = [ 'requests<3', 'rich', ] "}; let expected_output = indoc::indoc! {r" # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # /// "}; let result = serialize_metadata(metadata); assert_eq!(result, expected_output); } #[test] fn serialize_metadata_empty() { let metadata = ""; let expected_output = "# /// script\n# ///\n"; let result = serialize_metadata(metadata); assert_eq!(result, expected_output); } #[test] fn script_init_empty() { let contents = "".as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); assert_eq!(postlude, ""); } #[test] fn script_init_requires_python() { let contents = "".as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata( contents, &uv_pep440::VersionSpecifiers::from_str(">=3.8").unwrap(), ) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r#" requires-python = ">=3.8" dependencies = [] "#} ); assert_eq!(postlude, ""); } #[test] fn script_init_with_hashbang() { let contents = indoc::indoc! {r#" #!/usr/bin/env python3 print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, "#!/usr/bin/env python3\n"); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); assert_eq!( postlude, indoc::indoc! {r#" print("Hello, world!") "#} ); } #[test] fn script_init_with_other_metadata() { let contents = indoc::indoc! {r#" # /// noscript # Hello, # # World! # /// print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); // Note the extra line at the beginning. assert_eq!( postlude, indoc::indoc! {r#" # /// noscript # Hello, # # World! # /// print("Hello, world!") "#} ); } #[test] fn script_init_with_hashbang_and_other_metadata() { let contents = indoc::indoc! {r#" #!/usr/bin/env python3 # /// noscript # Hello, # # World! # /// print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, "#!/usr/bin/env python3\n"); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); // Note the extra line at the beginning. assert_eq!( postlude, indoc::indoc! {r#" # /// noscript # Hello, # # World! # /// print("Hello, world!") "#} ); } #[test] fn script_init_with_valid_metadata_line() { let contents = indoc::indoc! {r#" # Hello, # /// noscript # # World! # /// print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); // Note the extra line at the beginning. assert_eq!( postlude, indoc::indoc! {r#" # Hello, # /// noscript # # World! # /// print("Hello, world!") "#} ); } #[test] fn script_init_with_valid_empty_metadata_line() { let contents = indoc::indoc! {r#" # # /// noscript # Hello, # World! # /// print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); // Note the extra line at the beginning. assert_eq!( postlude, indoc::indoc! {r#" # # /// noscript # Hello, # World! # /// print("Hello, world!") "#} ); } #[test] fn script_init_with_non_metadata_comment() { let contents = indoc::indoc! {r#" #Hello, # /// noscript # # World! # /// print("Hello, world!") "#} .as_bytes(); let (prelude, metadata, postlude) = Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default()) .unwrap(); assert_eq!(prelude, ""); assert_eq!( metadata.raw, indoc::indoc! {r" dependencies = [] "} ); assert_eq!( postlude, indoc::indoc! {r#" #Hello, # /// noscript # # World! # /// print("Hello, world!") "#} ); } }
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-console/src/lib.rs
crates/uv-console/src/lib.rs
use console::{Key, Term, measure_text_width, style}; use std::{cmp::Ordering, iter}; /// Prompt the user for confirmation in the given [`Term`]. /// /// This is a slimmed-down version of `dialoguer::Confirm`, with the post-confirmation report /// enabled. pub fn confirm(message: &str, term: &Term, default: bool) -> std::io::Result<bool> { confirm_inner(message, None, term, default) } /// Prompt the user for confirmation in the given [`Term`], with a hint. pub fn confirm_with_hint( message: &str, hint: &str, term: &Term, default: bool, ) -> std::io::Result<bool> { confirm_inner(message, Some(hint), term, default) } fn confirm_inner( message: &str, hint: Option<&str>, term: &Term, default: bool, ) -> std::io::Result<bool> { let prompt = format!( "{} {} {} {} {}", style("?".to_string()).for_stderr().yellow(), style(message).for_stderr().bold(), style("[y/n]").for_stderr().black().bright(), style("›").for_stderr().black().bright(), style(if default { "yes" } else { "no" }) .for_stderr() .cyan(), ); term.write_str(&prompt)?; if let Some(hint) = hint { term.write_str(&format!( "\n\n{}{} {hint}", style("hint").for_stderr().bold().cyan(), style(":").for_stderr().bold() ))?; } term.hide_cursor()?; term.flush()?; // Match continuously on every keystroke, and do not wait for user to hit the // `Enter` key. let response = loop { let input = term.read_key_raw()?; match input { Key::Char('y' | 'Y') => break true, Key::Char('n' | 'N') => break false, Key::Enter => break default, Key::CtrlC => { let term = Term::stderr(); term.show_cursor()?; term.write_str("\n")?; term.flush()?; #[allow(clippy::exit, clippy::cast_possible_wrap)] std::process::exit(if cfg!(windows) { 0xC000_013A_u32 as i32 } else { 130 }); } _ => {} } }; let report = format!( "{} {} {} {}", style("✔".to_string()).for_stderr().green(), style(message).for_stderr().bold(), style("·").for_stderr().black().bright(), style(if response { "yes" } else { "no" }) .for_stderr() .cyan(), ); if hint.is_some() { term.clear_last_lines(2)?; // It's not clear why we need to clear to the end of the screen here, but it fixes lingering // display of the hint on `bash` (the issue did not reproduce on `zsh`). term.clear_to_end_of_screen()?; } else { term.clear_line()?; } term.write_line(&report)?; term.show_cursor()?; term.flush()?; Ok(response) } /// Prompt the user for password in the given [`Term`]. /// /// This is a slimmed-down version of `dialoguer::Password`. pub fn password(prompt: &str, term: &Term) -> std::io::Result<String> { term.write_str(prompt)?; term.show_cursor()?; term.flush()?; let input = term.read_secure_line()?; term.clear_line()?; Ok(input) } /// Prompt the user for username in the given [`Term`]. pub fn username(prompt: &str, term: &Term) -> std::io::Result<String> { term.write_str(prompt)?; term.show_cursor()?; term.flush()?; let input = term.read_line()?; term.clear_line()?; Ok(input) } /// Prompt the user for input text in the given [`Term`]. /// /// This is a slimmed-down version of `dialoguer::Input`. #[allow( // Suppress Clippy lints triggered by `dialoguer::Input`. clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss )] pub fn input(prompt: &str, term: &Term) -> std::io::Result<String> { term.write_str(prompt)?; term.show_cursor()?; term.flush()?; let prompt_len = measure_text_width(prompt); let mut chars: Vec<char> = Vec::new(); let mut position = 0; loop { match term.read_key()? { Key::Backspace if position > 0 => { position -= 1; chars.remove(position); let line_size = term.size().1 as usize; // Case we want to delete last char of a line so the cursor is at the beginning of the next line if (position + prompt_len).is_multiple_of(line_size - 1) { term.clear_line()?; term.move_cursor_up(1)?; term.move_cursor_right(line_size + 1)?; } else { term.clear_chars(1)?; } let tail: String = chars[position..].iter().collect(); if !tail.is_empty() { term.write_str(&tail)?; let total = position + prompt_len + tail.chars().count(); let total_line = total / line_size; let line_cursor = (position + prompt_len) / line_size; term.move_cursor_up(total_line - line_cursor)?; term.move_cursor_left(line_size)?; term.move_cursor_right((position + prompt_len) % line_size)?; } term.flush()?; } Key::Char(chr) if !chr.is_ascii_control() => { chars.insert(position, chr); position += 1; let tail: String = iter::once(&chr).chain(chars[position..].iter()).collect(); term.write_str(&tail)?; term.move_cursor_left(tail.chars().count() - 1)?; term.flush()?; } Key::ArrowLeft if position > 0 => { if (position + prompt_len).is_multiple_of(term.size().1 as usize) { term.move_cursor_up(1)?; term.move_cursor_right(term.size().1 as usize)?; } else { term.move_cursor_left(1)?; } position -= 1; term.flush()?; } Key::ArrowRight if position < chars.len() => { if (position + prompt_len).is_multiple_of(term.size().1 as usize - 1) { term.move_cursor_down(1)?; term.move_cursor_left(term.size().1 as usize)?; } else { term.move_cursor_right(1)?; } position += 1; term.flush()?; } Key::UnknownEscSeq(seq) if seq == vec!['b'] => { let line_size = term.size().1 as usize; let nb_space = chars[..position] .iter() .rev() .take_while(|c| c.is_whitespace()) .count(); let find_last_space = chars[..position - nb_space] .iter() .rposition(|c| c.is_whitespace()); // If we find a space we set the cursor to the next char else we set it to the beginning of the input if let Some(mut last_space) = find_last_space { if last_space < position { last_space += 1; let new_line = (prompt_len + last_space) / line_size; let old_line = (prompt_len + position) / line_size; let diff_line = old_line - new_line; if diff_line != 0 { term.move_cursor_up(old_line - new_line)?; } let new_pos_x = (prompt_len + last_space) % line_size; let old_pos_x = (prompt_len + position) % line_size; let diff_pos_x = new_pos_x as i64 - old_pos_x as i64; if diff_pos_x < 0 { term.move_cursor_left(-diff_pos_x as usize)?; } else { term.move_cursor_right((diff_pos_x) as usize)?; } position = last_space; } } else { term.move_cursor_left(position)?; position = 0; } term.flush()?; } Key::UnknownEscSeq(seq) if seq == vec!['f'] => { let line_size = term.size().1 as usize; let find_next_space = chars[position..].iter().position(|c| c.is_whitespace()); // If we find a space we set the cursor to the next char else we set it to the beginning of the input if let Some(mut next_space) = find_next_space { let nb_space = chars[position + next_space..] .iter() .take_while(|c| c.is_whitespace()) .count(); next_space += nb_space; let new_line = (prompt_len + position + next_space) / line_size; let old_line = (prompt_len + position) / line_size; term.move_cursor_down(new_line - old_line)?; let new_pos_x = (prompt_len + position + next_space) % line_size; let old_pos_x = (prompt_len + position) % line_size; let diff_pos_x = new_pos_x as i64 - old_pos_x as i64; if diff_pos_x < 0 { term.move_cursor_left(-diff_pos_x as usize)?; } else { term.move_cursor_right((diff_pos_x) as usize)?; } position += next_space; } else { let new_line = (prompt_len + chars.len()) / line_size; let old_line = (prompt_len + position) / line_size; term.move_cursor_down(new_line - old_line)?; let new_pos_x = (prompt_len + chars.len()) % line_size; let old_pos_x = (prompt_len + position) % line_size; let diff_pos_x = new_pos_x as i64 - old_pos_x as i64; match diff_pos_x.cmp(&0) { Ordering::Less => { term.move_cursor_left((-diff_pos_x - 1) as usize)?; } Ordering::Equal => {} Ordering::Greater => { term.move_cursor_right((diff_pos_x) as usize)?; } } position = chars.len(); } term.flush()?; } Key::Enter => break, _ => (), } } let input = chars.iter().collect::<String>(); term.write_line("")?; Ok(input) } /// Formats a number of bytes into a human readable SI-prefixed size (binary units). /// /// Returns a tuple of `(quantity, units)`. #[allow( clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_precision_loss, clippy::cast_sign_loss )] pub fn human_readable_bytes(bytes: u64) -> (f32, &'static str) { const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; let bytes_f32 = bytes as f32; let i = ((bytes_f32.log2() / 10.0) as usize).min(UNITS.len() - 1); (bytes_f32 / 1024_f32.powi(i as i32), UNITS[i]) }
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.rs
crates/uv/build.rs
//! This embeds a "manifest" - a special XML document - into the uv binary on Windows builds. //! //! It includes reasonable defaults for Windows binaries: //! - `System` codepage to retain backwards compatibility with previous uv releases. //! We can set to the utf-8 codepage in a future breaking release which lets us use the //! *A versions of Windows API functions without utf-16 conversion. //! - Long path awareness allows paths longer than 260 characters in Windows operations. //! This still requires `LongPathsEnabled` to be set in the Windows registry. //! - Declared Windows 7-10+ compatibility to avoid legacy compat layers from being potentially //! applied by not specifying any. This does not imply actual Windows 7, 8.0, 8.1 support. In //! cases where the application is run on Windows 7, the app is treated as Windows 7 aware //! rather than an unspecified legacy application (e.g. Windows XP). //! - Standard invoker execution levels for CLI applications to disable UAC virtualization. //! //! See <https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests> use embed_manifest::manifest::{ActiveCodePage, ExecutionLevel, Setting, SupportedOS}; use embed_manifest::{embed_manifest, empty_manifest}; use uv_static::EnvVars; fn main() { if std::env::var_os(EnvVars::CARGO_CFG_WINDOWS).is_some() { let [major, minor, patch] = uv_version::version() .splitn(3, '.') .map(str::parse) .collect::<Result<Vec<u16>, _>>() .ok() .and_then(|v| v.try_into().ok()) .expect("uv version must be in x.y.z format"); let manifest = empty_manifest() .name("uv") .version(major, minor, patch, 0) .active_code_page(ActiveCodePage::System) // "Windows10" includes Windows 10 and 11, and Windows Server 2016, 2019 and 2022 .supported_os(SupportedOS::Windows7..=SupportedOS::Windows10) .requested_execution_level(ExecutionLevel::AsInvoker) .long_path_aware(Setting::Enabled); embed_manifest(manifest).expect("unable to embed manifest"); } println!("cargo:rerun-if-changed=build.rs"); }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/settings.rs
crates/uv/src/settings.rs
use std::env::VarError; use std::num::NonZeroUsize; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::time::Duration; use crate::commands::{PythonUpgrade, PythonUpgradeSource}; use uv_auth::Service; use uv_cache::{CacheArgs, Refresh}; use uv_cli::comma::CommaSeparatedRequirements; use uv_cli::{ AddArgs, AuthLoginArgs, AuthLogoutArgs, AuthTokenArgs, ColorChoice, ExternalCommand, GlobalArgs, InitArgs, ListFormat, LockArgs, Maybe, PipCheckArgs, PipCompileArgs, PipFreezeArgs, PipInstallArgs, PipListArgs, PipShowArgs, PipSyncArgs, PipTreeArgs, PipUninstallArgs, PythonFindArgs, PythonInstallArgs, PythonListArgs, PythonListFormat, PythonPinArgs, PythonUninstallArgs, PythonUpgradeArgs, RemoveArgs, RunArgs, SyncArgs, SyncFormat, ToolDirArgs, ToolInstallArgs, ToolListArgs, ToolRunArgs, ToolUninstallArgs, TreeArgs, VenvArgs, VersionArgs, VersionBumpSpec, VersionFormat, }; use uv_cli::{ AuthorFrom, BuildArgs, ExportArgs, FormatArgs, PublishArgs, PythonDirArgs, ResolverInstallerArgs, ToolUpgradeArgs, options::{flag, resolver_installer_options, resolver_options}, }; use uv_client::Connectivity; use uv_configuration::{ BuildIsolation, BuildOptions, Concurrency, DependencyGroups, DryRun, EditableMode, EnvFile, ExportFormat, ExtrasSpecification, GitLfsSetting, HashCheckingMode, IndexStrategy, InstallOptions, KeyringProviderType, NoBinary, NoBuild, PipCompileFormat, ProjectBuildBackend, Reinstall, RequiredVersion, SourceStrategy, TargetTriple, TrustedHost, TrustedPublishing, Upgrade, VersionControlSystem, }; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildVariables, Index, IndexLocations, IndexUrl, PackageConfigSettings, Requirement, }; use uv_install_wheel::LinkMode; use uv_normalize::{ExtraName, PackageName, PipGroupName}; use uv_pep508::{MarkerTree, RequirementOrigin}; use uv_preview::Preview; use uv_pypi_types::SupportedEnvironments; use uv_python::{Prefix, PythonDownloads, PythonPreference, PythonVersion, Target}; use uv_redacted::DisplaySafeUrl; use uv_resolver::{ AnnotationStyle, DependencyMode, ExcludeNewer, ExcludeNewerPackage, ForkStrategy, PrereleaseMode, ResolutionMode, }; use uv_settings::{ Combine, EnvironmentOptions, FilesystemOptions, Options, PipOptions, PublishOptions, PythonInstallMirrors, ResolverInstallerOptions, ResolverInstallerSchema, ResolverOptions, }; use uv_static::EnvVars; use uv_torch::TorchMode; use uv_warnings::warn_user_once; use uv_workspace::pyproject::{DependencyType, ExtraBuildDependencies}; use uv_workspace::pyproject_mut::AddBoundsKind; use crate::commands::ToolRunCommand; use crate::commands::{InitKind, InitProjectKind, pip::operations::Modifications}; /// The default publish URL. const PYPI_PUBLISH_URL: &str = "https://upload.pypi.org/legacy/"; /// The resolved global settings to use for any invocation of the CLI. #[derive(Debug, Clone)] pub(crate) struct GlobalSettings { pub(crate) required_version: Option<RequiredVersion>, pub(crate) quiet: u8, pub(crate) verbose: u8, pub(crate) color: ColorChoice, pub(crate) network_settings: NetworkSettings, pub(crate) concurrency: Concurrency, pub(crate) show_settings: bool, pub(crate) preview: Preview, pub(crate) python_preference: PythonPreference, pub(crate) python_downloads: PythonDownloads, pub(crate) no_progress: bool, pub(crate) installer_metadata: bool, } impl GlobalSettings { /// Resolve the [`GlobalSettings`] from the CLI and filesystem configuration. pub(crate) fn resolve( args: &GlobalArgs, workspace: Option<&FilesystemOptions>, environment: &EnvironmentOptions, ) -> Self { let network_settings = NetworkSettings::resolve(args, workspace, environment); let python_preference = resolve_python_preference(args, workspace); Self { required_version: workspace .and_then(|workspace| workspace.globals.required_version.clone()), quiet: args.quiet, verbose: args.verbose, color: if let Some(color_choice) = args.color { // If `--color` is passed explicitly, use its value. color_choice } else if args.no_color { // If `--no-color` is passed explicitly, disable color output. ColorChoice::Never } else if std::env::var_os(EnvVars::NO_COLOR) .filter(|v| !v.is_empty()) .is_some() { // If the `NO_COLOR` is set, disable color output. ColorChoice::Never } else if std::env::var_os(EnvVars::FORCE_COLOR) .filter(|v| !v.is_empty()) .is_some() || std::env::var_os(EnvVars::CLICOLOR_FORCE) .filter(|v| !v.is_empty()) .is_some() { // If `FORCE_COLOR` or `CLICOLOR_FORCE` is set, always enable color output. ColorChoice::Always } else { ColorChoice::Auto }, network_settings, concurrency: Concurrency { downloads: environment .concurrency .downloads .combine(workspace.and_then(|workspace| workspace.globals.concurrent_downloads)) .map(NonZeroUsize::get) .unwrap_or(Concurrency::DEFAULT_DOWNLOADS), builds: environment .concurrency .builds .combine(workspace.and_then(|workspace| workspace.globals.concurrent_builds)) .map(NonZeroUsize::get) .unwrap_or_else(Concurrency::threads), installs: environment .concurrency .installs .combine(workspace.and_then(|workspace| workspace.globals.concurrent_installs)) .map(NonZeroUsize::get) .unwrap_or_else(Concurrency::threads), }, show_settings: args.show_settings, preview: Preview::from_args( flag(args.preview, args.no_preview, "preview") .combine(workspace.and_then(|workspace| workspace.globals.preview)) .unwrap_or(false), args.no_preview, &args.preview_features, ), python_preference, python_downloads: flag( args.allow_python_downloads, args.no_python_downloads, "python-downloads", ) .map(PythonDownloads::from) .combine(env(env::UV_PYTHON_DOWNLOADS)) .combine(workspace.and_then(|workspace| workspace.globals.python_downloads)) .unwrap_or_default(), // Disable the progress bar with `RUST_LOG` to avoid progress fragments interleaving // with log messages. no_progress: args.no_progress || std::env::var_os(EnvVars::RUST_LOG).is_some(), installer_metadata: !args.no_installer_metadata, } } } fn resolve_python_preference( args: &GlobalArgs, workspace: Option<&FilesystemOptions>, ) -> PythonPreference { if args.managed_python { PythonPreference::OnlyManaged } else if args.no_managed_python { PythonPreference::OnlySystem } else { args.python_preference .combine(workspace.and_then(|workspace| workspace.globals.python_preference)) .unwrap_or_default() } } /// The resolved network settings to use for any invocation of the CLI. #[derive(Debug, Clone)] pub(crate) struct NetworkSettings { pub(crate) connectivity: Connectivity, pub(crate) native_tls: bool, pub(crate) allow_insecure_host: Vec<TrustedHost>, pub(crate) timeout: Duration, pub(crate) retries: u32, } impl NetworkSettings { pub(crate) fn resolve( args: &GlobalArgs, workspace: Option<&FilesystemOptions>, environment: &EnvironmentOptions, ) -> Self { let connectivity = if flag(args.offline, args.no_offline, "offline") .combine(workspace.and_then(|workspace| workspace.globals.offline)) .unwrap_or(false) { Connectivity::Offline } else { Connectivity::Online }; let native_tls = flag(args.native_tls, args.no_native_tls, "native-tls") .combine(workspace.and_then(|workspace| workspace.globals.native_tls)) .unwrap_or(false); let allow_insecure_host = args .allow_insecure_host .as_ref() .map(|allow_insecure_host| { allow_insecure_host .iter() .filter_map(|value| value.clone().into_option()) }) .into_iter() .flatten() .chain( workspace .and_then(|workspace| workspace.globals.allow_insecure_host.clone()) .into_iter() .flatten(), ) .collect(); Self { connectivity, native_tls, allow_insecure_host, timeout: environment.http_timeout, retries: environment.http_retries, } } } /// The resolved cache settings to use for any invocation of the CLI. #[derive(Debug, Clone)] pub(crate) struct CacheSettings { pub(crate) no_cache: bool, pub(crate) cache_dir: Option<PathBuf>, } impl CacheSettings { /// Resolve the [`CacheSettings`] from the CLI and filesystem configuration. pub(crate) fn resolve(args: CacheArgs, workspace: Option<&FilesystemOptions>) -> Self { Self { no_cache: args.no_cache || workspace .and_then(|workspace| workspace.globals.no_cache) .unwrap_or(false), cache_dir: args .cache_dir .or_else(|| workspace.and_then(|workspace| workspace.globals.cache_dir.clone())), } } } /// The resolved settings to use for a `init` invocation. #[derive(Debug, Clone)] pub(crate) struct InitSettings { pub(crate) path: Option<PathBuf>, pub(crate) name: Option<PackageName>, pub(crate) package: bool, pub(crate) kind: InitKind, pub(crate) bare: bool, pub(crate) description: Option<String>, pub(crate) no_description: bool, pub(crate) vcs: Option<VersionControlSystem>, pub(crate) build_backend: Option<ProjectBuildBackend>, pub(crate) no_readme: bool, pub(crate) author_from: Option<AuthorFrom>, pub(crate) pin_python: bool, pub(crate) no_workspace: bool, pub(crate) python: Option<String>, pub(crate) install_mirrors: PythonInstallMirrors, } impl InitSettings { /// Resolve the [`InitSettings`] from the CLI and filesystem configuration. #[allow(clippy::needless_pass_by_value)] pub(crate) fn resolve( args: InitArgs, filesystem: Option<FilesystemOptions>, environment: EnvironmentOptions, ) -> Self { let InitArgs { path, name, r#virtual, package, no_package, bare, app, lib, script, description, no_description, vcs, build_backend, no_readme, author_from, no_pin_python, pin_python, no_workspace, python, .. } = args; let kind = match (app, lib, script) { (true, false, false) => InitKind::Project(InitProjectKind::Application), (false, true, false) => InitKind::Project(InitProjectKind::Library), (false, false, true) => InitKind::Script, (false, false, false) => InitKind::default(), (_, _, _) => unreachable!("`app`, `lib`, and `script` are mutually exclusive"), }; let package = flag( package || build_backend.is_some(), no_package || r#virtual, "virtual", ) .unwrap_or(kind.packaged_by_default()); let filesystem_install_mirrors = filesystem .map(|fs| fs.install_mirrors.clone()) .unwrap_or_default(); let no_description = no_description || (bare && description.is_none()); Self { path, name, package, kind, bare, description, no_description, vcs: vcs.or(bare.then_some(VersionControlSystem::None)), build_backend, no_readme, author_from, pin_python: flag(pin_python, no_pin_python, "pin-python").unwrap_or(!bare), no_workspace, python: python.and_then(Maybe::into_option), install_mirrors: environment .install_mirrors .combine(filesystem_install_mirrors), } } } /// The source of a lock check operation. #[derive(Debug, Clone, Copy)] pub(crate) enum LockCheckSource { /// The user invoked `uv <command> --locked` Locked, /// The user invoked `uv <command> --check` Check, } impl std::fmt::Display for LockCheckSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Locked => write!(f, "--locked"), Self::Check => write!(f, "--check"), } } } // Has lock check been enabled? #[derive(Debug, Clone, Copy)] pub(crate) enum LockCheck { /// Lockfile check is enabled. Enabled(LockCheckSource), /// Lockfile check is disabled. Disabled, } /// The resolved settings to use for a `run` invocation. #[derive(Debug, Clone)] pub(crate) struct RunSettings { pub(crate) lock_check: LockCheck, pub(crate) frozen: bool, pub(crate) extras: ExtrasSpecification, pub(crate) groups: DependencyGroups, pub(crate) editable: Option<EditableMode>, pub(crate) modifications: Modifications, pub(crate) with: Vec<String>, pub(crate) with_editable: Vec<String>, pub(crate) with_requirements: Vec<PathBuf>, pub(crate) isolated: bool, pub(crate) show_resolution: bool, pub(crate) all_packages: bool, pub(crate) package: Option<PackageName>, pub(crate) no_project: bool, pub(crate) active: Option<bool>, pub(crate) no_sync: bool, pub(crate) python: Option<String>, pub(crate) python_platform: Option<TargetTriple>, pub(crate) install_mirrors: PythonInstallMirrors, pub(crate) refresh: Refresh, pub(crate) settings: ResolverInstallerSettings, pub(crate) env_file: EnvFile, pub(crate) max_recursion_depth: u32, } impl RunSettings { // Default value for UV_RUN_MAX_RECURSION_DEPTH if unset. This is large // enough that it's unlikely a user actually needs this recursion depth, // but short enough that we detect recursion quickly enough to avoid OOMing // or hanging for a long time. const DEFAULT_MAX_RECURSION_DEPTH: u32 = 100; /// Resolve the [`RunSettings`] from the CLI and filesystem configuration. #[allow(clippy::needless_pass_by_value)] pub(crate) fn resolve( args: RunArgs, filesystem: Option<FilesystemOptions>, environment: EnvironmentOptions, ) -> Self { let RunArgs { extra, all_extras, no_extra, no_all_extras, dev, no_dev, group, no_group, no_default_groups, only_group, all_groups, module: _, only_dev, editable, no_editable, inexact, exact, script: _, gui_script: _, command: _, with, with_editable, with_requirements, isolated, active, no_active, no_sync, locked, frozen, installer, build, refresh, all_packages, package, no_project, python, python_platform, show_resolution, env_file, no_env_file, max_recursion_depth, } = args; let filesystem_install_mirrors = filesystem .clone() .map(|fs| fs.install_mirrors.clone()) .unwrap_or_default(); Self { lock_check: if locked { LockCheck::Enabled(LockCheckSource::Locked) } else { LockCheck::Disabled }, frozen, extras: ExtrasSpecification::from_args( extra.unwrap_or_default(), no_extra, // TODO(blueraft): support no_default_extras false, // TODO(blueraft): support only_extra vec![], flag(all_extras, no_all_extras, "all-extras").unwrap_or_default(), ), groups: DependencyGroups::from_args( dev, no_dev, only_dev, group, no_group, no_default_groups, only_group, all_groups, ), editable: flag(editable, no_editable, "editable").map(EditableMode::from), modifications: if flag(exact, inexact, "inexact").unwrap_or(false) { Modifications::Exact } else { Modifications::Sufficient }, with: with .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_editable: with_editable .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_requirements: with_requirements .into_iter() .filter_map(Maybe::into_option) .collect(), isolated, show_resolution, all_packages, package, no_project, no_sync, active: flag(active, no_active, "active"), python: python.and_then(Maybe::into_option), python_platform, refresh: Refresh::from(refresh), settings: ResolverInstallerSettings::combine( resolver_installer_options(installer, build), filesystem, ), env_file: EnvFile::from_args(env_file, no_env_file), install_mirrors: environment .install_mirrors .combine(filesystem_install_mirrors), max_recursion_depth: max_recursion_depth.unwrap_or(Self::DEFAULT_MAX_RECURSION_DEPTH), } } } /// The resolved settings to use for a `tool run` invocation. #[derive(Debug, Clone)] pub(crate) struct ToolRunSettings { pub(crate) command: Option<ExternalCommand>, pub(crate) from: Option<String>, pub(crate) with: Vec<String>, pub(crate) with_requirements: Vec<PathBuf>, pub(crate) with_editable: Vec<String>, pub(crate) constraints: Vec<PathBuf>, pub(crate) overrides: Vec<PathBuf>, pub(crate) build_constraints: Vec<PathBuf>, pub(crate) isolated: bool, pub(crate) show_resolution: bool, pub(crate) lfs: GitLfsSetting, pub(crate) python: Option<String>, pub(crate) python_platform: Option<TargetTriple>, pub(crate) install_mirrors: PythonInstallMirrors, pub(crate) refresh: Refresh, pub(crate) options: ResolverInstallerOptions, pub(crate) settings: ResolverInstallerSettings, pub(crate) env_file: Vec<PathBuf>, pub(crate) no_env_file: bool, } impl ToolRunSettings { /// Resolve the [`ToolRunSettings`] from the CLI and filesystem configuration. #[allow(clippy::needless_pass_by_value)] pub(crate) fn resolve( args: ToolRunArgs, filesystem: Option<FilesystemOptions>, invocation_source: ToolRunCommand, environment: EnvironmentOptions, ) -> Self { let ToolRunArgs { command, from, with, with_editable, with_requirements, constraints, overrides, build_constraints, isolated, env_file, no_env_file, show_resolution, installer, build, refresh, lfs, python, python_platform, torch_backend, generate_shell_completion: _, } = args; // If `--upgrade` was passed explicitly, warn. if installer.upgrade || !installer.upgrade_package.is_empty() { if with.is_empty() && with_requirements.is_empty() { warn_user_once!( "Tools cannot be upgraded via `{invocation_source}`; use `uv tool upgrade --all` to upgrade all installed tools, or `{invocation_source} package@latest` to run the latest version of a tool." ); } else { warn_user_once!( "Tools cannot be upgraded via `{invocation_source}`; use `uv tool upgrade --all` to upgrade all installed tools, `{invocation_source} package@latest` to run the latest version of a tool, or `{invocation_source} --refresh package` to upgrade any `--with` dependencies." ); } } // If `--reinstall` was passed explicitly, warn. if installer.reinstall || !installer.reinstall_package.is_empty() { if with.is_empty() && with_requirements.is_empty() { warn_user_once!( "Tools cannot be reinstalled via `{invocation_source}`; use `uv tool upgrade --all --reinstall` to reinstall all installed tools, `{invocation_source} package@latest` to run the latest version of a tool, or `uv cache prune` to clear any cached tool environments." ); } else { warn_user_once!( "Tools cannot be reinstalled via `{invocation_source}`; use `uv tool upgrade --all --reinstall` to reinstall all installed tools, `{invocation_source} package@latest` to run the latest version of a tool, `{invocation_source} --refresh package` to reinstall any `--with` dependencies, or `uv cache prune` to clear any cached tool environments." ); } } let filesystem_options = filesystem.map(FilesystemOptions::into_options); let options = resolver_installer_options(installer, build).combine(ResolverInstallerOptions::from( filesystem_options .as_ref() .map(|options| options.top_level.clone()) .unwrap_or_default(), )); let filesystem_install_mirrors = filesystem_options .map(|options| options.install_mirrors.clone()) .unwrap_or_default(); let mut settings = ResolverInstallerSettings::from(options.clone()); if torch_backend.is_some() { settings.resolver.torch_backend = torch_backend; } let lfs = GitLfsSetting::new(lfs.then_some(true), environment.lfs); Self { command, from, with: with .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_editable: with_editable .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_requirements: with_requirements .into_iter() .filter_map(Maybe::into_option) .collect(), constraints: constraints .into_iter() .filter_map(Maybe::into_option) .collect(), overrides: overrides .into_iter() .filter_map(Maybe::into_option) .collect(), build_constraints: build_constraints .into_iter() .filter_map(Maybe::into_option) .collect(), isolated, show_resolution, lfs, python: python.and_then(Maybe::into_option), python_platform, refresh: Refresh::from(refresh), settings, options, install_mirrors: environment .install_mirrors .combine(filesystem_install_mirrors), env_file, no_env_file, } } } /// The resolved settings to use for a `tool install` invocation. #[derive(Debug, Clone)] pub(crate) struct ToolInstallSettings { pub(crate) package: String, pub(crate) from: Option<String>, pub(crate) with: Vec<String>, pub(crate) with_requirements: Vec<PathBuf>, pub(crate) with_executables_from: Vec<String>, pub(crate) with_editable: Vec<String>, pub(crate) constraints: Vec<PathBuf>, pub(crate) overrides: Vec<PathBuf>, pub(crate) excludes: Vec<PathBuf>, pub(crate) build_constraints: Vec<PathBuf>, pub(crate) lfs: GitLfsSetting, pub(crate) python: Option<String>, pub(crate) python_platform: Option<TargetTriple>, pub(crate) refresh: Refresh, pub(crate) options: ResolverInstallerOptions, pub(crate) settings: ResolverInstallerSettings, pub(crate) force: bool, pub(crate) editable: bool, pub(crate) install_mirrors: PythonInstallMirrors, } impl ToolInstallSettings { /// Resolve the [`ToolInstallSettings`] from the CLI and filesystem configuration. #[allow(clippy::needless_pass_by_value)] pub(crate) fn resolve( args: ToolInstallArgs, filesystem: Option<FilesystemOptions>, environment: EnvironmentOptions, ) -> Self { let ToolInstallArgs { package, editable, from, with, with_editable, with_requirements, with_executables_from, constraints, overrides, excludes, build_constraints, lfs, installer, force, build, refresh, python, python_platform, torch_backend, } = args; let filesystem_options = filesystem.map(FilesystemOptions::into_options); let options = resolver_installer_options(installer, build).combine(ResolverInstallerOptions::from( filesystem_options .as_ref() .map(|options| options.top_level.clone()) .unwrap_or_default(), )); let filesystem_install_mirrors = filesystem_options .map(|options| options.install_mirrors.clone()) .unwrap_or_default(); let mut settings = ResolverInstallerSettings::from(options.clone()); if torch_backend.is_some() { settings.resolver.torch_backend = torch_backend; } let lfs = GitLfsSetting::new(lfs.then_some(true), environment.lfs); Self { package, from, with: with .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_editable: with_editable .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), with_requirements: with_requirements .into_iter() .filter_map(Maybe::into_option) .collect(), with_executables_from: with_executables_from .into_iter() .flat_map(CommaSeparatedRequirements::into_iter) .collect(), constraints: constraints .into_iter() .filter_map(Maybe::into_option) .collect(), overrides: overrides .into_iter() .filter_map(Maybe::into_option) .collect(), excludes: excludes .into_iter() .filter_map(Maybe::into_option) .collect(), build_constraints: build_constraints .into_iter() .filter_map(Maybe::into_option) .collect(), lfs, python: python.and_then(Maybe::into_option), python_platform, force, editable, refresh: Refresh::from(refresh), options, settings, install_mirrors: environment .install_mirrors .combine(filesystem_install_mirrors), } } } /// The resolved settings to use for a `tool upgrade` invocation. #[derive(Debug, Clone)] pub(crate) struct ToolUpgradeSettings { pub(crate) names: Vec<String>, pub(crate) python: Option<String>, pub(crate) python_platform: Option<TargetTriple>, pub(crate) install_mirrors: PythonInstallMirrors, pub(crate) args: ResolverInstallerOptions, pub(crate) filesystem: ResolverInstallerOptions, } impl ToolUpgradeSettings { /// Resolve the [`ToolUpgradeSettings`] from the CLI and filesystem configuration. #[allow(clippy::needless_pass_by_value)] pub(crate) fn resolve( args: ToolUpgradeArgs, filesystem: Option<FilesystemOptions>, environment: &EnvironmentOptions, ) -> Self { let ToolUpgradeArgs { name, python, python_platform, upgrade, upgrade_package, index_args, all, reinstall, no_reinstall, reinstall_package, index_strategy, keyring_provider, resolution, prerelease, pre, fork_strategy, config_setting, config_setting_package: config_settings_package, no_build_isolation, no_build_isolation_package, build_isolation, exclude_newer, link_mode, compile_bytecode, no_compile_bytecode, no_sources, exclude_newer_package, build, } = args; if upgrade { warn_user_once!("`--upgrade` is enabled by default on `uv tool upgrade`"); } if !upgrade_package.is_empty() { warn_user_once!("`--upgrade-package` is enabled by default on `uv tool upgrade`"); } // Enable `--upgrade` by default. let installer = ResolverInstallerArgs { index_args, upgrade: upgrade_package.is_empty(), no_upgrade: false, upgrade_package, reinstall, no_reinstall, reinstall_package, index_strategy, keyring_provider, resolution, prerelease, pre, fork_strategy, config_setting, config_settings_package, no_build_isolation, no_build_isolation_package, build_isolation, exclude_newer, exclude_newer_package, link_mode, compile_bytecode, no_compile_bytecode, no_sources, }; let args = resolver_installer_options(installer, build); let filesystem = filesystem.map(FilesystemOptions::into_options); let filesystem_install_mirrors = filesystem .clone() .map(|options| options.install_mirrors) .unwrap_or_default(); let top_level = ResolverInstallerOptions::from( filesystem .map(|options| options.top_level) .unwrap_or_default(), ); Self { names: if all { vec![] } else { name }, python: python.and_then(Maybe::into_option), python_platform, args, filesystem: top_level, install_mirrors: environment .install_mirrors .clone() .combine(filesystem_install_mirrors), } } } /// The resolved settings to use for a `tool list` invocation. #[derive(Debug, Clone)] pub(crate) struct ToolListSettings { pub(crate) show_paths: bool,
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/src/lib.rs
crates/uv/src/lib.rs
#![deny(clippy::print_stdout, clippy::print_stderr)] use std::borrow::Cow; use std::ffi::OsString; use std::fmt::Write; use std::io::stdout; #[cfg(feature = "self-update")] use std::ops::Bound; use std::path::Path; use std::process::ExitCode; use std::str::FromStr; use std::sync::atomic::Ordering; use anstream::eprintln; use anyhow::{Result, anyhow, bail}; use clap::error::{ContextKind, ContextValue}; use clap::{CommandFactory, Parser}; use futures::FutureExt; use owo_colors::OwoColorize; use settings::PipTreeSettings; use tokio::task::spawn_blocking; use tracing::{debug, instrument, trace}; #[cfg(not(feature = "self-update"))] use crate::install_source::InstallSource; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; #[cfg(feature = "self-update")] use uv_cli::SelfUpdateArgs; use uv_cli::{ AuthCommand, AuthHelperCommand, AuthNamespace, BuildBackendCommand, CacheCommand, CacheNamespace, Cli, Commands, PipCommand, PipNamespace, ProjectCommand, PythonCommand, PythonNamespace, SelfCommand, SelfNamespace, ToolCommand, ToolNamespace, TopLevelArgs, WorkspaceCommand, WorkspaceNamespace, compat::CompatArgs, }; use uv_client::BaseClientBuilder; use uv_configuration::min_stack_size; use uv_flags::EnvironmentFlags; use uv_fs::{CWD, Simplified}; #[cfg(feature = "self-update")] use uv_pep440::release_specifiers_to_ranges; use uv_pep508::VersionOrUrl; use uv_preview::PreviewFeatures; use uv_pypi_types::{ParsedDirectoryUrl, ParsedUrl}; use uv_python::PythonRequest; use uv_requirements::{GroupsSpecification, RequirementsSource}; use uv_requirements_txt::RequirementsTxtRequirement; use uv_scripts::{Pep723Error, Pep723Item, Pep723Metadata, Pep723Script}; use uv_settings::{Combine, EnvironmentOptions, FilesystemOptions, Options}; use uv_static::EnvVars; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache}; use crate::commands::{ExitStatus, RunCommand, ScriptPath, ToolRunCommand}; use crate::printer::Printer; use crate::settings::{ CacheSettings, GlobalSettings, PipCheckSettings, PipCompileSettings, PipFreezeSettings, PipInstallSettings, PipListSettings, PipShowSettings, PipSyncSettings, PipUninstallSettings, PublishSettings, }; pub(crate) mod child; pub(crate) mod commands; #[cfg(not(feature = "self-update"))] mod install_source; pub(crate) mod logging; pub(crate) mod printer; pub(crate) mod settings; #[cfg(windows)] mod windows_exception; #[instrument(skip_all)] async fn run(mut cli: Cli) -> Result<ExitStatus> { // Enable flag to pick up warnings generated by workspace loading. if cli.top_level.global_args.quiet == 0 { uv_warnings::enable(); } // Respect `UV_WORKING_DIRECTORY` for backwards compatibility. let directory = cli.top_level.global_args.directory.clone().or_else(|| { std::env::var_os(EnvVars::UV_WORKING_DIRECTORY).map(std::path::PathBuf::from) }); // Switch directories as early as possible. if let Some(directory) = directory.as_ref() { std::env::set_current_dir(directory)?; } // Determine the project directory. let project_dir = cli .top_level .global_args .project .as_deref() .map(std::path::absolute) .transpose()? .map(uv_fs::normalize_path_buf) .map(Cow::Owned) .unwrap_or_else(|| Cow::Borrowed(&*CWD)); // Load environment variables not handled by Clap let environment = EnvironmentOptions::new()?; // The `--isolated` argument is deprecated on preview APIs, and warns on non-preview APIs. let deprecated_isolated = if cli.top_level.global_args.isolated { match &*cli.command { // Supports `--isolated` as its own argument, so we can't warn either way. Commands::Tool(ToolNamespace { command: ToolCommand::Uvx(_) | ToolCommand::Run(_), }) => false, // Supports `--isolated` as its own argument, so we can't warn either way. Commands::Project(command) if matches!(**command, ProjectCommand::Run(_)) => false, // `--isolated` moved to `--no-workspace`. Commands::Project(command) if matches!(**command, ProjectCommand::Init(_)) => { warn_user!( "The `--isolated` flag is deprecated and has no effect. Instead, use `--no-config` to prevent uv from discovering configuration files or `--no-workspace` to prevent uv from adding the initialized project to the containing workspace." ); false } // Preview APIs. Ignore `--isolated` and warn. Commands::Project(_) | Commands::Tool(_) | Commands::Python(_) => { warn_user!( "The `--isolated` flag is deprecated and has no effect. Instead, use `--no-config` to prevent uv from discovering configuration files." ); false } // Non-preview APIs. Continue to support `--isolated`, but warn. _ => { warn_user!( "The `--isolated` flag is deprecated. Instead, use `--no-config` to prevent uv from discovering configuration files." ); true } } } else { false }; // Load configuration from the filesystem, prioritizing (in order): // 1. The configuration file specified on the command-line. // 2. The nearest configuration file (`uv.toml` or `pyproject.toml`) above the workspace root. // If found, this file is combined with the user configuration file. // 3. The nearest configuration file (`uv.toml` or `pyproject.toml`) in the directory tree, // starting from the current directory. let workspace_cache = WorkspaceCache::default(); let filesystem = if let Some(config_file) = cli.top_level.config_file.as_ref() { if config_file .file_name() .is_some_and(|file_name| file_name == "pyproject.toml") { warn_user!( "The `--config-file` argument expects to receive a `uv.toml` file, not a `pyproject.toml`. If you're trying to run a command from another project, use the `--project` argument instead." ); } Some(FilesystemOptions::from_file(config_file)?) } else if deprecated_isolated || cli.top_level.no_config { None } else if matches!(&*cli.command, Commands::Tool(_) | Commands::Self_(_)) { // For commands that operate at the user-level, ignore local configuration. FilesystemOptions::user()?.combine(FilesystemOptions::system()?) } else if let Ok(workspace) = Workspace::discover(&project_dir, &DiscoveryOptions::default(), &workspace_cache).await { let project = FilesystemOptions::find(workspace.install_path())?; let system = FilesystemOptions::system()?; let user = FilesystemOptions::user()?; project.combine(user).combine(system) } else { let project = FilesystemOptions::find(&project_dir)?; let system = FilesystemOptions::system()?; let user = FilesystemOptions::user()?; project.combine(user).combine(system) }; // Parse the external command, if necessary. let run_command = if let Commands::Project(command) = &mut *cli.command { if let ProjectCommand::Run(uv_cli::RunArgs { command: Some(command), module, script, gui_script, .. }) = &mut **command { let settings = GlobalSettings::resolve( &cli.top_level.global_args, filesystem.as_ref(), &environment, ); let client_builder = BaseClientBuilder::new( settings.network_settings.connectivity, settings.network_settings.native_tls, settings.network_settings.allow_insecure_host, settings.preview, settings.network_settings.timeout, settings.network_settings.retries, ); Some( RunCommand::from_args(command, client_builder, *module, *script, *gui_script) .await?, ) } else { None } } else { None }; // If the target is a PEP 723 script, parse it. let script = if let Commands::Project(command) = &*cli.command { match &**command { ProjectCommand::Run(uv_cli::RunArgs { .. }) => match run_command.as_ref() { Some( RunCommand::PythonScript(script, _) | RunCommand::PythonGuiScript(script, _), ) => match Pep723Script::read(&script).await { Ok(Some(script)) => Some(Pep723Item::Script(script)), Ok(None) => None, Err(Pep723Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => None, Err(err) => return Err(err.into()), }, Some(RunCommand::PythonRemote(url, script, _)) => { match Pep723Metadata::read(&script).await { Ok(Some(metadata)) => Some(Pep723Item::Remote(metadata, url.clone())), Ok(None) => None, Err(Pep723Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { None } Err(err) => return Err(err.into()), } } Some( RunCommand::PythonStdin(contents, _) | RunCommand::PythonGuiStdin(contents, _), ) => Pep723Metadata::parse(contents)?.map(Pep723Item::Stdin), _ => None, }, // For `uv add --script` and `uv lock --script`, we'll create a PEP 723 tag if it // doesn't already exist. ProjectCommand::Add(uv_cli::AddArgs { script: Some(script), .. }) | ProjectCommand::Lock(uv_cli::LockArgs { script: Some(script), .. }) => match Pep723Script::read(&script).await { Ok(Some(script)) => Some(Pep723Item::Script(script)), Ok(None) => None, Err(err) => return Err(err.into()), }, // For the remaining commands, the PEP 723 tag must exist already. ProjectCommand::Remove(uv_cli::RemoveArgs { script: Some(script), .. }) | ProjectCommand::Sync(uv_cli::SyncArgs { script: Some(script), .. }) | ProjectCommand::Tree(uv_cli::TreeArgs { script: Some(script), .. }) | ProjectCommand::Export(uv_cli::ExportArgs { script: Some(script), .. }) => match Pep723Script::read(&script).await { Ok(Some(script)) => Some(Pep723Item::Script(script)), Ok(None) => { bail!( "`{}` does not contain a PEP 723 metadata tag; run `{}` to initialize the script", script.user_display().cyan(), format!("uv init --script {}", script.user_display()).green() ) } Err(Pep723Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { bail!( "Failed to read `{}` (not found); run `{}` to create a PEP 723 script", script.user_display().cyan(), format!("uv init --script {}", script.user_display()).green() ) } Err(err) => return Err(err.into()), }, _ => None, } } else if let Commands::Python(uv_cli::PythonNamespace { command: PythonCommand::Find(uv_cli::PythonFindArgs { script: Some(script), .. }), }) = &*cli.command { match Pep723Script::read(&script).await { Ok(Some(script)) => Some(Pep723Item::Script(script)), Ok(None) => { bail!( "`{}` does not contain a PEP 723 metadata tag; run `{}` to initialize the script", script.user_display().cyan(), format!("uv init --script {}", script.user_display()).green() ) } Err(Pep723Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { bail!( "Failed to read `{}` (not found); run `{}` to create a PEP 723 script", script.user_display().cyan(), format!("uv init --script {}", script.user_display()).green() ) } Err(err) => return Err(err.into()), } } else { None }; // If the target is a PEP 723 script, merge the metadata into the filesystem metadata. let filesystem = script .as_ref() .map(Pep723Item::metadata) .and_then(|metadata| metadata.tool.as_ref()) .and_then(|tool| tool.uv.as_ref()) .map(|uv| Options::simple(uv.globals.clone(), uv.top_level.clone())) .map(FilesystemOptions::from) .combine(filesystem); // Resolve the global settings. let globals = GlobalSettings::resolve( &cli.top_level.global_args, filesystem.as_ref(), &environment, ); // Resolve the cache settings. let cache_settings = CacheSettings::resolve(*cli.top_level.cache_args, filesystem.as_ref()); // Set the global flags. uv_flags::init(EnvironmentFlags::from(&environment)) .map_err(|()| anyhow::anyhow!("Flags are already initialized"))?; // Enforce the required version. if let Some(required_version) = globals.required_version.as_ref() { let package_version = uv_pep440::Version::from_str(uv_version::version())?; if !required_version.contains(&package_version) { #[cfg(feature = "self-update")] let hint = { // If the required version range includes a lower bound that's higher than // the current version, suggest `uv self update`. let ranges = release_specifiers_to_ranges(required_version.specifiers().clone()); if let Some(singleton) = ranges.as_singleton() { // E.g., `==1.0.0` format!( ". Update `uv` by running `{}`.", format!("uv self update {singleton}").green() ) } else if ranges .bounding_range() .iter() .any(|(lowest, _highest)| match lowest { Bound::Included(version) => **version > package_version, Bound::Excluded(version) => **version > package_version, Bound::Unbounded => false, }) { // E.g., `>=1.0.0` format!(". Update `uv` by running `{}`.", "uv self update".cyan()) } else { String::new() } }; #[cfg(not(feature = "self-update"))] let hint = ""; return Err(anyhow::anyhow!( "Required uv version `{required_version}` does not match the running version `{package_version}`{hint}", )); } } // Configure the `tracing` crate, which controls internal logging. #[cfg(feature = "tracing-durations-export")] let (durations_layer, _duration_guard) = logging::setup_durations(environment.tracing_durations_file.as_ref())?; #[cfg(not(feature = "tracing-durations-export"))] let durations_layer = None::<tracing_subscriber::layer::Identity>; logging::setup_logging( match globals.verbose { 0 => logging::Level::Off, 1 => logging::Level::DebugUv, 2 => logging::Level::TraceUv, 3.. => logging::Level::TraceAll, }, durations_layer, globals.color, environment.log_context.unwrap_or_default(), )?; // Configure the `Printer`, which controls user-facing output in the CLI. let printer = if globals.quiet == 1 { Printer::Quiet } else if globals.quiet > 1 { Printer::Silent } else if globals.verbose > 0 { Printer::Verbose } else if globals.no_progress { Printer::NoProgress } else { Printer::Default }; // Configure the `warn!` macros, which control user-facing warnings in the CLI. if globals.quiet > 0 { uv_warnings::disable(); } else { uv_warnings::enable(); } anstream::ColorChoice::write_global(globals.color.into()); miette::set_hook(Box::new(|_| { Box::new( miette::MietteHandlerOpts::new() .break_words(false) .word_separator(textwrap::WordSeparator::AsciiSpace) .word_splitter(textwrap::WordSplitter::NoHyphenation) .wrap_lines( std::env::var(EnvVars::UV_NO_WRAP) .map(|_| false) .unwrap_or(true), ) .build(), ) }))?; // Don't initialize the rayon threadpool yet, this is too costly when we're doing a noop sync. uv_configuration::RAYON_PARALLELISM.store(globals.concurrency.installs, Ordering::Relaxed); debug!("uv {}", uv_cli::version::uv_self_version()); // Write out any resolved settings. macro_rules! show_settings { ($arg:expr) => { if globals.show_settings { writeln!(printer.stdout(), "{:#?}", $arg)?; return Ok(ExitStatus::Success); } }; ($arg:expr, false) => { if globals.show_settings { writeln!(printer.stdout(), "{:#?}", $arg)?; } }; } show_settings!(globals, false); show_settings!(cache_settings, false); // Configure the cache. if cache_settings.no_cache { debug!("Disabling the uv cache due to `--no-cache`"); } let cache = Cache::from_settings(cache_settings.no_cache, cache_settings.cache_dir)?; // Configure the global network settings. let client_builder = BaseClientBuilder::new( globals.network_settings.connectivity, globals.network_settings.native_tls, globals.network_settings.allow_insecure_host.clone(), globals.preview, globals.network_settings.timeout, globals.network_settings.retries, ); match *cli.command { Commands::Auth(AuthNamespace { command: AuthCommand::Login(args), }) => { // Resolve the settings from the command-line arguments and workspace configuration. let args = settings::AuthLoginSettings::resolve(args); show_settings!(args); commands::auth_login( args.service, args.username, args.password, args.token, client_builder, printer, globals.preview, ) .await } Commands::Auth(AuthNamespace { command: AuthCommand::Logout(args), }) => { // Resolve the settings from the command-line arguments and workspace configuration. let args = settings::AuthLogoutSettings::resolve(args); show_settings!(args); commands::auth_logout( args.service, args.username, client_builder, printer, globals.preview, ) .await } Commands::Auth(AuthNamespace { command: AuthCommand::Token(args), }) => { // Resolve the settings from the command-line arguments and workspace configuration. let args = settings::AuthTokenSettings::resolve(args); show_settings!(args); commands::auth_token( args.service, args.username, client_builder, printer, globals.preview, ) .await } Commands::Auth(AuthNamespace { command: AuthCommand::Dir(args), }) => { commands::auth_dir(args.service.as_ref(), printer)?; Ok(ExitStatus::Success) } Commands::Auth(AuthNamespace { command: AuthCommand::Helper(args), }) => { use uv_cli::AuthHelperProtocol; // Validate protocol (currently only Bazel is supported) match args.protocol { AuthHelperProtocol::Bazel => {} } match args.command { AuthHelperCommand::Get => { commands::auth_helper(client_builder, globals.preview, printer).await } } } Commands::Help(args) => commands::help( args.command.unwrap_or_default().as_slice(), printer, args.no_pager, ), Commands::Pip(PipNamespace { command: PipCommand::Compile(args), }) => { args.compat_args.validate()?; // Resolve the settings from the command-line arguments and workspace configuration. let args = PipCompileSettings::resolve(args, filesystem, environment); show_settings!(args); // Initialize the cache. let cache = cache.init().await?.with_refresh( args.refresh .combine(Refresh::from(args.settings.reinstall.clone())) .combine(Refresh::from(args.settings.upgrade.clone())), ); let requirements = args .src_file .into_iter() .map(RequirementsSource::from_requirements_file) .collect::<Result<Vec<_>, _>>()?; let constraints = args .constraints .into_iter() .map(RequirementsSource::from_constraints_txt) .collect::<Result<Vec<_>, _>>()?; let overrides = args .overrides .into_iter() .map(RequirementsSource::from_overrides_txt) .collect::<Result<Vec<_>, _>>()?; let excludes = args .excludes .into_iter() .map(RequirementsSource::from_requirements_txt) .collect::<Result<Vec<_>, _>>()?; let build_constraints = args .build_constraints .into_iter() .map(RequirementsSource::from_constraints_txt) .collect::<Result<Vec<_>, _>>()?; let groups = GroupsSpecification { root: project_dir.to_path_buf(), groups: args.settings.groups, }; commands::pip_compile( &requirements, &constraints, &overrides, &excludes, &build_constraints, args.constraints_from_workspace, args.overrides_from_workspace, args.excludes_from_workspace, args.build_constraints_from_workspace, args.environments, args.settings.extras, groups, args.settings.output_file.as_deref(), args.format, args.settings.resolution, args.settings.prerelease, args.settings.fork_strategy, args.settings.dependency_mode, args.settings.upgrade, args.settings.generate_hashes, args.settings.no_emit_package, args.settings.no_strip_extras, args.settings.no_strip_markers, !args.settings.no_annotate, !args.settings.no_header, args.settings.custom_compile_command, args.settings.emit_index_url, args.settings.emit_find_links, args.settings.emit_build_options, args.settings.emit_marker_expression, args.settings.emit_index_annotation, args.settings.index_locations, args.settings.index_strategy, args.settings.torch_backend, args.settings.dependency_metadata, args.settings.keyring_provider, &client_builder.subcommand(vec!["pip".to_owned(), "compile".to_owned()]), args.settings.config_setting, args.settings.config_settings_package, args.settings.build_isolation.clone(), &args.settings.extra_build_dependencies, &args.settings.extra_build_variables, args.settings.build_options, args.settings.install_mirrors, args.settings.python_version, args.settings.python_platform, globals.python_downloads, args.settings.universal, args.settings.exclude_newer, args.settings.sources, args.settings.annotation_style, args.settings.link_mode, args.settings.python, args.settings.system, globals.python_preference, globals.concurrency, globals.quiet > 0, cache, printer, globals.preview, ) .await } Commands::Pip(PipNamespace { command: PipCommand::Sync(args), }) => { args.compat_args.validate()?; // Resolve the settings from the command-line arguments and workspace configuration. let args = PipSyncSettings::resolve(args, filesystem, environment); show_settings!(args); // Initialize the cache. let cache = cache.init().await?.with_refresh( args.refresh .combine(Refresh::from(args.settings.reinstall.clone())) .combine(Refresh::from(args.settings.upgrade.clone())), ); let requirements = args .src_file .into_iter() .map(RequirementsSource::from_requirements_file) .collect::<Result<Vec<_>, _>>()?; let constraints = args .constraints .into_iter() .map(RequirementsSource::from_constraints_txt) .collect::<Result<Vec<_>, _>>()?; let build_constraints = args .build_constraints .into_iter() .map(RequirementsSource::from_constraints_txt) .collect::<Result<Vec<_>, _>>()?; let groups = GroupsSpecification { root: project_dir.to_path_buf(), groups: args.settings.groups, }; commands::pip_sync( &requirements, &constraints, &build_constraints, &args.settings.extras, &groups, args.settings.reinstall, args.settings.link_mode, args.settings.compile_bytecode, args.settings.hash_checking, args.settings.index_locations, args.settings.index_strategy, args.settings.torch_backend, args.settings.dependency_metadata, args.settings.keyring_provider, &client_builder.subcommand(vec!["pip".to_owned(), "sync".to_owned()]), args.settings.allow_empty_requirements, globals.installer_metadata, &args.settings.config_setting, &args.settings.config_settings_package, args.settings.build_isolation.clone(), &args.settings.extra_build_dependencies, &args.settings.extra_build_variables, args.settings.build_options, args.settings.python_version, args.settings.python_platform, globals.python_downloads, args.settings.install_mirrors, args.settings.strict, args.settings.exclude_newer, args.settings.python, args.settings.system, args.settings.break_system_packages, args.settings.target, args.settings.prefix, args.settings.sources, globals.python_preference, globals.concurrency, cache, args.dry_run, printer, globals.preview, ) .await } Commands::Pip(PipNamespace { command: PipCommand::Install(args), }) => { args.compat_args.validate()?; // Resolve the settings from the command-line arguments and workspace configuration. let mut args = PipInstallSettings::resolve(args, filesystem, environment); show_settings!(args); let mut requirements = Vec::with_capacity( args.package.len() + args.editables.len() + args.requirements.len(), ); for package in args.package { requirements.push(RequirementsSource::from_package_argument(&package)?); } for package in args.editables { requirements.push(RequirementsSource::from_editable(&package)?); } requirements.extend( args.requirements .into_iter() .map(RequirementsSource::from_requirements_file) .collect::<Result<Vec<_>, _>>()?, ); let constraints = args .constraints .into_iter() .map(RequirementsSource::from_constraints_txt) .collect::<Result<Vec<_>, _>>()?; let overrides = args .overrides .into_iter() .map(RequirementsSource::from_overrides_txt) .collect::<Result<Vec<_>, _>>()?; let excludes = args .excludes .into_iter() .map(RequirementsSource::from_requirements_txt) .collect::<Result<Vec<_>, _>>()?; let build_constraints = args .build_constraints .into_iter() .map(RequirementsSource::from_overrides_txt) .collect::<Result<Vec<_>, _>>()?; let groups = GroupsSpecification { root: project_dir.to_path_buf(), groups: args.settings.groups, }; // Special-case: any source trees specified on the command-line are automatically // reinstalled. This matches user expectations: `uv pip install .` should always // re-build and re-install the package in the current working directory. for requirement in &requirements { let requirement = match requirement { RequirementsSource::Package(requirement) => requirement, RequirementsSource::Editable(requirement) => requirement, _ => continue, }; match requirement { RequirementsTxtRequirement::Named(requirement) => { if let Some(VersionOrUrl::Url(url)) = requirement.version_or_url.as_ref() { if let ParsedUrl::Directory(ParsedDirectoryUrl { install_path, .. }) = &url.parsed_url { debug!( "Marking explicit source tree for reinstall: `{}`", install_path.display() ); args.settings.reinstall = args .settings
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/src/printer.rs
crates/uv/src/printer.rs
use anstream::{eprint, print}; use indicatif::ProgressDrawTarget; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Printer { /// A printer that suppresses all output. Silent, /// A printer that suppresses most output, but preserves "important" stdout. Quiet, /// A printer that prints to standard streams (e.g., stdout). Default, /// A printer that prints all output, including debug messages. Verbose, /// A printer that prints to standard streams, excluding all progress outputs NoProgress, } impl Printer { /// Return the [`ProgressDrawTarget`] for this printer. pub(crate) fn target(self) -> ProgressDrawTarget { match self { Self::Silent => ProgressDrawTarget::hidden(), Self::Quiet => ProgressDrawTarget::hidden(), Self::Default => ProgressDrawTarget::stderr(), // Confusingly, hide the progress bar when in verbose mode. // Otherwise, it gets interleaved with debug messages. Self::Verbose => ProgressDrawTarget::hidden(), Self::NoProgress => ProgressDrawTarget::hidden(), } } /// Return the [`Stdout`] for this printer. #[allow(dead_code, reason = "to be adopted incrementally")] pub(crate) fn stdout_important(self) -> Stdout { match self { Self::Silent => Stdout::Disabled, Self::Quiet => Stdout::Enabled, Self::Default => Stdout::Enabled, Self::Verbose => Stdout::Enabled, Self::NoProgress => Stdout::Enabled, } } /// Return the [`Stdout`] for this printer. pub(crate) fn stdout(self) -> Stdout { match self { Self::Silent => Stdout::Disabled, Self::Quiet => Stdout::Disabled, Self::Default => Stdout::Enabled, Self::Verbose => Stdout::Enabled, Self::NoProgress => Stdout::Enabled, } } /// Return the [`Stderr`] for this printer. pub(crate) fn stderr(self) -> Stderr { match self { Self::Silent => Stderr::Disabled, Self::Quiet => Stderr::Disabled, Self::Default => Stderr::Enabled, Self::Verbose => Stderr::Enabled, Self::NoProgress => Stderr::Enabled, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Stdout { Enabled, Disabled, } impl std::fmt::Write for Stdout { fn write_str(&mut self, s: &str) -> std::fmt::Result { match self { Self::Enabled => { #[allow(clippy::print_stdout, clippy::ignored_unit_patterns)] { print!("{s}"); } } Self::Disabled => {} } Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Stderr { Enabled, Disabled, } impl std::fmt::Write for Stderr { fn write_str(&mut self, s: &str) -> std::fmt::Result { match self { Self::Enabled => { #[allow(clippy::print_stderr, clippy::ignored_unit_patterns)] { eprint!("{s}"); } } Self::Disabled => {} } 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/src/child.rs
crates/uv/src/child.rs
use tokio::process::Child; use tracing::debug; use crate::commands::ExitStatus; /// Wait for the child process to complete, handling signals and error codes. /// /// Note that this registers handles to ignore some signals in the parent process. This is safe as /// long as the command is the last thing that runs in this process; otherwise, we'd need to restore /// the default signal handlers after the command completes. pub(crate) async fn run_to_completion(mut handle: Child) -> anyhow::Result<ExitStatus> { // On Unix, the terminal driver will send SIGINT to the active process group when a user presses // `Ctrl-C`. In general, this means that uv should ignore SIGINT, allowing the child process to // cleanly exit instead. If uv forwarded the SIGINT immediately, the child process would receive // _two_ SIGINT signals which has semantic meaning for some programs, i.e., slow exit on the // first signal and fast exit on the second. The exception to this is if a child process changes // its process group, in which case the terminal driver will _not_ send SIGINT to the child // process and uv must take ownership of forwarding the signal. // // Note the above only applies in an interactive terminal. If a signal is sent directly to the // uv parent process (e.g., `kill -2 <pid>`), the process group is not involved and a signal is // not sent to the child by default. In this context, uv must forward the signal to the child. // uv checks if stdin is a TTY as a heuristic to determine if uv is running in an interactive // terminal. When not in an interactive terminal, uv will forward SIGINT to the child. // // Use of SIGTERM is also a bit complicated. If a terminal receives a SIGTERM, it just waits for // its children to exit — multiple SIGTERMs do not have any effect and the signals are not // forwarded to the children. Consequently, the description for SIGINT above does not apply to // SIGTERM in the terminal driver. It is _possible_ to have a parent process that sends a // SIGTERM to the process group; for example, `tini` supports this via a `-g` option. In this // case, it's possible that uv will improperly send a second SIGTERM to the child process. // However, this seems preferable to not forwarding it in the first place. In the Docker case, // if `uv` is invoked directly (instead of via an init system), it's PID 1 which has a // special-cased default signal handler for SIGTERM by default. Generally, if a process receives // a SIGTERM and does not have a SIGTERM handler, it is terminated. However, if PID 1 receives a // SIGTERM, it is not terminated. In this context, it is essential for uv to forward the SIGTERM // to the child process or the process will not be killable. #[cfg(unix)] let status = { use std::io::{IsTerminal, stdin}; use std::ops::Deref; use anyhow::Context; use nix::sys::signal; use nix::unistd::{Pid, getpgid}; use tokio::select; use tokio::signal::unix::{Signal, SignalKind, signal as handle_signal}; /// A wrapper for a signal handler that is not available on all platforms, `recv` never /// returns on unsupported platforms. #[allow(dead_code)] enum PlatformSpecificSignal { Signal(Signal), Dummy, } impl PlatformSpecificSignal { async fn recv(&mut self) -> Option<()> { match self { Self::Signal(signal) => signal.recv().await, Self::Dummy => std::future::pending().await, } } } /// Simple new type for `Pid` allowing construction from [`Child`]. /// /// `None` if the child process has exited or the PID is invalid. struct ChildPid(Option<Pid>); impl Deref for ChildPid { type Target = Option<Pid>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<&Child> for ChildPid { fn from(child: &Child) -> Self { Self( child .id() .and_then(|id| id.try_into().ok()) .map(Pid::from_raw), ) } } // Get the parent PGID let parent_pgid = getpgid(None).context("Failed to get current PID")?; if let Some(child_pid) = *ChildPid::from(&handle) { debug!("Spawned child {child_pid} in process group {parent_pgid}"); } let mut sigterm_handle = handle_signal(SignalKind::terminate())?; let mut sigint_handle = handle_signal(SignalKind::interrupt())?; // The following signals are terminal by default, but can have user defined handlers. // Forward them to the child process for handling. let mut sigusr1_handle = handle_signal(SignalKind::user_defined1())?; let mut sigusr2_handle = handle_signal(SignalKind::user_defined2())?; let mut sighup_handle = handle_signal(SignalKind::hangup())?; let mut sigalrm_handle = handle_signal(SignalKind::alarm())?; let mut sigquit_handle = handle_signal(SignalKind::quit())?; // The following signals are ignored by default, but can be have user defined handlers. // Forward them to the child process for handling. let mut sigwinch_handle = handle_signal(SignalKind::window_change())?; let mut sigpipe_handle = handle_signal(SignalKind::pipe())?; // This signal is only available on some platforms, copied from `tokio::signal::unix` #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "illumos", ))] let mut siginfo_handle = PlatformSpecificSignal::Signal(handle_signal(SignalKind::info())?); #[cfg(not(any( target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "illumos", )))] let mut siginfo_handle = PlatformSpecificSignal::Dummy; // Use TTY detection as a heuristic let is_interactive = stdin().is_terminal(); // Notably, we do not handle `SIGCHLD` (sent when a child process status changes) and // `SIGIO` or `SIGPOLL` (sent when a file descriptor is ready for io) as they don't make // sense for this parent / child relationship. loop { select! { result = handle.wait() => { break result; }, _ = sigint_handle.recv() => { // See above for commentary on handling of SIGINT. // If the child has already exited, we can't send it signals let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGINT, but the child has already exited"); continue; }; // Check if the child pgid has changed let child_pgid = getpgid(Some(child_pid)).context("Failed to get PID of child process")?; // If the pgid _differs_ from the parent, the child will not receive a SIGINT // and we should forward it. If we think we're not in an interactive terminal, // forward the signal unconditionally. if child_pgid == parent_pgid && is_interactive { debug!("Received SIGINT, assuming the child received it from the terminal driver"); continue; } // The terminal may still be forwarding these signals, give the child a moment // to handle that signal before hitting it with another one debug!("Received SIGINT, forwarding to child at {child_pid} in 200ms"); tokio::time::sleep(std::time::Duration::from_millis(200)).await; let _ = signal::kill(child_pid, signal::Signal::SIGINT); }, _ = sigterm_handle.recv() => { // If the child has already exited, we can't send it signals let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGTERM, but the child has already exited"); continue; }; // We unconditionally forward SIGTERM to the child process; unlike SIGINT, this // isn't usually handled by the terminal. debug!("Received SIGTERM, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGTERM); } _ = sigusr1_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGUSR1, but the child has already exited"); continue; }; // We unconditionally forward SIGUSR1 to the child process. debug!("Received SIGUSR1, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGUSR1); } _ = sigusr2_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGUSR2, but the child has already exited"); continue; }; // We unconditionally forward SIGUSR2 to the child process. debug!("Received SIGUSR2, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGUSR2); } _ = sighup_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGHUP, but the child has already exited"); continue; }; // We unconditionally forward SIGHUP to the child process. debug!("Received SIGHUP, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGHUP); } _ = sigalrm_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGALRM, but the child has already exited"); continue; }; // We unconditionally forward SIGALRM to the child process. debug!("Received SIGALRM, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGALRM); } _ = sigquit_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGQUIT, but the child has already exited"); continue; }; // We unconditionally forward SIGQUIT to the child process. debug!("Received SIGQUIT, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGQUIT); } _ = sigwinch_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGWINCH, but the child has already exited"); continue; }; // We unconditionally forward SIGWINCH to the child process. debug!("Received SIGWINCH, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGWINCH); } _ = sigpipe_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGPIPE, but the child has already exited"); continue; }; // We unconditionally forward SIGPIPE to the child process. debug!("Received SIGPIPE, forwarding to child at {child_pid}"); let _ = signal::kill(child_pid, signal::Signal::SIGPIPE); } _ = siginfo_handle.recv() => { let Some(child_pid) = *ChildPid::from(&handle) else { debug!("Received SIGINFO, but the child has already exited"); continue; }; // We unconditionally forward SIGINFO to the child process. debug!("Received SIGINFO, forwarding to child at {child_pid}"); #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "illumos", ))] let _ = signal::kill(child_pid, signal::Signal::SIGINFO); } }; } }?; // On Windows, we just ignore the console CTRL_C_EVENT and assume it will always be sent to the // child by the console. There's not a clear programmatic way to forward the signal anyway. #[cfg(not(unix))] let status = { let _ctrl_c_handler = tokio::spawn(async { while tokio::signal::ctrl_c().await.is_ok() {} }); handle.wait().await? }; // Exit based on the result of the command. if let Some(code) = status.code() { debug!("Command exited with code: {code}"); if let Ok(code) = u8::try_from(code) { Ok(ExitStatus::External(code)) } else { #[allow(clippy::exit)] std::process::exit(code); } } else { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; debug!("Command exited with signal: {:?}", status.signal()); // Following https://tldp.org/LDP/abs/html/exitcodes.html, a fatal signal n gets the // exit code 128+n if let Some(mapped_code) = status .signal() .and_then(|signal| u8::try_from(signal).ok()) .and_then(|signal| 128u8.checked_add(signal)) { return Ok(ExitStatus::External(mapped_code)); } } Ok(ExitStatus::Failure) } }
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/src/windows_exception.rs
crates/uv/src/windows_exception.rs
//! Helper for setting up Windows exception handling. //! //! Recent versions of Windows seem to no longer show dialog boxes on access violations //! (segfaults) or similar errors. The user experience is that the command exits with //! the exception code as its exit status and no visible output. In order to see these //! errors both in the field and in CI, we need to install our own exception handler. //! //! This is a relatively simple exception handler that leans on Rust's own backtrace //! implementation and also displays some minimal information from the exception itself. #![allow(unsafe_code)] // Usually we want fs_err over std::fs, but there's no advantage here, we don't // report errors encountered while reporting an exception. #![allow(clippy::disallowed_types)] use std::fmt::Write; use std::fs::File; use std::mem::ManuallyDrop; use std::os::windows::io::FromRawHandle; use arrayvec::ArrayVec; use windows::Win32::{ Foundation, Globalization::CP_UTF8, System::Console::{ CONSOLE_MODE, GetConsoleMode, GetConsoleOutputCP, GetStdHandle, STD_ERROR_HANDLE, WriteConsoleW, }, System::Diagnostics::Debug::{ CONTEXT, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, SetUnhandledExceptionFilter, }, }; /// A write target for standard error that can be safely used in an exception handler. /// /// The exception handler can be called at any point in the execution of machine code, perhaps /// halfway through a Rust operation. It needs to be robust to operating with unknown program /// state, a concept that the UNIX world calls "async signal safety." In particular, we can't /// write to `std::io::stderr()` because that takes a lock, and we could be called in the middle of /// code that is holding that lock. enum ExceptionSafeStderr { // This is a simplified version of the logic in Rust std::sys::stdio::windows, on the // assumption that we're only writing strs, not bytes (so we do not need to care about // incomplete or invalid UTF-8) and we don't care about Windows 7 or every drop of // performance. // - If stderr is a non-UTF-8 console, we need to write UTF-16 with WriteConsoleW, and we // convert with encode_utf16(). // - If stderr is not a console, we cannot use WriteConsole and must use NtWriteFile, which // takes (UTF-8) bytes. // - If stderr is a UTF-8 console, we can do either. std uses NtWriteFile. // Note that we do not want to close stderr at any point, hence ManuallyDrop. WriteConsole(Foundation::HANDLE), NtWriteFile(ManuallyDrop<File>), } impl ExceptionSafeStderr { fn new() -> Result<Self, windows::core::Error> { // SAFETY: winapi call, no interesting parameters let handle = unsafe { GetStdHandle(STD_ERROR_HANDLE) }?; if handle.is_invalid() { return Err(windows::core::Error::empty()); } let mut mode = CONSOLE_MODE::default(); // SAFETY: winapi calls, no interesting parameters if unsafe { GetConsoleMode(handle, &raw mut mode).is_ok() && GetConsoleOutputCP() != CP_UTF8 } { Ok(Self::WriteConsole(handle)) } else { // SAFETY: winapi call, we just got this handle from the OS and checked it let file = unsafe { File::from_raw_handle(handle.0) }; Ok(Self::NtWriteFile(ManuallyDrop::new(file))) } } fn write_winerror(&mut self, s: &str) -> Result<(), windows::core::Error> { match self { Self::WriteConsole(handle) => { // According to comments in the ReactOS source, NT's behavior is that writes of 80 // bytes or fewer are passed in-line in the message to the console server and // longer writes allocate out of a shared heap with CSRSS. In an attempt to avoid // allocations, write in 80-byte chunks. let mut buf = ArrayVec::<u16, 40>::new(); for c in s.encode_utf16() { if buf.try_push(c).is_err() { // SAFETY: winapi call, arrayvec guarantees the slice is valid unsafe { WriteConsoleW(*handle, &buf, None, None) }?; buf.clear(); buf.push(c); } } if !buf.is_empty() { // SAFETY: winapi call, arrayvec guarantees the slice is valid unsafe { WriteConsoleW(*handle, &buf, None, None) }?; } } Self::NtWriteFile(file) => { use std::io::Write; file.write_all(s.as_bytes())?; } } Ok(()) } } impl Write for ExceptionSafeStderr { fn write_str(&mut self, s: &str) -> std::fmt::Result { self.write_winerror(s).map_err(|_| std::fmt::Error) } } fn display_exception_info( e: &mut ExceptionSafeStderr, name: &str, info: &[usize; 15], ) -> std::fmt::Result { match info[0] { 0 => writeln!(e, "{name} reading {:#x}", info[1])?, 1 => writeln!(e, "{name} writing {:#x}", info[1])?, 8 => writeln!(e, "{name} executing {:#x}", info[1])?, _ => writeln!(e, "{name} from operation {} at {:#x}", info[0], info[1])?, } Ok(()) } #[cfg(target_arch = "x86")] fn dump_regs(e: &mut ExceptionSafeStderr, c: &CONTEXT) -> std::fmt::Result { let CONTEXT { Eax, Ebx, Ecx, Edx, Esi, Edi, Eip, Ebp, Esp, EFlags, .. } = c; writeln!( e, "eax={Eax:08x} ebx={Ebx:08x} ecx={Ecx:08x} edx={Edx:08x} esi={Esi:08x} edi={Edi:08x}" )?; writeln!( e, "eip={Eip:08x} ebp={Ebp:08x} esp={Esp:08x} eflags={EFlags:08x}" )?; Ok(()) } #[cfg(target_arch = "x86_64")] fn dump_regs(e: &mut ExceptionSafeStderr, c: &CONTEXT) -> std::fmt::Result { let CONTEXT { Rax, Rbx, Rcx, Rdx, Rsi, Rdi, Rsp, Rbp, R8, R9, R10, R11, R12, R13, R14, R15, Rip, EFlags, .. } = c; writeln!(e, "rax={Rax:016x} rbx={Rbx:016x} rcx={Rcx:016x}")?; writeln!(e, "rdx={Rdx:016x} rsi={Rsi:016x} rdi={Rdi:016x}")?; writeln!(e, "rsp={Rsp:016x} rbp={Rbp:016x} r8={R8 :016x}")?; writeln!(e, " r9={R9 :016x} r10={R10:016x} r11={R11:016x}")?; writeln!(e, "r12={R12:016x} r13={R13:016x} r14={R14:016x}")?; writeln!(e, "r15={R15:016x} rip={Rip:016x} eflags={EFlags:016x}")?; Ok(()) } #[cfg(target_arch = "aarch64")] fn dump_regs(e: &mut ExceptionSafeStderr, c: &CONTEXT) -> std::fmt::Result { let CONTEXT { Cpsr, Sp, Pc, .. } = c; // SAFETY: The two variants of this anonymous union are equivalent, // one's an array and one has named registers. let regs = unsafe { c.Anonymous.Anonymous }; let windows::Win32::System::Diagnostics::Debug::CONTEXT_0_0 { X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16, X17, X18, X19, X20, X21, X22, X23, X24, X25, X26, X27, X28, Fp, Lr, } = regs; writeln!(e, "cpsr={Cpsr:016x} sp={Sp :016x} pc={Pc :016x}")?; writeln!(e, " x0={X0 :016x} x1={X1 :016x} x2={X2 :016x}")?; writeln!(e, " x3={X3 :016x} x4={X4 :016x} x5={X5 :016x}")?; writeln!(e, " x6={X6 :016x} x7={X7 :016x} x8={X8 :016x}")?; writeln!(e, " x9={X9 :016x} x10={X10:016x} x11={X11:016x}")?; writeln!(e, " x12={X12 :016x} x13={X13:016x} x14={X14:016x}")?; writeln!(e, " x15={X15 :016x} x16={X16:016x} x17={X17:016x}")?; writeln!(e, " x18={X18 :016x} x19={X19:016x} x20={X20:016x}")?; writeln!(e, " x21={X21 :016x} x22={X22:016x} x23={X23:016x}")?; writeln!(e, " x24={X24 :016x} x25={X25:016x} x26={X26:016x}")?; writeln!(e, " x27={X27 :016x} x28={X28:016x}")?; writeln!(e, " fp={Fp :016x} lr={Lr :016x}")?; Ok(()) } fn dump_exception(exception_info: *const EXCEPTION_POINTERS) -> std::fmt::Result { let mut e = ExceptionSafeStderr::new().map_err(|_| std::fmt::Error)?; writeln!(e, "error: unhandled exception in uv, please report a bug:")?; let mut context = None; // SAFETY: Pointer comes from the OS if let Some(info) = unsafe { exception_info.as_ref() } { // SAFETY: Pointer comes from the OS if let Some(exc) = unsafe { info.ExceptionRecord.as_ref() } { writeln!( e, "code {:#X} at address {:?}", exc.ExceptionCode.0, exc.ExceptionAddress )?; match exc.ExceptionCode { Foundation::EXCEPTION_ACCESS_VIOLATION => { display_exception_info( &mut e, "EXCEPTION_ACCESS_VIOLATION", &exc.ExceptionInformation, )?; } Foundation::EXCEPTION_IN_PAGE_ERROR => { display_exception_info( &mut e, "EXCEPTION_IN_PAGE_ERROR", &exc.ExceptionInformation, )?; } Foundation::EXCEPTION_ILLEGAL_INSTRUCTION => { writeln!(e, "EXCEPTION_ILLEGAL_INSTRUCTION")?; } Foundation::EXCEPTION_STACK_OVERFLOW => { writeln!(e, "EXCEPTION_STACK_OVERFLOW")?; } _ => {} } } else { writeln!(e, "(ExceptionRecord is NULL)")?; } // SAFETY: Pointer comes from the OS context = unsafe { info.ContextRecord.as_ref() }; } else { writeln!(e, "(ExceptionInfo is NULL)")?; } // TODO: std::backtrace does a lot of allocations, so we are no longer async-signal-safe at // this point, but hopefully we got a useful error message on screen already. We could do a // better job by using backtrace-rs directly + arrayvec. let backtrace = std::backtrace::Backtrace::capture(); if backtrace.status() == std::backtrace::BacktraceStatus::Disabled { writeln!( e, "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace" )?; } else { if let Some(context) = context { dump_regs(&mut e, context)?; } writeln!(e, "stack backtrace:\n{backtrace:#}")?; } Ok(()) } unsafe extern "system" fn unhandled_exception_filter( exception_info: *const EXCEPTION_POINTERS, ) -> i32 { let _ = dump_exception(exception_info); EXCEPTION_CONTINUE_SEARCH } /// Set up our handler for unhandled exceptions. pub(crate) fn setup() { // SAFETY: winapi call, argument is a mostly async-signal-safe function unsafe { SetUnhandledExceptionFilter(Some(Some(unhandled_exception_filter))); } }
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/src/install_source.rs
crates/uv/src/install_source.rs
#![cfg(not(feature = "self-update"))] use std::{ ffi::OsStr, path::{Path, PathBuf}, }; /// Known sources for uv installations. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum InstallSource { Homebrew, } impl InstallSource { /// Attempt to infer the install source for the given executable path. fn from_path(path: &Path) -> Option<Self> { let canonical = path.canonicalize().unwrap_or_else(|_| PathBuf::from(path)); let components = canonical .components() .map(|component| component.as_os_str().to_owned()) .collect::<Vec<_>>(); let cellar = OsStr::new("Cellar"); let formula = OsStr::new("uv"); if components .windows(2) .any(|window| window[0] == cellar && window[1] == formula) { return Some(Self::Homebrew); } None } /// Detect how uv was installed by inspecting the current executable path. pub(crate) fn detect() -> Option<Self> { Self::from_path(&std::env::current_exe().ok()?) } pub(crate) fn description(self) -> &'static str { match self { Self::Homebrew => "Homebrew", } } pub(crate) fn update_instructions(self) -> &'static str { match self { Self::Homebrew => "brew update && brew upgrade uv", } } } #[cfg(test)] mod tests { use super::*; #[test] fn detects_homebrew_cellar() { assert_eq!( InstallSource::from_path(Path::new("/opt/homebrew/Cellar/uv/0.9.11/bin/uv")), Some(InstallSource::Homebrew) ); } #[test] fn ignores_non_cellar_paths() { assert_eq!( InstallSource::from_path(Path::new("/usr/local/bin/uv")), 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/src/logging.rs
crates/uv/src/logging.rs
use std::str::FromStr; use anyhow::Context; #[cfg(feature = "tracing-durations-export")] use tracing_durations_export::{ DurationsLayer, DurationsLayerBuilder, DurationsLayerDropGuard, plot::PlotConfig, }; use tracing_subscriber::filter::Directive; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, Layer, Registry}; use tracing_tree::HierarchicalLayer; use tracing_tree::time::Uptime; use uv_cli::ColorChoice; use uv_logging::UvFormat; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub(crate) enum Level { #[default] Off, DebugUv, TraceUv, TraceAll, } /// Configure `tracing` based on the given [`Level`], taking into account the `RUST_LOG` environment /// variable. /// /// The [`Level`] is used to dictate the default filters (which can be overridden by the `RUST_LOG` /// environment variable) along with the formatting of the output. For example, [`Level::Verbose`] /// includes targets and timestamps, along with all `uv=debug` messages by default. pub(crate) fn setup_logging( level: Level, durations_layer: Option<impl Layer<Registry> + Send + Sync>, color: ColorChoice, detailed_logging: bool, ) -> anyhow::Result<()> { // We use directives here to ensure `RUST_LOG` can override them let default_directive = match level { Level::Off => { // Show nothing tracing::level_filters::LevelFilter::OFF.into() } Level::DebugUv => { // Show `DEBUG` messages from the CLI crate (and ERROR/WARN/INFO) Directive::from_str("uv=debug").unwrap() } Level::TraceUv => { // Show `TRACE` messages from the CLI crate (and ERROR/WARN/INFO/DEBUG) Directive::from_str("uv=trace").unwrap() } Level::TraceAll => { // Show all `TRACE` messages (and ERROR/WARN/INFO/DEBUG) Directive::from_str("trace").unwrap() } }; // Avoid setting the default log level to INFO let durations_layer = durations_layer.map(|durations_layer| { durations_layer.with_filter( // Only record our own spans tracing_subscriber::filter::Targets::new() .with_target("", tracing::level_filters::LevelFilter::INFO), ) }); let filter = EnvFilter::builder() .with_default_directive(default_directive) .from_env() .context("Invalid RUST_LOG directives")?; // Determine our final color settings and create an anstream wrapper based on it. // // The tracing `with_ansi` function on affects color tracing adds *on top of* the // log messages. This means that if we `debug!("{}", "hello".green())`, // (a thing we absolutely do throughout uv), then there will still be color // in the logs, which is undesirable. // // So we tell tracing to print to an anstream wrapper around stderr that force-strips ansi. // Given we do this, using `with_ansi` at all is arguably pointless, but it feels morally // correct to still do it? I don't know what would break if we didn't... but why find out? let (ansi, color_choice) = match color.and_colorchoice(anstream::Stderr::choice(&std::io::stderr())) { ColorChoice::Always => (true, anstream::ColorChoice::Always), ColorChoice::Never => (false, anstream::ColorChoice::Never), ColorChoice::Auto => unreachable!("anstream can't return auto as choice"), }; let writer = std::sync::Mutex::new(anstream::AutoStream::new(std::io::stderr(), color_choice)); if detailed_logging { // Regardless of the tracing level, include the uptime and target for each message. tracing_subscriber::registry() .with(durations_layer) .with( HierarchicalLayer::default() .with_targets(true) .with_timer(Uptime::default()) .with_writer(writer) .with_ansi(ansi) .with_filter(filter), ) .init(); } else { tracing_subscriber::registry() .with(durations_layer) .with( tracing_subscriber::fmt::layer() .event_format(UvFormat::default()) .with_writer(writer) .with_ansi(ansi) .with_filter(filter), ) .init(); } Ok(()) } /// Setup the `TRACING_DURATIONS_FILE` environment variable to enable tracing durations. #[cfg(feature = "tracing-durations-export")] pub(crate) fn setup_durations( tracing_durations_file: Option<&std::path::PathBuf>, ) -> anyhow::Result<( Option<DurationsLayer<Registry>>, Option<DurationsLayerDropGuard>, )> { if let Some(location) = tracing_durations_file { if let Some(parent) = location.parent() { fs_err::create_dir_all(parent) .context("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() .context("Couldn't create TRACING_DURATIONS_FILE files")?; Ok((Some(layer), Some(guard))) } else { Ok((None, 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/src/commands/venv.rs
crates/uv/src/commands/venv.rs
use std::fmt::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::vec; use anyhow::Result; use owo_colors::OwoColorize; use thiserror::Error; use uv_cache::Cache; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ BuildOptions, Concurrency, Constraints, DependencyGroups, DryRun, IndexStrategy, KeyringProviderType, NoBinary, NoBuild, SourceStrategy, }; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildRequires, Index, IndexLocations, PackageConfigSettings, Requirement, }; use uv_fs::Simplified; use uv_install_wheel::LinkMode; use uv_normalize::DefaultGroups; use uv_preview::{Preview, PreviewFeatures}; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest, }; use uv_resolver::{ExcludeNewer, FlatIndex}; use uv_settings::PythonInstallMirrors; use uv_shell::{Shell, shlex_posix, shlex_windows}; use uv_types::{AnyErrorBuild, BuildContext, BuildIsolation, BuildStack, HashStrategy}; use uv_virtualenv::OnExisting; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache, WorkspaceError}; use crate::commands::ExitStatus; use crate::commands::pip::loggers::{DefaultInstallLogger, InstallLogger}; use crate::commands::pip::operations::{Changelog, report_interpreter}; use crate::commands::project::{WorkspacePython, validate_project_requires_python}; use crate::commands::reporters::PythonDownloadReporter; use crate::printer::Printer; use super::project::default_dependency_groups; #[derive(Error, Debug)] enum VenvError { #[error("Failed to create virtual environment")] Creation(#[source] uv_virtualenv::Error), #[error("Failed to install seed packages into virtual environment")] Seed(#[source] AnyErrorBuild), #[error("Failed to extract interpreter tags for installing seed packages")] Tags(#[source] uv_platform_tags::TagsError), #[error("Failed to resolve `--find-links` entry")] FlatIndex(#[source] uv_client::FlatIndexError), } /// Create a virtual environment. #[allow(clippy::unnecessary_wraps, clippy::fn_params_excessive_bools)] pub(crate) async fn venv( project_dir: &Path, path: Option<PathBuf>, python_request: Option<PythonRequest>, install_mirrors: PythonInstallMirrors, python_preference: PythonPreference, python_downloads: PythonDownloads, link_mode: LinkMode, index_locations: &IndexLocations, index_strategy: IndexStrategy, dependency_metadata: DependencyMetadata, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, prompt: uv_virtualenv::Prompt, system_site_packages: bool, seed: bool, on_existing: OnExisting, exclude_newer: ExcludeNewer, concurrency: Concurrency, no_config: bool, no_project: bool, cache: &Cache, printer: Printer, relocatable: bool, preview: Preview, ) -> Result<ExitStatus> { let workspace_cache = WorkspaceCache::default(); let project = if no_project { None } else { match VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await { Ok(project) => Some(project), Err(WorkspaceError::MissingProject(_)) => None, Err(WorkspaceError::MissingPyprojectToml) => None, Err(WorkspaceError::NonWorkspace(_)) => None, Err(WorkspaceError::Toml(path, err)) => { warn_user!( "Failed to parse `{}` during environment creation:\n{}", path.user_display().cyan(), textwrap::indent(&err.to_string(), " ") ); None } Err(err) => { warn_user!("{err}"); None } } }; // Determine the default path; either the virtual environment for the project or `.venv` let path = path.unwrap_or( project .as_ref() .and_then(|project| { // Only use the project environment path if we're invoked from the root // This isn't strictly necessary and we may want to change it later, but this // avoids a breaking change when adding project environment support to `uv venv`. (project.workspace().install_path() == project_dir) .then(|| project.workspace().venv(Some(false))) }) .unwrap_or(PathBuf::from(".venv")), ); let reporter = PythonDownloadReporter::single(printer); // If the default dependency-groups demand a higher requires-python // we should bias an empty venv to that to avoid churn. let default_groups = match &project { Some(project) => default_dependency_groups(project.pyproject_toml())?, None => DefaultGroups::default(), }; let groups = DependencyGroups::default().with_defaults(default_groups); let WorkspacePython { source, python_request, requires_python, } = WorkspacePython::from_request( python_request, project.as_ref().map(VirtualProject::workspace), &groups, project_dir, no_config, ) .await?; // Locate the Python interpreter to use in the environment let interpreter = { let python = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await?; report_interpreter(&python, false, printer)?; python.into_interpreter() }; // Check if the discovered Python version is incompatible with the current workspace if let Some(requires_python) = requires_python { match validate_project_requires_python( &interpreter, project.as_ref().map(VirtualProject::workspace), &groups, &requires_python, &source, ) { Ok(()) => {} Err(err) => { warn_user!("{err}"); } } } writeln!( printer.stderr(), "Creating virtual environment {}at: {}", if seed { "with seed packages " } else { "" }, path.user_display().cyan() )?; let upgradeable = preview.is_enabled(PreviewFeatures::PYTHON_UPGRADE) && python_request .as_ref() .is_none_or(|request| !request.includes_patch()); // Create the virtual environment. let venv = uv_virtualenv::create_venv( &path, interpreter, prompt, system_site_packages, on_existing, relocatable, seed, upgradeable, preview, ) .map_err(VenvError::Creation)?; // Install seed packages. if seed { // Extract the interpreter. let interpreter = venv.interpreter(); // Instantiate a client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .keyring(keyring_provider) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Resolve the flat indexes from `--find-links`. let flat_index = { let tags = interpreter.tags().map_err(VenvError::Tags)?; let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await .map_err(VenvError::FlatIndex)?; FlatIndex::from_entries( entries, Some(tags), &HashStrategy::None, &BuildOptions::new(NoBinary::None, NoBuild::All), ) }; // Initialize any shared state. let state = SharedState::default(); let workspace_cache = WorkspaceCache::default(); // For seed packages, assume a bunch of default settings are sufficient. let build_constraints = Constraints::default(); let build_hasher = HashStrategy::default(); let config_settings = ConfigSettings::default(); let config_settings_package = PackageConfigSettings::default(); let sources = SourceStrategy::Disabled; // Do not allow builds let build_options = BuildOptions::new(NoBinary::None, NoBuild::All); let extra_build_requires = ExtraBuildRequires::default(); let extra_build_variables = uv_distribution_types::ExtraBuildVariables::default(); // Prep the build context. let build_dispatch = BuildDispatch::new( &client, cache, &build_constraints, interpreter, index_locations, &flat_index, &dependency_metadata, state.clone(), index_strategy, &config_settings, &config_settings_package, BuildIsolation::Isolated, &extra_build_requires, &extra_build_variables, link_mode, &build_options, &build_hasher, exclude_newer, sources, workspace_cache, concurrency, preview, ); // Resolve the seed packages. let requirements = if interpreter.python_tuple() >= (3, 12) { vec![Requirement::from( uv_pep508::Requirement::from_str("pip").unwrap(), )] } else { // Include `setuptools` and `wheel` on Python <3.12. vec![ Requirement::from(uv_pep508::Requirement::from_str("pip").unwrap()), Requirement::from(uv_pep508::Requirement::from_str("setuptools").unwrap()), Requirement::from(uv_pep508::Requirement::from_str("wheel").unwrap()), ] }; let build_stack = BuildStack::default(); // Resolve and install the requirements. // // Since the virtual environment is empty, and the set of requirements is trivial (no // constraints, no editables, etc.), we can use the build dispatch APIs directly. let resolution = build_dispatch .resolve(&requirements, &build_stack) .await .map_err(|err| VenvError::Seed(err.into()))?; let installed = build_dispatch .install(&resolution, &venv, &build_stack) .await .map_err(|err| VenvError::Seed(err.into()))?; let changelog = Changelog::from_installed(installed); DefaultInstallLogger.on_complete(&changelog, printer, DryRun::Disabled)?; } // Determine the appropriate activation command. let activation = match Shell::from_env() { None => None, Some(Shell::Bash | Shell::Zsh | Shell::Ksh) => Some(format!( "source {}", shlex_posix(venv.scripts().join("activate")) )), Some(Shell::Fish) => Some(format!( "source {}", shlex_posix(venv.scripts().join("activate.fish")) )), Some(Shell::Nushell) => Some(format!( "overlay use {}", shlex_posix(venv.scripts().join("activate.nu")) )), Some(Shell::Csh) => Some(format!( "source {}", shlex_posix(venv.scripts().join("activate.csh")) )), Some(Shell::Powershell) => Some(shlex_windows( venv.scripts().join("activate"), Shell::Powershell, )), Some(Shell::Cmd) => Some(shlex_windows(venv.scripts().join("activate"), Shell::Cmd)), }; if let Some(act) = activation { writeln!(printer.stderr(), "Activate with: {}", act.green())?; } Ok(ExitStatus::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/src/commands/diagnostics.rs
crates/uv/src/commands/diagnostics.rs
use std::str::FromStr; use std::sync::{Arc, LazyLock}; use owo_colors::OwoColorize; use rustc_hash::FxHashMap; use version_ranges::Ranges; use uv_distribution_types::{ DerivationChain, DerivationStep, Dist, DistErrorKind, Name, RequestedDist, }; use uv_normalize::PackageName; use uv_pep440::Version; use uv_resolver::SentinelRange; use crate::commands::pip; static SUGGESTIONS: LazyLock<FxHashMap<PackageName, PackageName>> = LazyLock::new(|| { let suggestions: Vec<(String, String)> = serde_json::from_str(include_str!("suggestions.json")).unwrap(); suggestions .iter() .map(|(k, v)| { ( PackageName::from_str(k).unwrap(), PackageName::from_str(v).unwrap(), ) }) .collect() }); /// A rich reporter for operational diagnostics, i.e., errors that occur during resolution and /// installation. #[derive(Debug, Default)] pub(crate) struct OperationDiagnostic { /// The hint to display to the user upon resolution failure. pub(crate) hint: Option<String>, /// Whether native TLS is enabled. pub(crate) native_tls: bool, /// The context to display to the user upon resolution failure. pub(crate) context: Option<&'static str>, } impl OperationDiagnostic { /// Create an [`OperationDiagnostic`] with the given native TLS setting. #[must_use] pub(crate) fn native_tls(native_tls: bool) -> Self { Self { native_tls, ..Default::default() } } /// Set the hint to display to the user upon resolution failure. #[must_use] pub(crate) fn with_hint(self, hint: String) -> Self { Self { hint: Some(hint), ..self } } /// Set the context to display to the user upon resolution failure. #[must_use] pub(crate) fn with_context(self, context: &'static str) -> Self { Self { context: Some(context), ..self } } /// Attempt to report an error with rich diagnostic context. /// /// Returns `Some` if the error was not handled. pub(crate) fn report(self, err: pip::operations::Error) -> Option<pip::operations::Error> { match err { pip::operations::Error::Resolve(uv_resolver::ResolveError::NoSolution(err)) => { if let Some(context) = self.context { no_solution_context(&err, context); } else if let Some(hint) = self.hint { no_solution_hint(err, hint); } else { no_solution(&err); } None } pip::operations::Error::Resolve(uv_resolver::ResolveError::Dist( kind, dist, chain, err, )) => { requested_dist_error(kind, dist, &chain, err, self.hint); None } pip::operations::Error::Resolve(uv_resolver::ResolveError::Dependencies( error, name, version, chain, )) => { dependencies_error(error, &name, &version, &chain, self.hint.clone()); None } pip::operations::Error::Requirements(uv_requirements::Error::Dist(kind, dist, err)) => { dist_error( kind, dist, &DerivationChain::default(), Arc::new(err), self.hint, ); None } pip::operations::Error::Prepare(uv_installer::PrepareError::Dist( kind, dist, chain, err, )) => { dist_error(kind, dist, &chain, Arc::new(err), self.hint); None } pip::operations::Error::Requirements(err) => { if let Some(context) = self.context { let err = miette::Report::msg(format!("{err}")) .context(format!("Failed to resolve {context} requirement")); anstream::eprint!("{err:?}"); None } else { Some(pip::operations::Error::Requirements(err)) } } pip::operations::Error::Resolve(uv_resolver::ResolveError::Client(err)) if !self.native_tls && err.is_ssl() => { native_tls_hint(err); None } pip::operations::Error::OutdatedEnvironment => { anstream::eprintln!("{}", err); None } err => Some(err), } } } /// Render a distribution failure (read, download or build) with a help message. pub(crate) fn dist_error( kind: DistErrorKind, dist: Box<Dist>, chain: &DerivationChain, cause: Arc<uv_distribution::Error>, help: Option<String>, ) { #[derive(Debug, miette::Diagnostic, thiserror::Error)] #[error("{kind} `{dist}`")] #[diagnostic()] struct Diagnostic { kind: DistErrorKind, dist: Box<Dist>, #[source] cause: Arc<uv_distribution::Error>, #[help] help: Option<String>, } let help = help.or_else(|| { SUGGESTIONS .get(dist.name()) .map(|suggestion| { format!( "`{}` is often confused for `{}` Did you mean to install `{}` instead?", dist.name().cyan(), suggestion.cyan(), suggestion.cyan(), ) }) .or_else(|| { if chain.is_empty() { None } else { Some(format_chain(dist.name(), dist.version(), chain)) } }) }); let report = miette::Report::new(Diagnostic { kind, dist, cause, help, }); anstream::eprint!("{report:?}"); } /// Render a requested distribution failure (read, download or build) with a help message. pub(crate) fn requested_dist_error( kind: DistErrorKind, dist: Box<RequestedDist>, chain: &DerivationChain, cause: Arc<uv_distribution::Error>, help: Option<String>, ) { #[derive(Debug, miette::Diagnostic, thiserror::Error)] #[error("{kind} `{dist}`")] #[diagnostic()] struct Diagnostic { kind: DistErrorKind, dist: Box<RequestedDist>, #[source] cause: Arc<uv_distribution::Error>, #[help] help: Option<String>, } let help = help.or_else(|| { SUGGESTIONS .get(dist.name()) .map(|suggestion| { format!( "`{}` is often confused for `{}` Did you mean to install `{}` instead?", dist.name().cyan(), suggestion.cyan(), suggestion.cyan(), ) }) .or_else(|| { if chain.is_empty() { None } else { Some(format_chain(dist.name(), dist.version(), chain)) } }) }); let report = miette::Report::new(Diagnostic { kind, dist, cause, help, }); anstream::eprint!("{report:?}"); } /// Render an error in fetching a package's dependencies. pub(crate) fn dependencies_error( error: Box<uv_resolver::ResolveError>, name: &PackageName, version: &Version, chain: &DerivationChain, help: Option<String>, ) { #[derive(Debug, miette::Diagnostic, thiserror::Error)] #[error("Failed to resolve dependencies for `{}` ({})", name.cyan(), format!("v{version}").cyan())] #[diagnostic()] struct Diagnostic { name: PackageName, version: Version, #[source] cause: Box<uv_resolver::ResolveError>, #[help] help: Option<String>, } let help = help.or_else(|| { SUGGESTIONS .get(name) .map(|suggestion| { format!( "`{}` is often confused for `{}` Did you mean to install `{}` instead?", name.cyan(), suggestion.cyan(), suggestion.cyan(), ) }) .or_else(|| { if chain.is_empty() { None } else { Some(format_chain(name, Some(version), chain)) } }) }); let report = miette::Report::new(Diagnostic { name: name.clone(), version: version.clone(), cause: error, help, }); anstream::eprint!("{report:?}"); } /// Render a [`uv_resolver::NoSolutionError`]. pub(crate) fn no_solution(err: &uv_resolver::NoSolutionError) { let report = miette::Report::msg(format!("{err}")).context(err.header()); anstream::eprint!("{report:?}"); } /// Render a [`uv_resolver::NoSolutionError`] with dedicated context. pub(crate) fn no_solution_context(err: &uv_resolver::NoSolutionError, context: &'static str) { let report = miette::Report::msg(format!("{err}")).context(err.header().with_context(context)); anstream::eprint!("{report:?}"); } /// Render a [`uv_resolver::NoSolutionError`] with a help message. pub(crate) fn no_solution_hint(err: Box<uv_resolver::NoSolutionError>, help: String) { #[derive(Debug, miette::Diagnostic, thiserror::Error)] #[error("{header}")] #[diagnostic()] struct Error { /// The header to render in the error message. header: uv_resolver::NoSolutionHeader, /// The underlying error. #[source] err: Box<uv_resolver::NoSolutionError>, /// The help message to display. #[help] help: String, } let header = err.header(); let report = miette::Report::new(Error { header, err, help }); anstream::eprint!("{report:?}"); } /// Render a [`uv_resolver::NoSolutionError`] with a help message. pub(crate) fn native_tls_hint(err: uv_client::Error) { #[derive(Debug, miette::Diagnostic)] #[diagnostic()] struct Error { /// The underlying error. err: uv_client::Error, /// The help message to display. #[help] help: String, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.err) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.err.source() } } let report = miette::Report::new(Error { err, help: format!( "Consider enabling use of system TLS certificates with the `{}` command-line flag", "--native-tls".green() ), }); anstream::eprint!("{report:?}"); } /// Format a [`DerivationChain`] as a human-readable error message. fn format_chain(name: &PackageName, version: Option<&Version>, chain: &DerivationChain) -> String { /// Format a step in the [`DerivationChain`] as a human-readable error message. fn format_step(step: &DerivationStep, range: Option<Ranges<Version>>) -> String { if let Some(range) = range.filter(|range| *range != Ranges::empty() && *range != Ranges::full()) { if let Some(extra) = &step.extra { if let Some(version) = step.version.as_ref() { // Ex) `flask[dotenv]>=1.0.0` (v1.2.3) format!( "`{}{}` ({})", format!("{}[{}]", step.name, extra).cyan(), range.cyan(), format!("v{version}").cyan(), ) } else { // Ex) `flask[dotenv]>=1.0.0` format!( "`{}{}`", format!("{}[{}]", step.name, extra).cyan(), range.cyan(), ) } } else if let Some(group) = &step.group { if let Some(version) = step.version.as_ref() { // Ex) `flask:dev>=1.0.0` (v1.2.3) format!( "`{}{}` ({})", format!("{}:{}", step.name, group).cyan(), range.cyan(), format!("v{version}").cyan(), ) } else { // Ex) `flask:dev>=1.0.0` format!( "`{}{}`", format!("{}:{}", step.name, group).cyan(), range.cyan(), ) } } else { if let Some(version) = step.version.as_ref() { // Ex) `flask>=1.0.0` (v1.2.3) format!( "`{}{}` ({})", step.name.cyan(), range.cyan(), format!("v{version}").cyan(), ) } else { // Ex) `flask>=1.0.0` format!("`{}{}`", step.name.cyan(), range.cyan()) } } } else { if let Some(extra) = &step.extra { if let Some(version) = step.version.as_ref() { // Ex) `flask[dotenv]` (v1.2.3) format!( "`{}` ({})", format!("{}[{}]", step.name, extra).cyan(), format!("v{version}").cyan(), ) } else { // Ex) `flask[dotenv]` format!("`{}`", format!("{}[{}]", step.name, extra).cyan()) } } else if let Some(group) = &step.group { if let Some(version) = step.version.as_ref() { // Ex) `flask:dev` (v1.2.3) format!( "`{}` ({})", format!("{}:{}", step.name, group).cyan(), format!("v{version}").cyan(), ) } else { // Ex) `flask:dev` format!("`{}`", format!("{}:{}", step.name, group).cyan()) } } else { if let Some(version) = step.version.as_ref() { // Ex) `flask` (v1.2.3) format!("`{}` ({})", step.name.cyan(), format!("v{version}").cyan()) } else { // Ex) `flask` format!("`{}`", step.name.cyan()) } } } } let mut message = if let Some(version) = version { format!( "`{}` ({}) was included because", name.cyan(), format!("v{version}").cyan() ) } else { format!("`{}` was included because", name.cyan()) }; let mut range: Option<Ranges<Version>> = None; for (i, step) in chain.iter().enumerate() { if i > 0 { message = format!("{message} {} which depends on", format_step(step, range)); } else { message = format!("{message} {} depends on", format_step(step, range)); } range = Some(SentinelRange::from(&step.range).strip()); } if let Some(range) = range.filter(|range| *range != Ranges::empty() && *range != Ranges::full()) { message = format!("{message} `{}{}`", name.cyan(), range.cyan()); } else { message = format!("{message} `{}`", name.cyan()); } message }
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/src/commands/publish.rs
crates/uv/src/commands/publish.rs
use std::fmt::Write; use std::sync::Arc; use anyhow::{Context, Result, bail}; use console::Term; use owo_colors::{AnsiColors, OwoColorize}; use tokio::sync::Semaphore; use tracing::{debug, info, trace}; use uv_auth::{Credentials, DEFAULT_TOLERANCE_SECS, PyxTokenStore}; use uv_cache::Cache; use uv_client::{ AuthIntegration, BaseClient, BaseClientBuilder, RedirectPolicy, RegistryClientBuilder, }; use uv_configuration::{KeyringProviderType, TrustedPublishing}; use uv_distribution_types::{IndexCapabilities, IndexLocations, IndexUrl}; use uv_publish::{ CheckUrlClient, FormMetadata, PublishError, TrustedPublishResult, check_trusted_publishing, group_files_for_publishing, upload, }; use uv_redacted::DisplaySafeUrl; use uv_settings::EnvironmentOptions; use uv_warnings::{warn_user_once, write_error_chain}; use crate::commands::reporters::PublishReporter; use crate::commands::{ExitStatus, human_readable_bytes}; use crate::printer::Printer; pub(crate) async fn publish( paths: Vec<String>, publish_url: DisplaySafeUrl, trusted_publishing: TrustedPublishing, keyring_provider: KeyringProviderType, environment: &EnvironmentOptions, client_builder: &BaseClientBuilder<'_>, username: Option<String>, password: Option<String>, check_url: Option<IndexUrl>, index: Option<String>, index_locations: IndexLocations, dry_run: bool, no_attestations: bool, cache: &Cache, printer: Printer, ) -> Result<ExitStatus> { if client_builder.is_offline() { bail!("Unable to publish files in offline mode"); } let token_store = PyxTokenStore::from_settings()?; let (publish_url, check_url) = if let Some(index_name) = index { // If the user provided an index by name, look it up. debug!("Publishing with index {index_name}"); let index = index_locations .simple_indexes() .find(|index| { index .name .as_ref() .is_some_and(|name| name.as_ref() == index_name) }) .with_context(|| { let mut index_names: Vec<String> = index_locations .simple_indexes() .filter_map(|index| index.name.as_ref()) .map(ToString::to_string) .collect(); index_names.sort(); if index_names.is_empty() { format!("No indexes were found, can't use index: `{index_name}`") } else { let index_names = index_names.join("`, `"); format!("Index not found: `{index_name}`. Found indexes: `{index_names}`") } })?; let publish_url = index .publish_url .clone() .with_context(|| format!("Index is missing a publish URL: `{index_name}`"))?; // pyx has the same behavior as PyPI where uploads of identical // files + contents are idempotent, so we don't need to pre-check. if token_store.is_known_url(&publish_url) { (publish_url, None) } else { let check_url = index.url.clone(); (publish_url, Some(check_url)) } } else { (publish_url, check_url) }; let groups = group_files_for_publishing(paths, no_attestations)?; match groups.len() { 0 => bail!("No files found to publish"), 1 => { if dry_run { writeln!(printer.stderr(), "Checking 1 file against {publish_url}")?; } else { writeln!(printer.stderr(), "Publishing 1 file to {publish_url}")?; } } n => { if dry_run { writeln!(printer.stderr(), "Checking {n} files against {publish_url}")?; } else { writeln!(printer.stderr(), "Publishing {n} files to {publish_url}")?; } } } // * For the uploads themselves, we roll our own retries due to // https://github.com/seanmonstar/reqwest/issues/2416, but for trusted publishing, we want // the default retries. We set the retries to 0 here and manually construct the retry policy // in the upload loop. // * We want to allow configuring TLS for the registry, while for trusted publishing we know the // defaults are correct. // * For the uploads themselves, we know we need an authorization header and we can't nor // shouldn't try cloning the request to make an unauthenticated request first, but we want // keyring integration. For trusted publishing, we use an OIDC auth routine without keyring // or other auth integration. let upload_client = client_builder .clone() .retries(0) .keyring(keyring_provider) // Don't try cloning the request to make an unauthenticated request first. .auth_integration(AuthIntegration::OnlyAuthenticated) // Disable automatic redirect, as the streaming publish request is not cloneable. // Rely on custom redirect logic instead. .redirect(RedirectPolicy::NoRedirect) .timeout(environment.upload_http_timeout) .build(); let oidc_client = client_builder .clone() .auth_integration(AuthIntegration::NoAuthMiddleware) .wrap_existing(&upload_client); let retry_policy = client_builder.retry_policy(); // We're only checking a single URL and one at a time, so 1 permit is sufficient let download_concurrency = Arc::new(Semaphore::new(1)); // Load credentials. let (publish_url, credentials) = gather_credentials( publish_url, username, password, trusted_publishing, keyring_provider, &token_store, &oidc_client, &upload_client, check_url.as_ref(), Prompt::Enabled, printer, ) .await?; // Initialize the registry client. let check_url_client = if let Some(index_url) = &check_url { let registry_client_builder = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations) .keyring(keyring_provider); Some(CheckUrlClient { index_url: index_url.clone(), registry_client_builder, client: &upload_client, index_capabilities: IndexCapabilities::default(), cache, }) } else { None }; for group in groups { if let Some(check_url_client) = &check_url_client { if uv_publish::check_url( check_url_client, &group.file, &group.filename, &download_concurrency, ) .await? { writeln!( printer.stderr(), "File {} already exists, skipping", group.filename )?; continue; } } let size = fs_err::metadata(&group.file)?.len(); let (bytes, unit) = human_readable_bytes(size); if dry_run { writeln!( printer.stderr(), "{} {} {}", "Checking".bold().cyan(), group.filename, format!("({bytes:.1}{unit})").dimmed() )?; } else { writeln!( printer.stderr(), "{} {} {}", "Uploading".bold().green(), group.filename, format!("({bytes:.1}{unit})").dimmed() )?; } // Collect the metadata for the file. let form_metadata = FormMetadata::read_from_file(&group.file, &group.filename) .await .map_err(|err| PublishError::PublishPrepare(group.file.clone(), Box::new(err)))?; // Run validation checks on the file, but don't upload it (if possible). uv_publish::validate( &group.file, &form_metadata, &group.raw_filename, &publish_url, &token_store, &upload_client, &credentials, ) .await?; if dry_run { continue; } let reporter = PublishReporter::single(printer); let uploaded = upload( &group, &form_metadata, &publish_url, &upload_client, retry_policy, &credentials, check_url_client.as_ref(), &download_concurrency, // Needs to be an `Arc` because the reqwest `Body` static lifetime requirement Arc::new(reporter), ) .await?; // Filename and/or URL are already attached, if applicable. info!("Upload succeeded"); if !uploaded { writeln!( printer.stderr(), "{}", "File already exists, skipping".dimmed() )?; } } Ok(ExitStatus::Success) } /// Whether to allow prompting for username and password. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Prompt { Enabled, #[allow(dead_code)] Disabled, } /// Unify the different possible source for username and password information. /// /// Possible credential sources are environment variables, the CLI, the URL, the keyring, trusted /// publishing or a prompt. /// /// The username can come from, in order: /// /// - Mutually exclusive: /// - `--username` or `UV_PUBLISH_USERNAME`. The CLI option overrides the environment variable /// - The username field in the publish URL /// - If `--token` or `UV_PUBLISH_TOKEN` are used, it is `__token__`. The CLI option /// overrides the environment variable /// - If trusted publishing is available, it is `__token__` /// - (We currently do not read the username from the keyring) /// - If stderr is a tty, prompt the user /// /// The password can come from, in order: /// /// - Mutually exclusive: /// - `--password` or `UV_PUBLISH_PASSWORD`. The CLI option overrides the environment variable /// - The password field in the publish URL /// - If `--token` or `UV_PUBLISH_TOKEN` are used, it is the token value. The CLI option overrides /// the environment variable /// - If the keyring is enabled, the keyring entry for the URL and username /// - If trusted publishing is available, the trusted publishing token /// - If stderr is a tty, prompt the user /// /// If no credentials are found, the auth middleware does a final check for cached credentials and /// otherwise errors without sending the request. /// /// Returns the publish URL, the username and the password. async fn gather_credentials( mut publish_url: DisplaySafeUrl, mut username: Option<String>, mut password: Option<String>, trusted_publishing: TrustedPublishing, keyring_provider: KeyringProviderType, token_store: &PyxTokenStore, oidc_client: &BaseClient, base_client: &BaseClient, check_url: Option<&IndexUrl>, prompt: Prompt, printer: Printer, ) -> Result<(DisplaySafeUrl, Credentials)> { // Support reading username and password from the URL, for symmetry with the index API. if let Some(url_password) = publish_url.password() { if password.is_some_and(|password| password != url_password) { bail!("The password can't be set both in the publish URL and in the CLI"); } password = Some(url_password.to_string()); publish_url .set_password(None) .expect("Failed to clear publish URL password"); } if !publish_url.username().is_empty() { if username.is_some_and(|username| username != publish_url.username()) { bail!("The username can't be set both in the publish URL and in the CLI"); } username = Some(publish_url.username().to_string()); publish_url .set_username("") .expect("Failed to clear publish URL username"); } // If the user is publishing to pyx, load the credentials from the store. if username.is_none() && password.is_none() { if token_store.is_known_url(&publish_url) { if let Some(token) = token_store .access_token( base_client.for_host(token_store.api()).raw_client(), DEFAULT_TOLERANCE_SECS, ) .await? { debug!("Using authentication token from the store"); return Ok((publish_url, Credentials::from(token))); } } } // If applicable, attempt obtaining a token for trusted publishing. let trusted_publishing_token = check_trusted_publishing( username.as_deref(), password.as_deref(), keyring_provider, trusted_publishing, &publish_url, oidc_client, ) .await?; let (username, mut password) = if let TrustedPublishResult::Configured(password) = &trusted_publishing_token { (Some("__token__".to_string()), Some(password.to_string())) } else { if username.is_none() && password.is_none() { match prompt { Prompt::Enabled => prompt_username_and_password()?, Prompt::Disabled => (None, None), } } else { (username, password) } }; if password.is_some() && username.is_none() { bail!( "Attempted to publish with a password, but no username. Either provide a username \ with `--username` (`UV_PUBLISH_USERNAME`), or use `--token` (`UV_PUBLISH_TOKEN`) \ instead of a password." ); } if username.is_none() && password.is_none() && keyring_provider == KeyringProviderType::Disabled { if let TrustedPublishResult::Ignored(err) = trusted_publishing_token { // The user has configured something incorrectly: // * The user forgot to configure credentials. // * The user forgot to forward the secrets as env vars (or used the wrong ones). // * The trusted publishing configuration is wrong. writeln!( printer.stderr(), "Note: Neither credentials nor keyring are configured, and there was an error \ fetching the trusted publishing token. If you don't want to use trusted \ publishing, you can ignore this error, but you need to provide credentials." )?; trace!("Error trace: {err:?}"); write_error_chain( anyhow::Error::from(err) .context("Trusted publishing failed") .as_ref(), printer.stderr(), "error", AnsiColors::Red, )?; } } // If applicable, fetch the password from the keyring eagerly to avoid user confusion about // missing keyring entries later. if let Some(provider) = keyring_provider.to_provider() { if password.is_none() { if let Some(username) = &username { debug!("Fetching password from keyring"); if let Some(keyring_password) = provider .fetch(DisplaySafeUrl::ref_cast(&publish_url), Some(username)) .await .as_ref() .and_then(|credentials| credentials.password()) { password = Some(keyring_password.to_string()); } else { warn_user_once!( "Keyring has no password for URL `{publish_url}` and username `{username}`" ); } } } else if check_url.is_none() { warn_user_once!( "Using `--keyring-provider` with a password or token and no check URL has no effect" ); } else { // We may be using the keyring for the simple index. } } let credentials = Credentials::basic(username, password); Ok((publish_url, credentials)) } fn prompt_username_and_password() -> Result<(Option<String>, Option<String>)> { let term = Term::stderr(); if !term.is_term() { return Ok((None, None)); } let username_prompt = "Enter username ('__token__' if using a token): "; let password_prompt = "Enter password: "; let username = uv_console::input(username_prompt, &term).context("Failed to read username")?; let password = uv_console::password(password_prompt, &term).context("Failed to read password")?; Ok((Some(username), Some(password))) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; use insta::assert_snapshot; use uv_redacted::DisplaySafeUrl; async fn get_credentials( url: DisplaySafeUrl, username: Option<String>, password: Option<String>, ) -> Result<(DisplaySafeUrl, Credentials)> { let client = BaseClientBuilder::default().build(); let token_store = PyxTokenStore::from_settings()?; gather_credentials( url, username, password, TrustedPublishing::Never, KeyringProviderType::Disabled, &token_store, &client, &client, None, Prompt::Disabled, Printer::Quiet, ) .await } #[tokio::test] async fn username_password_sources() { let example_url = DisplaySafeUrl::from_str("https://example.com").unwrap(); let example_url_username = DisplaySafeUrl::from_str("https://ferris@example.com").unwrap(); let example_url_username_password = DisplaySafeUrl::from_str("https://ferris:f3rr1s@example.com").unwrap(); let (publish_url, credentials) = get_credentials(example_url.clone(), None, None) .await .unwrap(); assert_eq!(publish_url, example_url); assert_eq!(credentials.username(), None); assert_eq!(credentials.password(), None); let (publish_url, credentials) = get_credentials(example_url_username.clone(), None, None) .await .unwrap(); assert_eq!(publish_url, example_url); assert_eq!(credentials.username(), Some("ferris")); assert_eq!(credentials.password(), None); let (publish_url, credentials) = get_credentials(example_url_username_password.clone(), None, None) .await .unwrap(); assert_eq!(publish_url, example_url); assert_eq!(credentials.username(), Some("ferris")); assert_eq!(credentials.password(), Some("f3rr1s")); // Ok: The username is the same between CLI/env vars and URL let (publish_url, credentials) = get_credentials( example_url_username_password.clone(), Some("ferris".to_string()), None, ) .await .unwrap(); assert_eq!(publish_url, example_url); assert_eq!(credentials.username(), Some("ferris")); assert_eq!(credentials.password(), Some("f3rr1s")); // Err: There are two different usernames between CLI/env vars and URL let err = get_credentials( example_url_username_password.clone(), Some("packaging-platypus".to_string()), None, ) .await .unwrap_err(); assert_snapshot!( err.to_string(), @"The username can't be set both in the publish URL and in the CLI" ); // Ok: The username and password are the same between CLI/env vars and URL let (publish_url, credentials) = get_credentials( example_url_username_password.clone(), Some("ferris".to_string()), Some("f3rr1s".to_string()), ) .await .unwrap(); assert_eq!(publish_url, example_url); assert_eq!(credentials.username(), Some("ferris")); assert_eq!(credentials.password(), Some("f3rr1s")); // Err: There are two different passwords between CLI/env vars and URL let err = get_credentials( example_url_username_password.clone(), Some("ferris".to_string()), Some("secret".to_string()), ) .await .unwrap_err(); assert_snapshot!( err.to_string(), @"The password can't be set both in the publish URL and in the CLI" ); } }
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/src/commands/cache_prune.rs
crates/uv/src/commands/cache_prune.rs
use std::fmt::Write; use anyhow::{Context, Result}; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::{Cache, Removal}; use uv_fs::Simplified; use crate::commands::{ExitStatus, human_readable_bytes}; use crate::printer::Printer; /// Prune all unreachable objects from the cache. pub(crate) async fn cache_prune( ci: bool, force: bool, cache: Cache, printer: Printer, ) -> Result<ExitStatus> { if !cache.root().exists() { writeln!( printer.stderr(), "No cache found at: {}", cache.root().user_display().cyan() )?; return Ok(ExitStatus::Success); } let cache = match cache.with_exclusive_lock_no_wait() { Ok(cache) => cache, Err(cache) if force => { debug!("Cache is currently in use, proceeding due to `--force`"); cache } Err(cache) => { writeln!( printer.stderr(), "Cache is currently in-use, waiting for other uv processes to finish (use `--force` to override)" )?; cache.with_exclusive_lock().await? } }; writeln!( printer.stderr(), "Pruning cache at: {}", cache.root().user_display().cyan() )?; let mut summary = Removal::default(); // Prune the source distribution cache, which is tightly coupled to the builder crate. summary += uv_distribution::prune(&cache) .with_context(|| format!("Failed to prune cache at: {}", cache.root().user_display()))?; // Prune the remaining cache buckets. summary += cache .prune(ci) .with_context(|| format!("Failed to prune cache at: {}", cache.root().user_display()))?; // Write a summary of the number of files and directories removed. match (summary.num_files, summary.num_dirs) { (0, 0) => { write!(printer.stderr(), "No unused entries found")?; } (0, 1) => { write!(printer.stderr(), "Removed 1 directory")?; } (0, num_dirs_removed) => { write!(printer.stderr(), "Removed {num_dirs_removed} directories")?; } (1, _) => { write!(printer.stderr(), "Removed 1 file")?; } (num_files_removed, _) => { write!(printer.stderr(), "Removed {num_files_removed} files")?; } } // If any, write a summary of the total byte count removed. if summary.total_bytes > 0 { let bytes = if summary.total_bytes < 1024 { format!("{}B", summary.total_bytes) } else { let (bytes, unit) = human_readable_bytes(summary.total_bytes); format!("{bytes:.1}{unit}") }; write!(printer.stderr(), " ({})", bytes.green())?; } writeln!(printer.stderr())?; Ok(ExitStatus::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/src/commands/build_backend.rs
crates/uv/src/commands/build_backend.rs
use crate::commands::ExitStatus; use anyhow::{Context, Result}; use std::env; use std::io::Write; use std::path::Path; /// PEP 517 hook to build a source distribution. pub(crate) fn build_sdist(sdist_directory: &Path) -> Result<ExitStatus> { 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")?; Ok(ExitStatus::Success) } /// PEP 517 hook to build a wheel. pub(crate) fn build_wheel( wheel_directory: &Path, metadata_directory: Option<&Path>, ) -> Result<ExitStatus> { let filename = uv_build_backend::build_wheel( &env::current_dir()?, wheel_directory, metadata_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")?; Ok(ExitStatus::Success) } /// PEP 660 hook to build a wheel. pub(crate) fn build_editable( wheel_directory: &Path, metadata_directory: Option<&Path>, ) -> Result<ExitStatus> { let filename = uv_build_backend::build_editable( &env::current_dir()?, wheel_directory, metadata_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")?; Ok(ExitStatus::Success) } /// Not used from Python code, exists for symmetry with PEP 517. pub(crate) fn get_requires_for_build_sdist() -> Result<ExitStatus> { unimplemented!("uv does not support extra requires") } /// Not used from Python code, exists for symmetry with PEP 517. pub(crate) fn get_requires_for_build_wheel() -> Result<ExitStatus> { unimplemented!("uv does not support extra requires") } /// PEP 517 hook to just emit metadata through `.dist-info`. pub(crate) fn prepare_metadata_for_build_wheel(metadata_directory: &Path) -> Result<ExitStatus> { let filename = uv_build_backend::metadata( &env::current_dir()?, metadata_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")?; Ok(ExitStatus::Success) } /// Not used from Python code, exists for symmetry with PEP 660. pub(crate) fn get_requires_for_build_editable() -> Result<ExitStatus> { unimplemented!("uv does not support extra requires") } /// PEP 660 hook to just emit metadata through `.dist-info`. pub(crate) fn prepare_metadata_for_build_editable(metadata_directory: &Path) -> Result<ExitStatus> { let filename = uv_build_backend::metadata( &env::current_dir()?, metadata_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")?; Ok(ExitStatus::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/src/commands/cache_clean.rs
crates/uv/src/commands/cache_clean.rs
use std::fmt::Write; use anyhow::{Context, Result}; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::{Cache, Removal}; use uv_fs::Simplified; use uv_normalize::PackageName; use crate::commands::reporters::{CleaningDirectoryReporter, CleaningPackageReporter}; use crate::commands::{ExitStatus, human_readable_bytes}; use crate::printer::Printer; /// Clear the cache, removing all entries or those linked to specific packages. pub(crate) async fn cache_clean( packages: &[PackageName], force: bool, cache: Cache, printer: Printer, ) -> Result<ExitStatus> { if !cache.root().exists() { writeln!( printer.stderr(), "No cache found at: {}", cache.root().user_display().cyan() )?; return Ok(ExitStatus::Success); } let cache = match cache.with_exclusive_lock_no_wait() { Ok(cache) => cache, Err(cache) if force => { debug!("Cache is currently in use, proceeding due to `--force`"); cache } Err(cache) => { writeln!( printer.stderr(), "Cache is currently in-use, waiting for other uv processes to finish (use `--force` to override)" )?; cache.with_exclusive_lock().await? } }; let summary = if packages.is_empty() { writeln!( printer.stderr(), "Clearing cache at: {}", cache.root().user_display().cyan() )?; let num_paths = walkdir::WalkDir::new(cache.root()).into_iter().count(); let reporter = CleaningDirectoryReporter::new(printer, Some(num_paths)); let root = cache.root().to_path_buf(); cache .clear(Box::new(reporter)) .with_context(|| format!("Failed to clear cache at: {}", root.user_display()))? } else { let reporter = CleaningPackageReporter::new(printer, Some(packages.len())); let mut summary = Removal::default(); for package in packages { let removed = cache.remove(package)?; summary += removed; reporter.on_clean(package.as_str(), &summary); } reporter.on_complete(); summary }; // Write a summary of the number of files and directories removed. match (summary.num_files, summary.num_dirs) { (0, 0) => { write!(printer.stderr(), "No cache entries found")?; } (0, 1) => { write!(printer.stderr(), "Removed 1 directory")?; } (0, num_dirs_removed) => { write!(printer.stderr(), "Removed {num_dirs_removed} directories")?; } (1, _) => { write!(printer.stderr(), "Removed 1 file")?; } (num_files_removed, _) => { write!(printer.stderr(), "Removed {num_files_removed} files")?; } } // If any, write a summary of the total byte count removed. if summary.total_bytes > 0 { let bytes = if summary.total_bytes < 1024 { format!("{}B", summary.total_bytes) } else { let (bytes, unit) = human_readable_bytes(summary.total_bytes); format!("{bytes:.1}{unit}") }; write!(printer.stderr(), " ({})", bytes.green())?; } writeln!(printer.stderr())?; Ok(ExitStatus::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/src/commands/cache_dir.rs
crates/uv/src/commands/cache_dir.rs
use owo_colors::OwoColorize; use std::fmt::Write; use uv_cache::Cache; use uv_fs::Simplified; use crate::commands::ExitStatus; use crate::printer::Printer; /// Show the cache directory. pub(crate) fn cache_dir(cache: &Cache, printer: Printer) -> anyhow::Result<ExitStatus> { writeln!( printer.stdout(), "{}", cache.root().simplified_display().cyan() )?; Ok(ExitStatus::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/src/commands/cache_size.rs
crates/uv/src/commands/cache_size.rs
use std::fmt::Write; use anyhow::Result; use diskus::DiskUsage; use crate::commands::{ExitStatus, human_readable_bytes}; use crate::printer::Printer; use uv_cache::Cache; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::warn_user; /// Display the total size of the cache. pub(crate) fn cache_size( cache: &Cache, human_readable: bool, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::CACHE_SIZE) { warn_user!( "`uv cache size` is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::CACHE_SIZE ); } if !cache.root().exists() { if human_readable { writeln!(printer.stdout_important(), "0B")?; } else { writeln!(printer.stdout_important(), "0")?; } return Ok(ExitStatus::Success); } let disk_usage = DiskUsage::new(vec![cache.root().to_path_buf()]); let total_bytes = disk_usage.count_ignoring_errors(); if human_readable { let (bytes, unit) = human_readable_bytes(total_bytes); writeln!(printer.stdout_important(), "{bytes:.1}{unit}")?; } else { writeln!(printer.stdout_important(), "{total_bytes}")?; } Ok(ExitStatus::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/src/commands/help.rs
crates/uv/src/commands/help.rs
use std::ffi::OsString; use std::path::PathBuf; use std::str::FromStr; use std::{fmt::Display, fmt::Write}; use anstream::{ColorChoice, stream::IsTerminal}; use anyhow::{Result, anyhow}; use clap::CommandFactory; use itertools::Itertools; use owo_colors::OwoColorize; use which::which; use super::ExitStatus; use crate::printer::Printer; use uv_cli::Cli; use uv_static::EnvVars; // hidden subcommands to show in the help command const SHOW_HIDDEN_COMMANDS: &[&str] = &["generate-shell-completion"]; pub(crate) fn help(query: &[String], printer: Printer, no_pager: bool) -> Result<ExitStatus> { let mut uv: clap::Command = SHOW_HIDDEN_COMMANDS .iter() .fold(Cli::command(), |uv, &name| { uv.mut_subcommand(name, |cmd| cmd.hide(false)) }); // It is very important to build the command before beginning inspection or subcommands // will be missing all of the propagated options. uv.build(); let command = find_command(query, &uv).map_err(|(unmatched, nearest)| { let missing = if unmatched.len() == query.len() { format!("`{}` for `uv`", query.join(" ")) } else { format!("`{}` for `uv {}`", unmatched.join(" "), nearest.get_name()) }; anyhow!( "There is no command {}. Did you mean one of:\n {}", missing, nearest .get_subcommands() .filter(|cmd| !cmd.is_hide_set()) .map(clap::Command::get_name) .filter(|name| *name != "help") .join("\n "), ) })?; let name = command.get_name(); let is_root = name == uv.get_name(); let mut command = command.clone(); let help = if is_root { command .after_help(format!( "Use `{}` for more information on a specific command.", "uv help <command>".bold() )) .render_help() } else { if command.has_subcommands() { command.after_long_help(format!( "Use `{}` for more information on a specific command.", format!("uv help {name} <command>").bold() )) } else { command } .render_long_help() }; let want_color = match anstream::Stdout::choice(&std::io::stdout()) { ColorChoice::Always | ColorChoice::AlwaysAnsi => true, ColorChoice::Never => false, // We just asked anstream for a choice, that can't be auto ColorChoice::Auto => unreachable!(), }; let is_terminal = std::io::stdout().is_terminal(); let should_page = !no_pager && !is_root && is_terminal; if should_page && let Some(pager) = Pager::try_from_env() { let query = query.join(" "); if want_color && pager.supports_colors() { pager.spawn(format!("{}: {query}", "uv help".bold()), help.ansi())?; } else { pager.spawn(format!("uv help: {query}"), help)?; } } else { if want_color { writeln!(printer.stdout(), "{}", help.ansi())?; } else { writeln!(printer.stdout(), "{help}")?; } } Ok(ExitStatus::Success) } /// Find the command corresponding to a set of arguments, e.g., `["uv", "pip", "install"]`. /// /// If the command cannot be found, the nearest command is returned. fn find_command<'a>( query: &'a [String], cmd: &'a clap::Command, ) -> Result<&'a clap::Command, (&'a [String], &'a clap::Command)> { let Some(next) = query.first() else { return Ok(cmd); }; let subcommand = cmd.find_subcommand(next).ok_or((query, cmd))?; find_command(&query[1..], subcommand) } #[derive(Debug)] enum PagerKind { Less, More, Other(String), } #[derive(Debug)] struct Pager { kind: PagerKind, args: Vec<String>, path: Option<PathBuf>, } impl PagerKind { fn default_args(&self) -> Vec<String> { match self { Self::Less => vec!["-R".to_string()], Self::More => vec![], Self::Other(_) => vec![], } } } impl Display for PagerKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Less => write!(f, "less"), Self::More => write!(f, "more"), Self::Other(name) => write!(f, "{name}"), } } } impl FromStr for Pager { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { let mut split = s.split_ascii_whitespace(); // Empty string let Some(first) = split.next() else { return Err(()); }; match first { "less" => Ok(Self { kind: PagerKind::Less, args: split.map(str::to_string).collect(), path: None, }), "more" => Ok(Self { kind: PagerKind::More, args: split.map(str::to_string).collect(), path: None, }), _ => Ok(Self { kind: PagerKind::Other(first.to_string()), args: split.map(str::to_string).collect(), path: None, }), } } } impl Pager { /// Display `contents` using the pager. fn spawn(self, heading: String, contents: impl Display) -> Result<()> { use std::io::Write; let command = self .path .as_ref() .map(|path| path.as_os_str().to_os_string()) .unwrap_or(OsString::from(self.kind.to_string())); let args = if self.args.is_empty() { self.kind.default_args() } else { self.args }; let mut child = std::process::Command::new(command) .args(args) .stdin(std::process::Stdio::piped()) .spawn()?; let mut stdin = child .stdin .take() .ok_or_else(|| anyhow!("Failed to take child process stdin"))?; let contents = contents.to_string(); let writer = std::thread::spawn(move || { let _ = write!(stdin, "{heading}\n\n"); let _ = stdin.write_all(contents.as_bytes()); }); drop(child.wait()); drop(writer.join()); Ok(()) } /// Get a pager to use and its path, if available. /// /// Supports the `PAGER` environment variable, otherwise checks for `less` and `more` in the /// search path. fn try_from_env() -> Option<Self> { if let Some(pager) = std::env::var_os(EnvVars::PAGER) { if !pager.is_empty() { return Self::from_str(&pager.to_string_lossy()).ok(); } } if let Ok(less) = which("less") { Some(Self { kind: PagerKind::Less, args: vec![], path: Some(less), }) } else if let Ok(more) = which("more") { Some(Self { kind: PagerKind::More, args: vec![], path: Some(more), }) } else { None } } fn supports_colors(&self) -> bool { match self.kind { // The `-R` flag is required for color support. We will provide it by default. PagerKind::Less => self.args.is_empty() || self.args.iter().any(|arg| arg == "-R"), PagerKind::More => false, PagerKind::Other(_) => 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/src/commands/build_frontend.rs
crates/uv/src/commands/build_frontend.rs
use std::borrow::Cow; use std::fmt::Write as _; use std::io::Write as _; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fmt, io}; use anyhow::{Context, Result}; use owo_colors::OwoColorize; use thiserror::Error; use tracing::instrument; use uv_build_backend::check_direct_build; use uv_cache::{Cache, CacheBucket}; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ BuildIsolation, BuildKind, BuildOptions, BuildOutput, Concurrency, Constraints, DependencyGroupsWithDefaults, HashCheckingMode, IndexStrategy, KeyringProviderType, SourceStrategy, }; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_filename::{ DistFilename, SourceDistExtension, SourceDistFilename, WheelFilename, }; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildVariables, Index, IndexLocations, PackageConfigSettings, RequiresPython, SourceDist, }; use uv_fs::{Simplified, relative_to}; use uv_install_wheel::LinkMode; use uv_normalize::PackageName; use uv_pep440::Version; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVariant, PythonVersionFile, VersionFileDiscoveryOptions, VersionRequest, }; use uv_requirements::RequirementsSource; use uv_resolver::{ExcludeNewer, FlatIndex}; use uv_settings::PythonInstallMirrors; use uv_types::{AnyErrorBuild, BuildContext, BuildStack, HashStrategy}; use uv_workspace::pyproject::ExtraBuildDependencies; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache, WorkspaceError}; use crate::commands::ExitStatus; use crate::commands::pip::operations; use crate::commands::project::{ProjectError, find_requires_python}; use crate::commands::reporters::PythonDownloadReporter; use crate::printer::Printer; use crate::settings::ResolverSettings; #[derive(Debug, Error)] enum Error { #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] FindOrDownloadPython(#[from] uv_python::Error), #[error(transparent)] HashStrategy(#[from] uv_types::HashStrategyError), #[error(transparent)] FlatIndex(#[from] uv_client::FlatIndexError), #[error(transparent)] BuildPlan(anyhow::Error), #[error(transparent)] Extract(#[from] uv_extract::Error), #[error(transparent)] Operations(#[from] operations::Error), #[error(transparent)] Join(#[from] tokio::task::JoinError), #[error(transparent)] BuildBackend(#[from] uv_build_backend::Error), #[error(transparent)] BuildDispatch(AnyErrorBuild), #[error(transparent)] BuildFrontend(#[from] uv_build_frontend::Error), #[error(transparent)] Project(#[from] ProjectError), #[error("Failed to write message")] Fmt(#[from] fmt::Error), #[error("Can't use `--force-pep517` with `--list`")] ListForcePep517, #[error("Can only use `--list` with the uv backend")] ListNonUv, #[error( "`{0}` is not a valid build source. Expected to receive a source directory, or a source \ distribution ending in one of: {1}." )] InvalidSourceDistExt(String, uv_distribution_filename::ExtensionError), #[error("The built source distribution has an invalid filename")] InvalidBuiltSourceDistFilename(#[source] uv_distribution_filename::SourceDistFilenameError), #[error("The built wheel has an invalid filename")] InvalidBuiltWheelFilename(#[source] uv_distribution_filename::WheelFilenameError), #[error("The source distribution declares version {0}, but the wheel declares version {1}")] VersionMismatch(Version, Version), } /// Build source distributions and wheels. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn build_frontend( project_dir: &Path, src: Option<PathBuf>, package: Option<PackageName>, all_packages: bool, output_dir: Option<PathBuf>, sdist: bool, wheel: bool, list: bool, build_logs: bool, gitignore: bool, force_pep517: bool, clear: bool, build_constraints: Vec<RequirementsSource>, hash_checking: Option<HashCheckingMode>, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: &ResolverSettings, client_builder: &BaseClientBuilder<'_>, no_config: bool, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let build_result = build_impl( project_dir, src.as_deref(), package.as_ref(), all_packages, output_dir.as_deref(), sdist, wheel, list, build_logs, gitignore, force_pep517, clear, &build_constraints, hash_checking, python.as_deref(), install_mirrors, settings, client_builder, no_config, python_preference, python_downloads, concurrency, cache, printer, preview, ) .await?; match build_result { BuildResult::Failure => Ok(ExitStatus::Error), BuildResult::Success => Ok(ExitStatus::Success), } } /// Represents the overall result of a build process. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum BuildResult { /// Indicates that at least one of the builds failed. Failure, /// Indicates that all builds succeeded. Success, } #[allow(clippy::fn_params_excessive_bools)] async fn build_impl( project_dir: &Path, src: Option<&Path>, package: Option<&PackageName>, all_packages: bool, output_dir: Option<&Path>, sdist: bool, wheel: bool, list: bool, build_logs: bool, gitignore: bool, force_pep517: bool, clear: bool, build_constraints: &[RequirementsSource], hash_checking: Option<HashCheckingMode>, python_request: Option<&str>, install_mirrors: PythonInstallMirrors, settings: &ResolverSettings, client_builder: &BaseClientBuilder<'_>, no_config: bool, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<BuildResult> { // Extract the resolver settings. let ResolverSettings { index_locations, index_strategy, keyring_provider, resolution: _, prerelease: _, fork_strategy: _, dependency_metadata, config_setting, config_settings_package, build_isolation, extra_build_dependencies, extra_build_variables, exclude_newer, link_mode, upgrade: _, build_options, sources, torch_backend: _, } = settings; // Determine the source to build. let src = if let Some(src) = src { let src = std::path::absolute(src)?; let metadata = match fs_err::tokio::metadata(&src).await { Ok(metadata) => metadata, Err(err) if err.kind() == io::ErrorKind::NotFound => { return Err(anyhow::anyhow!( "Source `{}` does not exist", src.user_display() )); } Err(err) => return Err(err.into()), }; if metadata.is_file() { Source::File(Cow::Owned(src)) } else { Source::Directory(Cow::Owned(src)) } } else { Source::Directory(Cow::Borrowed(project_dir)) }; // Attempt to discover the workspace; on failure, save the error for later. let workspace_cache = WorkspaceCache::default(); let workspace = Workspace::discover( src.directory(), &DiscoveryOptions::default(), &workspace_cache, ) .await; // If a `--package` or `--all-packages` was provided, adjust the source directory. let packages = if let Some(package) = package { if matches!(src, Source::File(_)) { return Err(anyhow::anyhow!( "Cannot specify `--package` when building from a file" )); } let workspace = match workspace { Ok(ref workspace) => workspace, Err(err) => { return Err(err).context("`--package` was provided, but no workspace was found"); } }; let package = workspace .packages() .get(package) .ok_or_else(|| anyhow::anyhow!("Package `{package}` not found in workspace"))?; if !package.pyproject_toml().is_package(true) { let name = &package.project().name; let pyproject_toml = package.root().join("pyproject.toml"); return Err(anyhow::anyhow!( "Package `{}` is missing a `{}`. For example, to build with `{}`, add the following to `{}`:\n```toml\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n```", name.cyan(), "build-system".green(), "setuptools".cyan(), pyproject_toml.user_display().cyan() )); } vec![AnnotatedSource::from(Source::Directory(Cow::Borrowed( package.root(), )))] } else if all_packages { if matches!(src, Source::File(_)) { return Err(anyhow::anyhow!( "Cannot specify `--all-packages` when building from a file" )); } let workspace = match workspace { Ok(ref workspace) => workspace, Err(err) => { return Err(err) .context("`--all-packages` was provided, but no workspace was found"); } }; if workspace.packages().is_empty() { return Err(anyhow::anyhow!("No packages found in workspace")); } let packages: Vec<_> = workspace .packages() .values() .filter(|package| package.pyproject_toml().is_package(true)) .map(|package| AnnotatedSource { source: Source::Directory(Cow::Borrowed(package.root())), package: Some(package.project().name.clone()), }) .collect(); if packages.is_empty() { let member = workspace.packages().values().next().unwrap(); let name = &member.project().name; let pyproject_toml = member.root().join("pyproject.toml"); return Err(anyhow::anyhow!( "Workspace does not contain any buildable packages. For example, to build `{}` with `{}`, add a `{}` to `{}`:\n```toml\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n```", name.cyan(), "setuptools".cyan(), "build-system".green(), pyproject_toml.user_display().cyan() )); } packages } else { vec![AnnotatedSource::from(src)] }; let results: Vec<_> = futures::future::join_all(packages.into_iter().map(|source| { let future = build_package( source.clone(), output_dir, python_request, install_mirrors.clone(), no_config, workspace.as_ref(), python_preference, python_downloads, cache, printer, index_locations, client_builder.clone(), hash_checking, build_logs, gitignore, force_pep517, clear, build_constraints, build_isolation, extra_build_dependencies, extra_build_variables, *index_strategy, *keyring_provider, exclude_newer.clone(), *sources, concurrency, build_options, sdist, wheel, list, dependency_metadata, *link_mode, config_setting, config_settings_package, preview, ); async { let result = future.await; (source, result) } })) .await; let mut success = true; for (source, result) in results { match result { Ok(messages) => { for message in messages { message.print(printer)?; } } Err(err) => { #[derive(Debug, miette::Diagnostic, thiserror::Error)] #[error("Failed to build `{source}`", source = source.cyan())] #[diagnostic()] struct Diagnostic { source: String, #[source] cause: anyhow::Error, #[help] help: Option<String>, } let help = if let Error::Extract(uv_extract::Error::Tar(err)) = &err { // TODO(konsti): astral-tokio-tar should use a proper error instead of // encoding everything in strings // NOTE(ww): We check for both messages below because the both indicate // different external extraction scenarios; the first is for any // absolute path outside of the target directory, and the second // is specifically for symlinks that point outside. if err.to_string().contains("/bin/python") && std::error::Error::source(err).is_some_and(|err| { let err = err.to_string(); err.ends_with("outside of the target directory") || err.ends_with("external symlinks are not allowed") }) { Some( "This file seems to be part of a virtual environment. Virtual environments must be excluded from source distributions." .to_string(), ) } else { None } } else { None }; let report = miette::Report::new(Diagnostic { source: source.to_string(), cause: err.into(), help, }); anstream::eprint!("{report:?}"); success = false; } } } if success { Ok(BuildResult::Success) } else { Ok(BuildResult::Failure) } } #[allow(clippy::fn_params_excessive_bools)] async fn build_package( source: AnnotatedSource<'_>, output_dir: Option<&Path>, python_request: Option<&str>, install_mirrors: PythonInstallMirrors, no_config: bool, workspace: Result<&Workspace, &WorkspaceError>, python_preference: PythonPreference, python_downloads: PythonDownloads, cache: &Cache, printer: Printer, index_locations: &IndexLocations, client_builder: BaseClientBuilder<'_>, hash_checking: Option<HashCheckingMode>, build_logs: bool, gitignore: bool, force_pep517: bool, clear: bool, build_constraints: &[RequirementsSource], build_isolation: &BuildIsolation, extra_build_dependencies: &ExtraBuildDependencies, extra_build_variables: &ExtraBuildVariables, index_strategy: IndexStrategy, keyring_provider: KeyringProviderType, exclude_newer: ExcludeNewer, sources: SourceStrategy, concurrency: Concurrency, build_options: &BuildOptions, sdist: bool, wheel: bool, list: bool, dependency_metadata: &DependencyMetadata, link_mode: LinkMode, config_setting: &ConfigSettings, config_settings_package: &PackageConfigSettings, preview: Preview, ) -> Result<Vec<BuildMessage>, Error> { let output_dir = if let Some(output_dir) = output_dir { Cow::Owned(std::path::absolute(output_dir)?) } else { if let Ok(workspace) = workspace { Cow::Owned(workspace.install_path().join("dist")) } else { match &source.source { Source::Directory(src) => Cow::Owned(src.join("dist")), Source::File(src) => Cow::Borrowed(src.parent().unwrap()), } } }; // Clear the output directory if requested if clear && output_dir.exists() { fs_err::remove_dir_all(&*output_dir)?; } // (1) Explicit request from user let mut interpreter_request = python_request.map(PythonRequest::parse); // (2) Request from `.python-version` if interpreter_request.is_none() { interpreter_request = PythonVersionFile::discover( source.directory(), &VersionFileDiscoveryOptions::default().with_no_config(no_config), ) .await? .and_then(PythonVersionFile::into_version); } // (3) `Requires-Python` in `pyproject.toml` if interpreter_request.is_none() { if let Ok(workspace) = workspace { let groups = DependencyGroupsWithDefaults::none(); interpreter_request = find_requires_python(workspace, &groups)? .as_ref() .map(RequiresPython::specifiers) .map(|specifiers| { PythonRequest::Version(VersionRequest::Range( specifiers.clone(), PythonVariant::Default, )) }); } } // Locate the Python interpreter to use in the environment. let interpreter = PythonInstallation::find_or_download( interpreter_request.as_ref(), EnvironmentPreference::Any, python_preference, python_downloads, &client_builder, cache, Some(&PythonDownloadReporter::single(printer)), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); // Read build constraints. let build_constraints = operations::read_constraints(build_constraints, &client_builder).await?; // Collect the set of required hashes. let hasher = if let Some(hash_checking) = hash_checking { HashStrategy::from_requirements( std::iter::empty(), build_constraints .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), Some(&interpreter.resolver_marker_environment()), hash_checking, )? } else { HashStrategy::None }; let build_constraints = Constraints::from_requirements( build_constraints .into_iter() .map(|constraint| constraint.requirement), ); // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .keyring(keyring_provider) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Determine whether to enable build isolation. let environment; let types_build_isolation = match build_isolation { BuildIsolation::Isolate => uv_types::BuildIsolation::Isolated, BuildIsolation::Shared => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); uv_types::BuildIsolation::Shared(&environment) } BuildIsolation::SharedPackage(packages) => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); uv_types::BuildIsolation::SharedPackage(&environment, packages) } }; // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, None, &hasher, build_options) }; // Initialize any shared state. let state = SharedState::default(); let workspace_cache = WorkspaceCache::default(); let extra_build_requires = LoweredExtraBuildDependencies::from_non_lowered(extra_build_dependencies.clone()) .into_inner(); // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, cache, &build_constraints, &interpreter, index_locations, &flat_index, dependency_metadata, state.clone(), index_strategy, config_setting, config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, build_options, &hasher, exclude_newer, sources, workspace_cache, concurrency, preview, ); prepare_output_directory(&output_dir, gitignore).await?; // Determine the build plan. let plan = BuildPlan::determine(&source, sdist, wheel).map_err(Error::BuildPlan)?; // Check if the build backend is matching uv version that allows calling in the uv build backend // directly. let build_action = if list { if force_pep517 { return Err(Error::ListForcePep517); } if !check_direct_build(source.path(), source.path().user_display()) { // TODO(konsti): Provide more context on what mismatched return Err(Error::ListNonUv); } BuildAction::List } else if !force_pep517 && check_direct_build(source.path(), source.path().user_display()) { BuildAction::DirectBuild } else { BuildAction::Pep517 }; // Prepare some common arguments for the build. let dist = None; let subdirectory = None; let version_id = source.path().file_name().and_then(|name| name.to_str()); let build_output = match printer { Printer::Default | Printer::NoProgress | Printer::Verbose => { if build_logs && !uv_flags::contains(uv_flags::EnvironmentFlags::HIDE_BUILD_OUTPUT) { BuildOutput::Stderr } else { BuildOutput::Quiet } } Printer::Quiet | Printer::Silent => BuildOutput::Quiet, }; let mut build_results = Vec::new(); match plan { BuildPlan::SdistToWheel => { // Even when listing files, we still need to build the source distribution for the wheel // build. if list { let sdist_list = build_sdist( source.path(), &output_dir, build_action, &source, printer, "source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, ) .await?; build_results.push(sdist_list); } let sdist_build = build_sdist( source.path(), &output_dir, build_action.force_build(), &source, printer, "source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, ) .await?; build_results.push(sdist_build.clone()); // Extract the source distribution into a temporary directory. let path = output_dir.join(sdist_build.raw_filename()); let reader = fs_err::tokio::File::open(&path).await?; let ext = SourceDistExtension::from_path(path.as_path()) .map_err(|err| Error::InvalidSourceDistExt(path.user_display().to_string(), err))?; let temp_dir = tempfile::tempdir_in(cache.bucket(CacheBucket::SourceDistributions))?; uv_extract::stream::archive(reader, ext, temp_dir.path()).await?; // Extract the top-level directory from the archive. let extracted = match uv_extract::strip_component(temp_dir.path()) { Ok(top_level) => top_level, Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(), Err(err) => return Err(err.into()), }; let wheel_build = build_wheel( &extracted, &output_dir, build_action, &source, printer, "wheel from source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, Some(sdist_build.normalized_filename().version()), ) .await?; build_results.push(wheel_build); } BuildPlan::Sdist => { let sdist_build = build_sdist( source.path(), &output_dir, build_action, &source, printer, "source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, ) .await?; build_results.push(sdist_build); } BuildPlan::Wheel => { let wheel_build = build_wheel( source.path(), &output_dir, build_action, &source, printer, "wheel", &build_dispatch, sources, dist, subdirectory, version_id, build_output, None, ) .await?; build_results.push(wheel_build); } BuildPlan::SdistAndWheel => { let sdist_build = build_sdist( source.path(), &output_dir, build_action, &source, printer, "source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, ) .await?; let wheel_build = build_wheel( source.path(), &output_dir, build_action, &source, printer, "wheel", &build_dispatch, sources, dist, subdirectory, version_id, build_output, Some(sdist_build.normalized_filename().version()), ) .await?; build_results.push(sdist_build); build_results.push(wheel_build); } BuildPlan::WheelFromSdist => { // Extract the source distribution into a temporary directory. let reader = fs_err::tokio::File::open(source.path()).await?; let ext = SourceDistExtension::from_path(source.path()).map_err(|err| { Error::InvalidSourceDistExt(source.path().user_display().to_string(), err) })?; let temp_dir = tempfile::tempdir_in(&output_dir)?; uv_extract::stream::archive(reader, ext, temp_dir.path()).await?; // If the source distribution has a version in its filename, check the version. let version = source .path() .file_name() .and_then(|filename| filename.to_str()) .and_then(|filename| SourceDistFilename::parsed_normalized_filename(filename).ok()) .map(|filename| filename.version); // Extract the top-level directory from the archive. let extracted = match uv_extract::strip_component(temp_dir.path()) { Ok(top_level) => top_level, Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(), Err(err) => return Err(err.into()), }; let wheel_build = build_wheel( &extracted, &output_dir, build_action, &source, printer, "wheel from source distribution", &build_dispatch, sources, dist, subdirectory, version_id, build_output, version.as_ref(), ) .await?; build_results.push(wheel_build); } } Ok(build_results) } #[derive(Copy, Clone, PartialEq, Eq)] enum BuildAction { /// Only list the files that would be included, don't actually build. List, /// Build by calling directly into the build backend. DirectBuild, /// Build through the PEP 517 hooks. Pep517, } impl BuildAction { /// If in list mode, still build the distribution. fn force_build(self) -> Self { match self { // List is only available for the uv build backend Self::List => Self::DirectBuild, Self::DirectBuild => Self::DirectBuild, Self::Pep517 => Self::Pep517, } } } /// Build a source distribution, either through PEP 517 or through a direct build. #[instrument(skip_all)] async fn build_sdist( source_tree: &Path, output_dir: &Path, action: BuildAction, source: &AnnotatedSource<'_>, printer: Printer, build_kind_message: &str, // Below is only used with PEP 517 builds build_dispatch: &BuildDispatch<'_>, sources: SourceStrategy, dist: Option<&SourceDist>, subdirectory: Option<&Path>, version_id: Option<&str>, build_output: BuildOutput, ) -> Result<BuildMessage, Error> { let build_result = match action { BuildAction::List => { let source_tree_ = source_tree.to_path_buf(); let (filename, file_list) = tokio::task::spawn_blocking(move || { uv_build_backend::list_source_dist( &source_tree_, uv_version::version(), sources == SourceStrategy::Enabled, ) }) .await??; let raw_filename = filename.to_string(); BuildMessage::List { normalized_filename: DistFilename::SourceDistFilename(filename), raw_filename, source_tree: source_tree.to_path_buf(), file_list, } } BuildAction::DirectBuild => { writeln!( printer.stderr(), "{}", format!( "{}Building {} (uv build backend)...", source.message_prefix(), build_kind_message ) .bold() )?; let source_tree = source_tree.to_path_buf(); let output_dir_ = output_dir.to_path_buf(); let filename = tokio::task::spawn_blocking(move || { uv_build_backend::build_source_dist( &source_tree, &output_dir_, uv_version::version(), sources == SourceStrategy::Enabled, ) }) .await?? .to_string(); BuildMessage::Build { normalized_filename: DistFilename::SourceDistFilename( SourceDistFilename::parsed_normalized_filename(&filename) .map_err(Error::InvalidBuiltSourceDistFilename)?, ), raw_filename: filename, output_dir: output_dir.to_path_buf(), } } BuildAction::Pep517 => { writeln!( printer.stderr(), "{}", format!( "{}Building {}...", source.message_prefix(),
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/src/commands/self_update.rs
crates/uv/src/commands/self_update.rs
use std::fmt::Write; use anyhow::Result; use axoupdater::{AxoUpdater, AxoupdateError, UpdateRequest}; use owo_colors::OwoColorize; use tracing::debug; use uv_client::{BaseClientBuilder, WrappedReqwestError}; use uv_fs::Simplified; use crate::commands::ExitStatus; use crate::printer::Printer; /// Attempt to update the uv binary. pub(crate) async fn self_update( version: Option<String>, token: Option<String>, dry_run: bool, printer: Printer, client_builder: BaseClientBuilder<'_>, ) -> Result<ExitStatus> { if client_builder.is_offline() { writeln!( printer.stderr(), "{}", format_args!( "{}{} Self-update is not possible because network connectivity is disabled (i.e., with `--offline`)", "error".red().bold(), ":".bold() ) )?; return Ok(ExitStatus::Failure); } let mut updater = AxoUpdater::new_for("uv"); updater.disable_installer_output(); if let Some(ref token) = token { updater.set_github_token(token); } // Load the "install receipt" for the current binary. If the receipt is not found, then // uv was likely installed via a package manager. let Ok(updater) = updater.load_receipt() else { debug!("No receipt found; assuming uv was installed via a package manager"); writeln!( printer.stderr(), "{}", format_args!( concat!( "{}{} Self-update is only available for uv binaries installed via the standalone installation scripts.", "\n", "\n", "If you installed uv with pip, brew, or another package manager, update uv with `pip install --upgrade`, `brew upgrade`, or similar." ), "error".red().bold(), ":".bold() ) )?; return Ok(ExitStatus::Error); }; // If we know what our version is, ignore whatever the receipt thinks it is! // This makes us behave better if someone manually installs a random version of uv // in a way that doesn't update the receipt. if let Ok(version) = env!("CARGO_PKG_VERSION").parse() { // This is best-effort, it's fine if it fails (also it can't actually fail) let _ = updater.set_current_version(version); } // Ensure the receipt is for the current binary. If it's not, then the user likely has multiple // uv binaries installed, and the current binary was _not_ installed via the standalone // installation scripts. if !updater.check_receipt_is_for_this_executable()? { let current_exe = std::env::current_exe()?; let receipt_prefix = updater.install_prefix_root()?; writeln!( printer.stderr(), "{}", format_args!( concat!( "{}{} Self-update is only available for uv binaries installed via the standalone installation scripts.", "\n", "\n", "The current executable is at `{}` but the standalone installer was used to install uv to `{}`. Are multiple copies of uv installed?" ), "error".red().bold(), ":".bold(), current_exe.simplified_display().bold().cyan(), receipt_prefix.simplified_display().bold().cyan() ) )?; return Ok(ExitStatus::Error); } writeln!( printer.stderr(), "{}", format_args!( "{}{} Checking for updates...", "info".cyan().bold(), ":".bold() ) )?; let update_request = if let Some(version) = version { UpdateRequest::SpecificTag(version) } else { UpdateRequest::Latest }; updater.configure_version_specifier(update_request.clone()); if dry_run { // TODO(charlie): `updater.fetch_release` isn't public, so we can't say what the latest // version is. if updater.is_update_needed().await? { let version = match update_request { UpdateRequest::Latest | UpdateRequest::LatestMaybePrerelease => { "the latest version".to_string() } UpdateRequest::SpecificTag(version) | UpdateRequest::SpecificVersion(version) => { format!("v{version}") } }; writeln!( printer.stderr(), "Would update uv from {} to {}", format!("v{}", env!("CARGO_PKG_VERSION")).bold().white(), version.bold().white(), )?; } else { writeln!( printer.stderr(), "{}", format_args!( "You're on the latest version of uv ({})", format!("v{}", env!("CARGO_PKG_VERSION")).bold().white() ) )?; } return Ok(ExitStatus::Success); } // Run the updater. This involves a network request, since we need to determine the latest // available version of uv. match updater.run().await { Ok(Some(result)) => { let direction = if result .old_version .as_ref() .is_some_and(|old_version| *old_version > result.new_version) { "Downgraded" } else { "Upgraded" }; let version_information = if let Some(old_version) = result.old_version { format!( "from {} to {}", format!("v{old_version}").bold().cyan(), format!("v{}", result.new_version).bold().cyan(), ) } else { format!("to {}", format!("v{}", result.new_version).bold().cyan()) }; writeln!( printer.stderr(), "{}", format_args!( "{}{} {direction} uv {}! {}", "success".green().bold(), ":".bold(), version_information, format!( "https://github.com/astral-sh/uv/releases/tag/{}", result.new_version_tag ) .cyan() ) )?; } Ok(None) => { writeln!( printer.stderr(), "{}", format_args!( "{}{} You're on the latest version of uv ({})", "success".green().bold(), ":".bold(), format!("v{}", env!("CARGO_PKG_VERSION")).bold().cyan() ) )?; } Err(err) => { return if let AxoupdateError::Reqwest(err) = err { if err.status() == Some(http::StatusCode::FORBIDDEN) && token.is_none() { writeln!( printer.stderr(), "{}", format_args!( "{}{} GitHub API rate limit exceeded. Please provide a GitHub token via the {} option.", "error".red().bold(), ":".bold(), "`--token`".green().bold() ) )?; Ok(ExitStatus::Error) } else { Err(WrappedReqwestError::from(err).into()) } } else { Err(err.into()) }; } } Ok(ExitStatus::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/src/commands/mod.rs
crates/uv/src/commands/mod.rs
use std::borrow::Cow; use std::io::stdout; use std::path::{Path, PathBuf}; use std::time::Duration; use std::{fmt::Write, process::ExitCode}; use anstream::AutoStream; use anyhow::Context; use owo_colors::OwoColorize; use tracing::debug; pub(crate) use auth::dir::dir as auth_dir; pub(crate) use auth::helper::helper as auth_helper; pub(crate) use auth::login::login as auth_login; pub(crate) use auth::logout::logout as auth_logout; pub(crate) use auth::token::token as auth_token; pub(crate) use build_frontend::build_frontend; pub(crate) use cache_clean::cache_clean; pub(crate) use cache_dir::cache_dir; pub(crate) use cache_prune::cache_prune; pub(crate) use cache_size::cache_size; pub(crate) use help::help; pub(crate) use pip::check::pip_check; pub(crate) use pip::compile::pip_compile; pub(crate) use pip::freeze::pip_freeze; pub(crate) use pip::install::pip_install; pub(crate) use pip::list::pip_list; pub(crate) use pip::show::pip_show; pub(crate) use pip::sync::pip_sync; pub(crate) use pip::tree::pip_tree; pub(crate) use pip::uninstall::pip_uninstall; pub(crate) use project::add::add; pub(crate) use project::export::export; pub(crate) use project::format::format; pub(crate) use project::init::{InitKind, InitProjectKind, init}; pub(crate) use project::lock::lock; pub(crate) use project::remove::remove; pub(crate) use project::run::{RunCommand, run}; pub(crate) use project::sync::sync; pub(crate) use project::tree::tree; pub(crate) use project::version::{project_version, self_version}; pub(crate) use publish::publish; pub(crate) use python::dir::dir as python_dir; pub(crate) use python::find::find as python_find; pub(crate) use python::find::find_script as python_find_script; pub(crate) use python::install::install as python_install; pub(crate) use python::install::{PythonUpgrade, PythonUpgradeSource}; pub(crate) use python::list::list as python_list; pub(crate) use python::pin::pin as python_pin; pub(crate) use python::uninstall::uninstall as python_uninstall; pub(crate) use python::update_shell::update_shell as python_update_shell; #[cfg(feature = "self-update")] pub(crate) use self_update::self_update; pub(crate) use tool::dir::dir as tool_dir; pub(crate) use tool::install::install as tool_install; pub(crate) use tool::list::list as tool_list; pub(crate) use tool::run::ToolRunCommand; pub(crate) use tool::run::run as tool_run; pub(crate) use tool::uninstall::uninstall as tool_uninstall; pub(crate) use tool::update_shell::update_shell as tool_update_shell; pub(crate) use tool::upgrade::upgrade as tool_upgrade; use uv_cache::Cache; use uv_configuration::Concurrency; pub(crate) use uv_console::human_readable_bytes; use uv_fs::{CWD, Simplified}; use uv_installer::compile_tree; use uv_python::PythonEnvironment; use uv_scripts::Pep723Script; pub(crate) use venv::venv; pub(crate) use workspace::dir::dir; pub(crate) use workspace::list::list; pub(crate) use workspace::metadata::metadata; use crate::commands::pip::operations::ChangedDist; use crate::printer::Printer; mod auth; pub(crate) mod build_backend; mod build_frontend; mod cache_clean; mod cache_dir; mod cache_prune; mod cache_size; mod diagnostics; mod help; pub(crate) mod pip; mod project; mod publish; mod python; pub(crate) mod reporters; #[cfg(feature = "self-update")] mod self_update; mod tool; mod venv; mod workspace; #[derive(Copy, Clone)] pub(crate) enum ExitStatus { /// The command succeeded. Success, /// The command failed due to an error in the user input. Failure, /// The command failed with an unexpected error. Error, /// The command's exit status is propagated from an external command. External(u8), } impl From<ExitStatus> for ExitCode { fn from(status: ExitStatus) -> Self { match status { ExitStatus::Success => Self::from(0), ExitStatus::Failure => Self::from(1), ExitStatus::Error => Self::from(2), ExitStatus::External(code) => Self::from(code), } } } /// Format a duration as a human-readable string, Cargo-style. pub(super) fn elapsed(duration: Duration) -> String { let secs = duration.as_secs(); let ms = duration.subsec_millis(); if secs >= 60 { format!("{}m {:02}s", secs / 60, secs % 60) } else if secs > 0 { format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000) } else if ms > 0 { format!("{ms}ms") } else { format!("0.{:02}ms", duration.subsec_nanos() / 10_000) } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub(super) enum ChangeEventKind { /// The package was removed from the environment. Removed, /// The package was added to the environment. Added, /// The package was reinstalled without changing versions. Reinstalled, } #[derive(Debug)] pub(super) struct ChangeEvent<'a> { dist: &'a ChangedDist, kind: ChangeEventKind, } /// Compile all Python source files in site-packages to bytecode, to speed up the /// initial run of any subsequent executions. /// /// See the `--compile` option on `pip sync` and `pip install`. pub(super) async fn compile_bytecode( venv: &PythonEnvironment, concurrency: &Concurrency, cache: &Cache, printer: Printer, ) -> anyhow::Result<()> { let start = std::time::Instant::now(); let mut files = 0; for site_packages in venv.site_packages() { let site_packages = CWD.join(site_packages); if !site_packages.exists() { debug!( "Skipping non-existent site-packages directory: {}", site_packages.display() ); continue; } files += compile_tree( &site_packages, venv.python_executable(), concurrency, cache.root(), ) .await .with_context(|| { format!( "Failed to bytecode-compile Python file in: {}", site_packages.user_display() ) })?; } let s = if files == 1 { "" } else { "s" }; writeln!( printer.stderr(), "{}", format!( "Bytecode compiled {} {}", format!("{files} file{s}").bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; Ok(()) } /// A multicasting writer that writes to both the standard output and an output file, if present. #[allow(clippy::disallowed_types)] struct OutputWriter<'a> { stdout: Option<AutoStream<std::io::Stdout>>, output_file: Option<&'a Path>, buffer: Vec<u8>, } #[allow(clippy::disallowed_types)] impl<'a> OutputWriter<'a> { /// Create a new output writer. fn new(include_stdout: bool, output_file: Option<&'a Path>) -> Self { let stdout = include_stdout.then(|| AutoStream::<std::io::Stdout>::auto(stdout())); Self { stdout, output_file, buffer: Vec::new(), } } /// Commit the buffer to the output file. async fn commit(self) -> std::io::Result<()> { if let Some(output_file) = self.output_file { if let Some(parent_dir) = output_file.parent() { fs_err::create_dir_all(parent_dir)?; } // If the output file is an existing symlink, write to the destination instead. let output_file = fs_err::read_link(output_file) .map(Cow::Owned) .unwrap_or(Cow::Borrowed(output_file)); let stream = anstream::adapter::strip_bytes(&self.buffer).into_vec(); uv_fs::write_atomic(output_file, &stream).await?; } Ok(()) } } impl std::io::Write for OutputWriter<'_> { /// Write to both standard output and the output buffer, if present. fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { // Write to the buffer. if self.output_file.is_some() { self.buffer.write_all(buf)?; } // Write to standard output. if let Some(stdout) = &mut self.stdout { stdout.write_all(buf)?; } Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { if let Some(stdout) = &mut self.stdout { stdout.flush()?; } Ok(()) } } /// Given a list of names, return a conjunction of the names (e.g., "Alice, Bob, and Charlie"). pub(super) fn conjunction(names: Vec<String>) -> String { let mut names = names.into_iter(); let first = names.next(); let last = names.next_back(); match (first, last) { (Some(first), Some(last)) => { let mut result = first; let mut comma = false; for name in names { result.push_str(", "); result.push_str(&name); comma = true; } if comma { result.push_str(", and "); } else { result.push_str(" and "); } result.push_str(&last); result } (Some(first), None) => first, _ => String::new(), } } /// Capitalize the first letter of a string. pub(super) fn capitalize(s: &str) -> String { let mut chars = s.chars(); match chars.next() { None => String::new(), Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(), } } /// A Python file that may or may not include an existing PEP 723 script tag. #[derive(Debug)] #[allow(clippy::large_enum_variant)] pub(crate) enum ScriptPath { /// The Python file already includes a PEP 723 script tag. Script(Pep723Script), /// The Python file does not include a PEP 723 script tag. Path(PathBuf), }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/reporters.rs
crates/uv/src/commands/reporters.rs
use std::env; use std::fmt::Write; use std::ops::Deref; use std::sync::LazyLock; use std::sync::{Arc, Mutex}; use std::time::Duration; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use owo_colors::OwoColorize; use rustc_hash::FxHashMap; use crate::commands::human_readable_bytes; use crate::printer::Printer; use uv_cache::Removal; use uv_distribution_types::{ BuildableSource, CachedDist, DistributionMetadata, Name, SourceDist, VersionOrUrlRef, }; use uv_normalize::PackageName; use uv_pep440::Version; use uv_python::PythonInstallationKey; use uv_redacted::DisplaySafeUrl; use uv_static::EnvVars; /// Since downloads, fetches and builds run in parallel, their message output order is /// non-deterministic, so can't capture them in test output. static HAS_UV_TEST_NO_CLI_PROGRESS: LazyLock<bool> = LazyLock::new(|| env::var(EnvVars::UV_TEST_NO_CLI_PROGRESS).is_ok()); #[derive(Debug)] struct ProgressReporter { printer: Printer, root: ProgressBar, mode: ProgressMode, } #[derive(Debug)] enum ProgressMode { /// Reports top-level progress. Single, /// Reports progress of all concurrent download, build, and checkout processes. Multi { multi_progress: MultiProgress, state: Arc<Mutex<BarState>>, }, } #[derive(Debug)] enum ProgressBarKind { /// A progress bar with an increasing value, such as a download. Numeric { progress: ProgressBar, /// The download size in bytes, if known. size: Option<u64>, }, /// A progress spinner for a task, such as a build. Spinner { progress: ProgressBar }, } impl Deref for ProgressBarKind { type Target = ProgressBar; fn deref(&self) -> &Self::Target { match self { Self::Numeric { progress, .. } => progress, Self::Spinner { progress } => progress, } } } #[derive(Debug)] struct BarState { /// The number of bars that precede any download bars (i.e., build/checkout status). headers: usize, /// A list of download bar sizes, in descending order. sizes: Vec<u64>, /// A map of progress bars, by ID. bars: FxHashMap<usize, ProgressBarKind>, /// A monotonic counter for bar IDs. id: usize, /// The maximum length of all bar names encountered. max_len: usize, } impl Default for BarState { fn default() -> Self { Self { headers: 0, sizes: Vec::default(), bars: FxHashMap::default(), id: 0, // Avoid resizing the progress bar templates too often by starting with a padding // that's wider than most package names. max_len: 20, } } } impl BarState { /// Returns a unique ID for a new progress bar. fn id(&mut self) -> usize { self.id += 1; self.id } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Upload, Download, Extract, } impl Direction { fn as_str(&self) -> &str { match self { Self::Download => "Downloading", Self::Upload => "Uploading", Self::Extract => "Extracting", } } } impl From<uv_python::downloads::Direction> for Direction { fn from(dir: uv_python::downloads::Direction) -> Self { match dir { uv_python::downloads::Direction::Download => Self::Download, uv_python::downloads::Direction::Extract => Self::Extract, } } } impl ProgressReporter { fn new(root: ProgressBar, multi_progress: MultiProgress, printer: Printer) -> Self { let mode = if env::var(EnvVars::JPY_SESSION_NAME).is_ok() { // Disable concurrent progress bars when running inside a Jupyter notebook // because the Jupyter terminal does not support clearing previous lines. // See: https://github.com/astral-sh/uv/issues/3887. ProgressMode::Single } else { ProgressMode::Multi { state: Arc::default(), multi_progress, } }; Self { printer, root, mode, } } fn on_build_start(&self, source: &BuildableSource) -> usize { let ProgressMode::Multi { multi_progress, state, } = &self.mode else { return 0; }; let mut state = state.lock().unwrap(); let id = state.id(); let progress = multi_progress.insert_before( &self.root, ProgressBar::with_draw_target(None, self.printer.target()), ); progress.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); let message = format!( " {} {}", "Building".bold().cyan(), source.to_color_string() ); if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS { let _ = writeln!(self.printer.stderr(), "{message}"); } progress.set_message(message); state.headers += 1; state.bars.insert(id, ProgressBarKind::Spinner { progress }); id } fn on_build_complete(&self, source: &BuildableSource, id: usize) { let ProgressMode::Multi { state, multi_progress, } = &self.mode else { return; }; let progress = { let mut state = state.lock().unwrap(); state.headers -= 1; state.bars.remove(&id).unwrap() }; let message = format!( " {} {}", "Built".bold().green(), source.to_color_string() ); if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS { let _ = writeln!(self.printer.stderr(), "{message}"); } progress.finish_with_message(message); } fn on_request_start(&self, direction: Direction, name: String, size: Option<u64>) -> usize { let ProgressMode::Multi { multi_progress, state, } = &self.mode else { return 0; }; let mut state = state.lock().unwrap(); // Preserve ascending order. let position = size.map_or(0, |size| state.sizes.partition_point(|&len| len < size)); state.sizes.insert(position, size.unwrap_or(0)); state.max_len = std::cmp::max(state.max_len, name.len()); let max_len = state.max_len; for progress in state.bars.values_mut() { // Ignore spinners, such as for builds. if let ProgressBarKind::Numeric { progress, .. } = progress { let template = format!( "{{msg:{max_len}.dim}} {{bar:30.green/black.dim}} {{binary_bytes:>7}}/{{binary_total_bytes:7}}" ); progress.set_style( ProgressStyle::with_template(&template) .unwrap() .progress_chars("--"), ); progress.tick(); } } let progress = multi_progress.insert( // Make sure not to reorder the initial "Preparing..." bar, or any previous bars. position + 1 + state.headers, ProgressBar::with_draw_target(size, self.printer.target()), ); if let Some(size) = size { // We're using binary bytes to match `human_readable_bytes`. progress.set_style( ProgressStyle::with_template( &format!( "{{msg:{}.dim}} {{bar:30.green/black.dim}} {{binary_bytes:>7}}/{{binary_total_bytes:7}}", state.max_len ), ) .unwrap() .progress_chars("--"), ); // If the file is larger than 1MB, show a message to indicate that this may take // a while keeping the log concise. if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS && size > 1024 * 1024 { let (bytes, unit) = human_readable_bytes(size); let _ = writeln!( self.printer.stderr(), "{} {} {}", direction.as_str().bold().cyan(), name, format!("({bytes:.1}{unit})").dimmed() ); } progress.set_message(name); } else { progress.set_style(ProgressStyle::with_template("{wide_msg:.dim} ....").unwrap()); if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS { let _ = writeln!( self.printer.stderr(), "{} {}", direction.as_str().bold().cyan(), name ); } progress.set_message(name); progress.finish(); } let id = state.id(); state .bars .insert(id, ProgressBarKind::Numeric { progress, size }); id } fn on_request_progress(&self, id: usize, bytes: u64) { let ProgressMode::Multi { state, .. } = &self.mode else { return; }; // Avoid panics due to reads on failed requests. // https://github.com/astral-sh/uv/issues/17090 // TODO(konsti): Add a debug assert once https://github.com/seanmonstar/reqwest/issues/2884 // is fixed if let Some(bar) = state.lock().unwrap().bars.get(&id) { bar.inc(bytes); } } fn on_request_complete(&self, direction: Direction, id: usize) { let ProgressMode::Multi { state, multi_progress, } = &self.mode else { return; }; let mut state = state.lock().unwrap(); if let ProgressBarKind::Numeric { progress, size } = state.bars.remove(&id).unwrap() { if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS && size.is_none_or(|size| size > 1024 * 1024) { let _ = writeln!( self.printer.stderr(), " {} {}", match direction { Direction::Download => "Downloaded", Direction::Upload => "Uploaded", Direction::Extract => "Extracted", } .bold() .cyan(), progress.message() ); } progress.finish_and_clear(); } else { debug_assert!(false, "Request progress bars are numeric"); } } fn on_download_progress(&self, id: usize, bytes: u64) { self.on_request_progress(id, bytes); } fn on_download_complete(&self, id: usize) { self.on_request_complete(Direction::Download, id); } fn on_download_start(&self, name: String, size: Option<u64>) -> usize { self.on_request_start(Direction::Download, name, size) } fn on_upload_progress(&self, id: usize, bytes: u64) { self.on_request_progress(id, bytes); } fn on_upload_complete(&self, id: usize) { self.on_request_complete(Direction::Upload, id); } fn on_upload_start(&self, name: String, size: Option<u64>) -> usize { self.on_request_start(Direction::Upload, name, size) } fn on_checkout_start(&self, url: &DisplaySafeUrl, rev: &str) -> usize { let ProgressMode::Multi { multi_progress, state, } = &self.mode else { return 0; }; let mut state = state.lock().unwrap(); let id = state.id(); let progress = multi_progress.insert_before( &self.root, ProgressBar::with_draw_target(None, self.printer.target()), ); progress.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); let message = format!(" {} {} ({})", "Updating".bold().cyan(), url, rev.dimmed()); if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS { let _ = writeln!(self.printer.stderr(), "{message}"); } progress.set_message(message); progress.finish(); state.headers += 1; state.bars.insert(id, ProgressBarKind::Spinner { progress }); id } fn on_checkout_complete(&self, url: &DisplaySafeUrl, rev: &str, id: usize) { let ProgressMode::Multi { state, multi_progress, } = &self.mode else { return; }; let progress = { let mut state = state.lock().unwrap(); state.headers -= 1; state.bars.remove(&id).unwrap() }; let message = format!( " {} {} ({})", "Updated".bold().green(), url, rev.dimmed() ); if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS { let _ = writeln!(self.printer.stderr(), "{message}"); } progress.finish_with_message(message); } } #[derive(Debug)] pub(crate) struct PrepareReporter { reporter: ProgressReporter, } impl From<Printer> for PrepareReporter { fn from(printer: Printer) -> Self { let multi_progress = MultiProgress::with_draw_target(printer.target()); let root = multi_progress.add(ProgressBar::with_draw_target(None, printer.target())); root.enable_steady_tick(Duration::from_millis(200)); root.set_style( ProgressStyle::with_template("{spinner:.white} {msg:.dim} ({pos}/{len})") .unwrap() .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]), ); root.set_message("Preparing packages..."); let reporter = ProgressReporter::new(root, multi_progress, printer); Self { reporter } } } impl PrepareReporter { #[must_use] pub(crate) fn with_length(self, length: u64) -> Self { self.reporter.root.set_length(length); self } } impl uv_installer::PrepareReporter for PrepareReporter { fn on_progress(&self, _dist: &CachedDist) { self.reporter.root.inc(1); } fn on_complete(&self) { // Need an extra call to `set_message` here to fully clear avoid leaving ghost output // in Jupyter notebooks. self.reporter.root.set_message(""); self.reporter.root.finish_and_clear(); } 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_download_start(&self, name: &PackageName, size: Option<u64>) -> usize { self.reporter.on_download_start(name.to_string(), size) } fn on_download_progress(&self, id: usize, bytes: u64) { self.reporter.on_download_progress(id, bytes); } fn on_download_complete(&self, _name: &PackageName, id: usize) { self.reporter.on_download_complete(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, id: usize) { self.reporter.on_checkout_complete(url, rev, id); } } #[derive(Debug)] pub(crate) struct ResolverReporter { reporter: ProgressReporter, } impl ResolverReporter { #[must_use] pub(crate) fn with_length(self, length: u64) -> Self { self.reporter.root.set_length(length); self } } impl From<Printer> for ResolverReporter { fn from(printer: Printer) -> Self { let multi_progress = MultiProgress::with_draw_target(printer.target()); let root = multi_progress.add(ProgressBar::with_draw_target(None, printer.target())); root.enable_steady_tick(Duration::from_millis(200)); root.set_style( ProgressStyle::with_template("{spinner:.white} {wide_msg:.dim}") .unwrap() .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]), ); root.set_message("Resolving dependencies..."); let reporter = ProgressReporter::new(root, multi_progress, printer); Self { reporter } } } impl uv_resolver::ResolverReporter for ResolverReporter { fn on_progress(&self, name: &PackageName, version_or_url: &VersionOrUrlRef) { match version_or_url { VersionOrUrlRef::Version(version) => { self.reporter.root.set_message(format!("{name}=={version}")); } VersionOrUrlRef::Url(url) => { self.reporter.root.set_message(format!("{name} @ {url}")); } } } fn on_complete(&self) { self.reporter.root.set_message(""); self.reporter.root.finish_and_clear(); } 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, id: usize) { self.reporter.on_checkout_complete(url, rev, id); } fn on_download_start(&self, name: &PackageName, size: Option<u64>) -> usize { self.reporter.on_download_start(name.to_string(), size) } fn on_download_progress(&self, id: usize, bytes: u64) { self.reporter.on_download_progress(id, bytes); } fn on_download_complete(&self, _name: &PackageName, id: usize) { self.reporter.on_download_complete(id); } } impl uv_distribution::Reporter for ResolverReporter { 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_download_start(&self, name: &PackageName, size: Option<u64>) -> usize { self.reporter.on_download_start(name.to_string(), size) } fn on_download_progress(&self, id: usize, bytes: u64) { self.reporter.on_download_progress(id, bytes); } fn on_download_complete(&self, _name: &PackageName, id: usize) { self.reporter.on_download_complete(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, id: usize) { self.reporter.on_checkout_complete(url, rev, id); } } #[derive(Debug)] pub(crate) struct InstallReporter { progress: ProgressBar, } impl From<Printer> for InstallReporter { fn from(printer: Printer) -> Self { let progress = ProgressBar::with_draw_target(None, printer.target()); progress.set_style( ProgressStyle::with_template("{bar:20} [{pos}/{len}] {wide_msg:.dim}").unwrap(), ); progress.set_message("Installing wheels..."); Self { progress } } } impl InstallReporter { #[must_use] pub(crate) fn with_length(self, length: u64) -> Self { self.progress.set_length(length); self } } impl uv_installer::InstallReporter for InstallReporter { fn on_install_progress(&self, wheel: &CachedDist) { self.progress.set_message(format!("{wheel}")); self.progress.inc(1); } fn on_install_complete(&self) { self.progress.set_message(""); self.progress.finish_and_clear(); } } #[derive(Debug)] pub(crate) struct PythonDownloadReporter { reporter: ProgressReporter, } impl PythonDownloadReporter { /// Initialize a [`PythonDownloadReporter`] for a single Python download. pub(crate) fn single(printer: Printer) -> Self { Self::new(printer, None) } /// Initialize a [`PythonDownloadReporter`] for multiple Python downloads. pub(crate) fn new(printer: Printer, length: Option<u64>) -> Self { let multi_progress = MultiProgress::with_draw_target(printer.target()); let root = multi_progress.add(ProgressBar::with_draw_target(length, printer.target())); let reporter = ProgressReporter::new(root, multi_progress, printer); Self { reporter } } } impl uv_python::downloads::Reporter for PythonDownloadReporter { fn on_request_start( &self, direction: uv_python::downloads::Direction, name: &PythonInstallationKey, size: Option<u64>, ) -> usize { self.reporter .on_request_start(direction.into(), format!("{name} ({direction})"), size) } fn on_request_progress(&self, id: usize, inc: u64) { self.reporter.on_request_progress(id, inc); } fn on_request_complete(&self, direction: uv_python::downloads::Direction, id: usize) { self.reporter.on_request_complete(direction.into(), id); } } #[derive(Debug)] pub(crate) struct PublishReporter { reporter: ProgressReporter, } impl PublishReporter { /// Initialize a [`PublishReporter`] for a single upload. pub(crate) fn single(printer: Printer) -> Self { Self::new(printer, None) } /// Initialize a [`PublishReporter`] for multiple uploads. pub(crate) fn new(printer: Printer, length: Option<u64>) -> Self { let multi_progress = MultiProgress::with_draw_target(printer.target()); let root = multi_progress.add(ProgressBar::with_draw_target(length, printer.target())); let reporter = ProgressReporter::new(root, multi_progress, printer); Self { reporter } } } impl uv_publish::Reporter for PublishReporter { fn on_progress(&self, _name: &str, id: usize) { self.reporter.on_download_complete(id); } fn on_upload_start(&self, name: &str, size: Option<u64>) -> usize { self.reporter.on_upload_start(name.to_string(), size) } fn on_upload_progress(&self, id: usize, inc: u64) { self.reporter.on_upload_progress(id, inc); } fn on_upload_complete(&self, id: usize) { self.reporter.on_upload_complete(id); } } #[derive(Debug)] pub(crate) struct LatestVersionReporter { progress: ProgressBar, } impl From<Printer> for LatestVersionReporter { fn from(printer: Printer) -> Self { let progress = ProgressBar::with_draw_target(None, printer.target()); progress.set_style( ProgressStyle::with_template("{bar:20} [{pos}/{len}] {wide_msg:.dim}").unwrap(), ); progress.set_message("Fetching latest versions..."); Self { progress } } } impl LatestVersionReporter { #[must_use] pub(crate) fn with_length(self, length: u64) -> Self { self.progress.set_length(length); self } pub(crate) fn on_fetch_progress(&self) { self.progress.inc(1); } pub(crate) fn on_fetch_version(&self, name: &PackageName, version: &Version) { self.progress.set_message(format!("{name} v{version}")); self.progress.inc(1); } pub(crate) fn on_fetch_complete(&self) { self.progress.set_message(""); self.progress.finish_and_clear(); } } #[derive(Debug)] pub(crate) struct CleaningDirectoryReporter { bar: ProgressBar, } impl CleaningDirectoryReporter { /// Initialize a [`CleaningDirectoryReporter`] for cleaning the cache directory. pub(crate) fn new(printer: Printer, max: Option<usize>) -> Self { let bar = ProgressBar::with_draw_target(max.map(|m| m as u64), printer.target()); bar.set_style( ProgressStyle::with_template("{prefix} [{bar:20}] {percent}%") .unwrap() .progress_chars("=> "), ); bar.set_prefix(format!("{}", "Cleaning".bold().cyan())); Self { bar } } } impl uv_cache::CleanReporter for CleaningDirectoryReporter { fn on_clean(&self) { self.bar.inc(1); } fn on_complete(&self) { self.bar.finish_and_clear(); } } #[derive(Debug)] pub(crate) struct CleaningPackageReporter { bar: ProgressBar, } impl CleaningPackageReporter { /// Initialize a [`CleaningPackageReporter`] for cleaning packages from the cache. pub(crate) fn new(printer: Printer, max: Option<usize>) -> Self { let bar = ProgressBar::with_draw_target(max.map(|m| m as u64), printer.target()); bar.set_style( ProgressStyle::with_template("{prefix} [{bar:20}] {pos}/{len}{msg}") .unwrap() .progress_chars("=> "), ); bar.set_prefix(format!("{}", "Cleaning".bold().cyan())); Self { bar } } pub(crate) fn on_clean(&self, package: &str, removal: &Removal) { self.bar.inc(1); self.bar.set_message(format!( ": {}, {} files {} folders removed", package, removal.num_files, removal.num_dirs, )); } pub(crate) fn on_complete(&self) { self.bar.finish_and_clear(); } } /// Like [`std::fmt::Display`], but with colors. trait ColorDisplay { fn to_color_string(&self) -> String; } impl ColorDisplay for SourceDist { fn to_color_string(&self) -> String { let name = self.name(); let version_or_url = self.version_or_url(); format!("{}{}", name, version_or_url.to_string().dimmed()) } } impl ColorDisplay for BuildableSource<'_> { fn to_color_string(&self) -> String { match self { Self::Dist(dist) => dist.to_color_string(), Self::Url(url) => url.to_string(), } } } pub(crate) struct BinaryDownloadReporter { reporter: ProgressReporter, } impl BinaryDownloadReporter { /// Initialize a [`BinaryDownloadReporter`] for a single binary download. pub(crate) fn single(printer: Printer) -> Self { let multi_progress = MultiProgress::with_draw_target(printer.target()); let root = multi_progress.add(ProgressBar::with_draw_target(None, printer.target())); let reporter = ProgressReporter::new(root, multi_progress, printer); Self { reporter } } } impl uv_bin_install::Reporter for BinaryDownloadReporter { fn on_download_start(&self, name: &str, version: &Version, size: Option<u64>) -> usize { self.reporter .on_request_start(Direction::Download, format!("{name} v{version}"), size) } fn on_download_progress(&self, id: usize, inc: u64) { self.reporter.on_request_progress(id, inc); } fn on_download_complete(&self, id: usize) { self.reporter.on_request_complete(Direction::Download, id); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/python/uninstall.rs
crates/uv/src/commands/python/uninstall.rs
use std::collections::BTreeSet; use std::fmt::Write; use std::path::PathBuf; use anyhow::Result; use futures::StreamExt; use futures::stream::FuturesUnordered; use indexmap::IndexSet; use itertools::Itertools; use owo_colors::OwoColorize; use rustc_hash::{FxHashMap, FxHashSet}; use tracing::{debug, warn}; use uv_fs::Simplified; use uv_preview::Preview; use uv_python::downloads::PythonDownloadRequest; use uv_python::managed::{ ManagedPythonInstallations, PythonMinorVersionLink, python_executable_dir, }; use uv_python::{PythonInstallationKey, PythonInstallationMinorVersionKey, PythonRequest}; use crate::commands::python::install::format_executables; use crate::commands::python::{ChangeEvent, ChangeEventKind}; use crate::commands::{ExitStatus, elapsed}; use crate::printer::Printer; /// Uninstall managed Python versions. pub(crate) async fn uninstall( install_dir: Option<PathBuf>, targets: Vec<String>, all: bool, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let installations = ManagedPythonInstallations::from_settings(install_dir)?.init()?; let _lock = installations.lock().await?; // Perform the uninstallation. do_uninstall(&installations, targets, all, printer, preview).await?; // Clean up any empty directories. if uv_fs::directories(installations.root())?.all(|path| uv_fs::is_temporary(&path)) { fs_err::tokio::remove_dir_all(&installations.root()).await?; if let Some(top_level) = installations.root().parent() { // Remove the `toolchains` symlink. match fs_err::tokio::remove_file(top_level.join("toolchains")).await { Ok(()) => {} Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } if uv_fs::directories(top_level)?.all(|path| uv_fs::is_temporary(&path)) { fs_err::tokio::remove_dir_all(top_level).await?; } } } Ok(ExitStatus::Success) } /// Perform the uninstallation of managed Python installations. async fn do_uninstall( installations: &ManagedPythonInstallations, targets: Vec<String>, all: bool, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let start = std::time::Instant::now(); let requests = if all { vec![PythonRequest::Default] } else { let targets = targets.into_iter().collect::<BTreeSet<_>>(); targets .iter() .map(|target| PythonRequest::parse(target.as_str())) .collect::<Vec<_>>() }; let download_requests = requests .iter() .map(|request| { PythonDownloadRequest::from_request(request).ok_or_else(|| { anyhow::anyhow!("Cannot uninstall managed Python for request: {request}") }) }) // Always include pre-releases in uninstalls .map(|result| result.map(|request| request.with_prereleases(true))) .collect::<Result<Vec<_>>>()?; let installed_installations: Vec<_> = installations.find_all()?.collect(); let mut matching_installations = BTreeSet::default(); for (request, download_request) in requests.iter().zip(download_requests) { if matches!(requests.as_slice(), [PythonRequest::Default]) { writeln!(printer.stderr(), "Searching for Python installations")?; } else { writeln!( printer.stderr(), "Searching for Python versions matching: {}", request.cyan() )?; } let mut found = false; for installation in installed_installations .iter() .filter(|installation| download_request.satisfied_by_key(installation.key())) { found = true; matching_installations.insert(installation.clone()); } if !found { // Clear any remnants in the registry #[cfg(windows)] { uv_python::windows_registry::remove_orphan_registry_entries( &installed_installations, ); } if matches!(requests.as_slice(), [PythonRequest::Default]) { writeln!(printer.stderr(), "No Python installations found")?; return Ok(ExitStatus::Failure); } writeln!( printer.stderr(), "No existing installations found for: {}", request.cyan() )?; } } if matching_installations.is_empty() { writeln!( printer.stderr(), "No Python installations found matching the requests" )?; return Ok(ExitStatus::Failure); } // Remove registry entries first, so we don't have dangling entries between the file removal // and the registry removal. let mut errors = vec![]; #[cfg(windows)] { uv_python::windows_registry::remove_registry_entry( &matching_installations, all, &mut errors, ); uv_python::windows_registry::remove_orphan_registry_entries(&installed_installations); } // Find and remove all relevant Python executables let mut uninstalled_executables: FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>> = FxHashMap::default(); for executable in python_executable_dir()? .read_dir() .into_iter() .flatten() .filter_map(|entry| match entry { Ok(entry) => Some(entry), Err(err) => { warn!("Failed to read executable: {}", err); None } }) .filter(|entry| entry.file_type().is_ok_and(|file_type| !file_type.is_dir())) .map(|entry| entry.path()) // Only include files that match the expected Python executable names // TODO(zanieb): This is a minor optimization to avoid opening more files, but we could // leave broken links behind, i.e., if the user created them. .filter(|path| { matching_installations.iter().any(|installation| { let name = path.file_name().and_then(|name| name.to_str()); name == Some(&installation.key().executable_name_minor()) || name == Some(&installation.key().executable_name_major()) || name == Some(&installation.key().executable_name()) }) }) .sorted() { let Some(installation) = matching_installations .iter() .find(|installation| installation.is_bin_link(executable.as_path())) else { continue; }; fs_err::remove_file(&executable)?; debug!( "Removed `{}` for `{}`", executable.simplified_display(), installation.key() ); uninstalled_executables .entry(installation.key().clone()) .or_default() .insert(executable); } let mut tasks = FuturesUnordered::new(); for installation in &matching_installations { tasks.push(async { ( installation.key(), fs_err::tokio::remove_dir_all(installation.path()).await, ) }); } let mut uninstalled = IndexSet::<PythonInstallationKey>::default(); while let Some((key, result)) = tasks.next().await { if let Err(err) = result { errors.push((key.clone(), anyhow::Error::new(err))); } else { uninstalled.insert(key.clone()); } } // Read all existing managed installations and find the highest installed patch // for each installed minor version. Ensure the minor version link directory // is still valid. let uninstalled_minor_versions: IndexSet<_> = uninstalled .iter() .map(PythonInstallationMinorVersionKey::ref_cast) .collect(); let remaining_installations: Vec<_> = installed_installations .into_iter() .filter(|installation| !uninstalled.contains(installation.key())) .collect(); let remaining_minor_versions = PythonInstallationMinorVersionKey::highest_installations_by_minor_version_key( remaining_installations.iter(), ); for (_, installation) in remaining_minor_versions .iter() .filter(|(minor_version, _)| uninstalled_minor_versions.contains(minor_version)) { installation.update_minor_version_link(preview)?; } // For each uninstalled installation, check if there are no remaining installations // for its minor version. If there are none remaining, remove the symlink directory // (or junction on Windows) if it exists. for installation in &matching_installations { if !remaining_minor_versions.contains_key(installation.minor_version_key()) { if let Some(minor_version_link) = PythonMinorVersionLink::from_installation(installation, preview) { if minor_version_link.exists() { let result = if cfg!(windows) { fs_err::remove_dir(minor_version_link.symlink_directory.as_path()) } else { fs_err::remove_file(minor_version_link.symlink_directory.as_path()) }; if result.is_err() { return Err(anyhow::anyhow!( "Failed to remove symlink directory {}", minor_version_link.symlink_directory.display() )); } let symlink_term = if cfg!(windows) { "junction" } else { "symlink directory" }; debug!( "Removed {}: {}", symlink_term, minor_version_link.symlink_directory.to_string_lossy() ); } } } } // Report on any uninstalled installations. if let Some(first_uninstalled) = uninstalled.first() { if uninstalled.len() == 1 { // Ex) "Uninstalled Python 3.9.7 in 1.68s" writeln!( printer.stderr(), "{}", format!( "Uninstalled {} {}", format!("Python {}", first_uninstalled.version()).bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; } else { // Ex) "Uninstalled 2 versions in 1.68s" writeln!( printer.stderr(), "{}", format!( "Uninstalled {} {}", format!("{} versions", uninstalled.len()).bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; } for event in uninstalled .into_iter() .map(|key| ChangeEvent { key, kind: ChangeEventKind::Removed, }) .sorted_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.kind.cmp(&b.kind))) { let executables = format_executables(&event, &uninstalled_executables); match event.kind { ChangeEventKind::Removed => { writeln!( printer.stderr(), " {} {}{}", "-".red(), event.key.bold(), executables, )?; } _ => unreachable!(), } } } if !errors.is_empty() { for (key, err) in errors { writeln!( printer.stderr(), "Failed to uninstall {}: {}", key.green(), err.to_string().trim() )?; } return Ok(ExitStatus::Failure); } Ok(ExitStatus::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/src/commands/python/list.rs
crates/uv/src/commands/python/list.rs
use serde::Serialize; use std::collections::BTreeSet; use std::fmt::Write; use uv_cli::PythonListFormat; use uv_pep440::Version; use uv_preview::Preview; use anyhow::Result; use itertools::Either; use owo_colors::OwoColorize; use rustc_hash::FxHashSet; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_fs::Simplified; use uv_python::downloads::{ManagedPythonDownloadList, PythonDownloadRequest}; use uv_python::{ DiscoveryError, EnvironmentPreference, PythonDownloads, PythonInstallation, PythonNotFound, PythonPreference, PythonRequest, PythonSource, find_python_installations, }; use crate::commands::ExitStatus; use crate::printer::Printer; use crate::settings::PythonListKinds; #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)] enum Kind { Download, Managed, System, } #[derive(Debug, Serialize)] struct NamedVersionParts { major: u64, minor: u64, patch: u64, } #[derive(Debug, Serialize)] struct PrintData { key: String, version: Version, version_parts: NamedVersionParts, path: Option<String>, symlink: Option<String>, url: Option<String>, os: String, variant: String, implementation: String, arch: String, libc: String, } /// List available Python installations. #[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)] pub(crate) async fn list( request: Option<String>, kinds: PythonListKinds, all_versions: bool, all_platforms: bool, all_arches: bool, show_urls: bool, output_format: PythonListFormat, python_downloads_json_url: Option<String>, python_install_mirror: Option<String>, pypy_install_mirror: Option<String>, python_preference: PythonPreference, python_downloads: PythonDownloads, client_builder: &BaseClientBuilder<'_>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let request = request.as_deref().map(PythonRequest::parse); let base_download_request = if python_preference == PythonPreference::OnlySystem { None } else { // If the user request cannot be mapped to a download request, we won't show any downloads PythonDownloadRequest::from_request(request.as_ref().unwrap_or(&PythonRequest::Any)) }; let client = client_builder.build(); let download_list = ManagedPythonDownloadList::new(&client, python_downloads_json_url.as_deref()).await?; let mut output = BTreeSet::new(); if let Some(base_download_request) = base_download_request { let download_request = match kinds { PythonListKinds::Installed => None, PythonListKinds::Downloads => Some(if all_platforms { base_download_request } else if all_arches { base_download_request.fill_platform()?.with_any_arch() } else { base_download_request.fill_platform()? }), PythonListKinds::Default => { if python_downloads.is_automatic() { Some(if all_platforms { base_download_request } else if all_arches { base_download_request.fill_platform()?.with_any_arch() } else { base_download_request.fill_platform()? }) } else { // If fetching is not automatic, then don't show downloads as available by default None } } } // Include pre-release versions .map(|request| request.with_prereleases(true)); let downloads = download_request .as_ref() .map(|request| download_list.iter_matching(request)) .into_iter() .flatten() // TODO(zanieb): Add a way to show debug downloads, we just hide them for now .filter(|download| !download.key().variant().is_debug()); for download in downloads { output.insert(( download.key().clone(), Kind::Download, Either::Right(download.download_url( python_install_mirror.as_deref(), pypy_install_mirror.as_deref(), )?), )); } } let installed = match kinds { PythonListKinds::Installed | PythonListKinds::Default => { Some(find_python_installations( request.as_ref().unwrap_or(&PythonRequest::Any), EnvironmentPreference::OnlySystem, python_preference, cache, preview, ) // Raise discovery errors if critical .filter(|result| { result .as_ref() .err() .is_none_or(DiscoveryError::is_critical) }) .collect::<Result<Vec<Result<PythonInstallation, PythonNotFound>>, DiscoveryError>>()? .into_iter() // Drop any "missing" installations .filter_map(Result::ok)) } PythonListKinds::Downloads => None, }; if let Some(installed) = installed { for installation in installed { let kind = if matches!(installation.source(), PythonSource::Managed) { Kind::Managed } else { Kind::System }; output.insert(( installation.key(), kind, Either::Left(installation.interpreter().real_executable().to_path_buf()), )); } } let mut seen_minor = FxHashSet::default(); let mut seen_patch = FxHashSet::default(); let mut seen_paths = FxHashSet::default(); let mut include = Vec::new(); for (key, kind, uri) in output.iter().rev() { // Do not show the same path more than once if let Either::Left(path) = uri { if !seen_paths.insert(path) { continue; } } // Only show the latest patch version for each download unless all were requested. // // We toggle off platforms/arches based unless all_platforms/all_arches because // we want to only show the "best" option for each version by default, even // if e.g. the x86_32 build would also work on x86_64. if !matches!(kind, Kind::System) { if let [major, minor, ..] = *key.version().release() { if !seen_minor.insert(( all_platforms.then_some(*key.os()), major, minor, key.variant(), key.implementation(), all_arches.then_some(*key.arch()), *key.libc(), )) { if matches!(kind, Kind::Download) && !all_versions { continue; } } } if let [major, minor, patch] = *key.version().release() { if !seen_patch.insert(( all_platforms.then_some(*key.os()), major, minor, patch, key.variant(), key.implementation(), all_arches.then_some(*key.arch()), key.libc(), )) { if matches!(kind, Kind::Download) { continue; } } } } include.push((key, uri)); } match output_format { PythonListFormat::Json => { let data = include .iter() .map(|(key, uri)| -> Result<_> { let mut path_or_none: Option<String> = None; let mut symlink_or_none: Option<String> = None; let mut url_or_none: Option<String> = None; match uri { Either::Left(path) => { path_or_none = Some(path.user_display().to_string()); let is_symlink = fs_err::symlink_metadata(path)?.is_symlink(); if is_symlink { symlink_or_none = Some(path.read_link()?.user_display().to_string()); } } Either::Right(url) => { url_or_none = Some((*url).to_string()); } } let version = key.version(); let release = version.release(); Ok(PrintData { key: key.to_string(), version: version.version().clone(), #[allow(clippy::get_first)] version_parts: NamedVersionParts { major: release.get(0).copied().unwrap_or(0), minor: release.get(1).copied().unwrap_or(0), patch: release.get(2).copied().unwrap_or(0), }, path: path_or_none, symlink: symlink_or_none, url: url_or_none, arch: key.arch().to_string(), implementation: key.implementation().to_string(), os: key.os().to_string(), variant: key.variant().to_string(), libc: key.libc().to_string(), }) }) .collect::<Result<Vec<_>>>()?; writeln!(printer.stdout(), "{}", serde_json::to_string(&data)?)?; } PythonListFormat::Text => { // Compute the width of the first column. let width = include .iter() .fold(0usize, |acc, (key, _)| acc.max(key.to_string().len())); for (key, uri) in include { let key = key.to_string(); match uri { Either::Left(path) => { let is_symlink = fs_err::symlink_metadata(path)?.is_symlink(); if is_symlink { writeln!( printer.stdout(), "{key:width$} {} -> {}", path.user_display().cyan(), path.read_link()?.user_display().cyan() )?; } else { writeln!( printer.stdout(), "{key:width$} {}", path.user_display().cyan() )?; } } Either::Right(url) => { if show_urls { writeln!(printer.stdout(), "{key:width$} {}", url.dimmed())?; } else { writeln!( printer.stdout(), "{key:width$} {}", "<download available>".dimmed() )?; } } } } } } Ok(ExitStatus::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/src/commands/python/find.rs
crates/uv/src/commands/python/find.rs
use anyhow::Result; use std::fmt::Write; use std::path::Path; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::DependencyGroupsWithDefaults; use uv_fs::Simplified; use uv_preview::Preview; use uv_python::downloads::ManagedPythonDownloadList; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest, }; use uv_scripts::Pep723ItemRef; use uv_settings::PythonInstallMirrors; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache, WorkspaceError}; use crate::commands::{ ExitStatus, project::{ScriptInterpreter, WorkspacePython, validate_project_requires_python}, }; use crate::printer::Printer; /// Find a Python interpreter. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn find( project_dir: &Path, request: Option<String>, show_version: bool, no_project: bool, no_config: bool, system: bool, python_preference: PythonPreference, python_downloads_json_url: Option<&str>, client_builder: &BaseClientBuilder<'_>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let environment_preference = if system { EnvironmentPreference::OnlySystem } else { EnvironmentPreference::Any }; let workspace_cache = WorkspaceCache::default(); let project = if no_project { None } else { match VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await { Ok(project) => Some(project), Err(WorkspaceError::MissingProject(_)) => None, Err(WorkspaceError::MissingPyprojectToml) => None, Err(WorkspaceError::NonWorkspace(_)) => None, Err(err) => { warn_user_once!("{err}"); None } } }; // Don't enable the requires-python settings on groups let groups = DependencyGroupsWithDefaults::none(); let WorkspacePython { source, python_request, requires_python, } = WorkspacePython::from_request( request.map(|request| PythonRequest::parse(&request)), project.as_ref().map(VirtualProject::workspace), &groups, project_dir, no_config, ) .await?; let client = client_builder.clone().retries(0).build(); let download_list = ManagedPythonDownloadList::new(&client, python_downloads_json_url).await?; let python = PythonInstallation::find( &python_request.unwrap_or_default(), environment_preference, python_preference, &download_list, cache, preview, )?; // Warn if the discovered Python version is incompatible with the current workspace if let Some(requires_python) = requires_python { match validate_project_requires_python( python.interpreter(), project.as_ref().map(VirtualProject::workspace), &groups, &requires_python, &source, ) { Ok(()) => {} Err(err) => { warn_user!("{err}"); } } } if show_version { writeln!( printer.stdout(), "{}", python.interpreter().python_version() )?; } else { writeln!( printer.stdout(), "{}", std::path::absolute(python.interpreter().sys_executable())?.simplified_display() )?; } Ok(ExitStatus::Success) } pub(crate) async fn find_script( script: Pep723ItemRef<'_>, show_version: bool, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let interpreter = match ScriptInterpreter::discover( script, None, client_builder, python_preference, python_downloads, &PythonInstallMirrors::default(), false, no_config, Some(false), cache, printer, preview, ) .await { Err(error) => { writeln!(printer.stderr(), "{error}")?; return Ok(ExitStatus::Failure); } Ok(ScriptInterpreter::Interpreter(interpreter)) => interpreter, Ok(ScriptInterpreter::Environment(environment)) => environment.into_interpreter(), }; if show_version { writeln!(printer.stdout(), "{}", interpreter.python_version())?; } else { writeln!( printer.stdout(), "{}", std::path::absolute(interpreter.sys_executable())?.simplified_display() )?; } Ok(ExitStatus::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/src/commands/python/install.rs
crates/uv/src/commands/python/install.rs
use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt::Write; use std::io::ErrorKind; use std::path::{Path, PathBuf}; use std::str::FromStr; use anyhow::{Error, Result}; use futures::StreamExt; use futures::stream::FuturesUnordered; use indexmap::IndexSet; use itertools::{Either, Itertools}; use owo_colors::{AnsiColors, OwoColorize}; use rustc_hash::{FxHashMap, FxHashSet}; use tracing::{debug, trace}; use uv_client::BaseClientBuilder; use uv_fs::Simplified; use uv_platform::{Arch, Libc}; use uv_preview::{Preview, PreviewFeatures}; use uv_python::downloads::{ self, ArchRequest, DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList, PythonDownloadRequest, }; use uv_python::managed::{ ManagedPythonInstallation, ManagedPythonInstallations, PythonMinorVersionLink, create_link_to_executable, python_executable_dir, }; use uv_python::{ PythonDownloads, PythonInstallationKey, PythonInstallationMinorVersionKey, PythonRequest, PythonVersionFile, VersionFileDiscoveryOptions, VersionFilePreference, VersionRequest, }; use uv_shell::Shell; use uv_trampoline_builder::{Launcher, LauncherKind}; use uv_warnings::{warn_user, write_error_chain}; use crate::commands::python::{ChangeEvent, ChangeEventKind}; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::{ExitStatus, elapsed}; use crate::printer::Printer; #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct InstallRequest<'a> { /// The original request from the user request: PythonRequest, /// A download request corresponding to the `request` with platform information filled download_request: PythonDownloadRequest, /// A download that satisfies the request download: &'a ManagedPythonDownload, } impl<'a> InstallRequest<'a> { fn new(request: PythonRequest, download_list: &'a ManagedPythonDownloadList) -> Result<Self> { // Make sure the request is a valid download request and fill platform information let download_request = PythonDownloadRequest::from_request(&request) .ok_or_else(|| { anyhow::anyhow!( "`{}` is not a valid Python download request; see `uv help python` for supported formats and `uv python list --only-downloads` for available versions", request.to_canonical_string() ) })? .fill()?; // Find a matching download let download = match download_list.find(&download_request) { Ok(download) => download, Err(downloads::Error::NoDownloadFound(request)) if request.libc().is_some_and(Libc::is_musl) && request .arch() .is_some_and(|arch| Arch::is_arm(&arch.inner())) => { return Err(anyhow::anyhow!( "uv does not yet provide musl Python distributions on aarch64." )); } Err(err) => return Err(err.into()), }; Ok(Self { request, download_request, download, }) } fn matches_installation(&self, installation: &ManagedPythonInstallation) -> bool { self.download_request.satisfied_by_key(installation.key()) } fn python_request(&self) -> &PythonRequest { &self.request } } impl std::fmt::Display for InstallRequest<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let request = self.request.to_canonical_string(); let download = self.download_request.to_string(); if request != download { write!(f, "{request} ({download})") } else { write!(f, "{request}") } } } #[derive(Debug, Default)] struct Changelog { existing: FxHashSet<PythonInstallationKey>, installed: FxHashSet<PythonInstallationKey>, uninstalled: FxHashSet<PythonInstallationKey>, installed_executables: FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>>, } impl Changelog { fn events(&self) -> impl Iterator<Item = ChangeEvent> { let reinstalled = self .uninstalled .intersection(&self.installed) .cloned() .collect::<FxHashSet<_>>(); let uninstalled = self.uninstalled.difference(&reinstalled).cloned(); let installed = self.installed.difference(&reinstalled).cloned(); uninstalled .map(|key| ChangeEvent { key: key.clone(), kind: ChangeEventKind::Removed, }) .chain(installed.map(|key| ChangeEvent { key: key.clone(), kind: ChangeEventKind::Added, })) .chain(reinstalled.iter().map(|key| ChangeEvent { key: key.clone(), kind: ChangeEventKind::Reinstalled, })) .sorted_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.kind.cmp(&b.kind))) } } #[derive(Debug, Clone, Copy)] enum InstallErrorKind { DownloadUnpack, Bin, #[cfg_attr(not(windows), allow(dead_code))] Registry, } #[derive(Debug, Clone, Copy)] pub(crate) enum PythonUpgradeSource { /// The user invoked `uv python install --upgrade` Install, /// The user invoked `uv python upgrade` Upgrade, } impl std::fmt::Display for PythonUpgradeSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Install => write!(f, "uv python install --upgrade"), Self::Upgrade => write!(f, "uv python upgrade"), } } } #[derive(Debug, Clone, Copy)] pub(crate) enum PythonUpgrade { /// Python upgrades are enabled. Enabled(PythonUpgradeSource), /// Python upgrades are disabled. Disabled, } /// Download and install Python versions. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn install( project_dir: &Path, install_dir: Option<PathBuf>, targets: Vec<String>, reinstall: bool, upgrade: PythonUpgrade, bin: Option<bool>, registry: Option<bool>, force: bool, python_install_mirror: Option<String>, pypy_install_mirror: Option<String>, python_downloads_json_url: Option<String>, client_builder: BaseClientBuilder<'_>, default: bool, python_downloads: PythonDownloads, no_config: bool, preview: Preview, printer: Printer, ) -> Result<ExitStatus> { let start = std::time::Instant::now(); // TODO(zanieb): We should consider marking the Python installation as the default when // `--default` is used. It's not clear how this overlaps with a global Python pin, but I'd be // surprised if `uv python find` returned the "newest" Python version rather than the one I just // installed with the `--default` flag. if default && !preview.is_enabled(PreviewFeatures::PYTHON_INSTALL_DEFAULT) { warn_user!( "The `--default` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning", PreviewFeatures::PYTHON_INSTALL_DEFAULT ); } if let PythonUpgrade::Enabled(source @ PythonUpgradeSource::Upgrade) = upgrade { if !preview.is_enabled(PreviewFeatures::PYTHON_UPGRADE) { warn_user!( "`{source}` is experimental and may change without warning. Pass `--preview-features {}` to disable this warning", PreviewFeatures::PYTHON_UPGRADE ); } } if default && targets.len() > 1 { anyhow::bail!("The `--default` flag cannot be used with multiple targets"); } // Read the existing installations, lock the directory for the duration let installations = ManagedPythonInstallations::from_settings(install_dir.clone())?.init()?; let installations_dir = installations.root(); let scratch_dir = installations.scratch(); let _lock = installations.lock().await?; let existing_installations: Vec<_> = installations .find_all()? .inspect(|installation| trace!("Found existing installation {}", installation.key())) .collect(); // Resolve the requests let mut is_default_install = false; let mut is_unspecified_upgrade = false; let retry_policy = client_builder.retry_policy(); // Python downloads are performing their own retries to catch stream errors, disable the // default retries to avoid the middleware from performing uncontrolled retries. let client = client_builder.retries(0).build(); let download_list = ManagedPythonDownloadList::new(&client, python_downloads_json_url.as_deref()).await?; // TODO(zanieb): We use this variable to special-case .python-version files, but it'd be nice to // have generalized request source tracking instead let mut is_from_python_version_file = false; let requests: Vec<_> = if targets.is_empty() { if matches!( upgrade, PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) ) { is_unspecified_upgrade = true; // On upgrade, derive requests for all of the existing installations let mut minor_version_requests = IndexSet::<InstallRequest>::default(); for installation in &existing_installations { let mut request = PythonDownloadRequest::from(installation); // We should always have a version in the request from an existing installation let version = request.take_version().unwrap(); // Drop the patch and prerelease parts from the request request = request.with_version(version.only_minor()); let install_request = InstallRequest::new(PythonRequest::Key(request), &download_list)?; minor_version_requests.insert(install_request); } minor_version_requests.into_iter().collect::<Vec<_>>() } else { PythonVersionFile::discover( project_dir, &VersionFileDiscoveryOptions::default() .with_no_config(no_config) .with_preference(VersionFilePreference::Versions), ) .await? .inspect(|file| { debug!( "Found Python version file at: {}", file.path().user_display() ); }) .map(PythonVersionFile::into_versions) .inspect(|_| is_from_python_version_file = true) .unwrap_or_else(|| { // If no version file is found and no requests were made // TODO(zanieb): We should consider differentiating between a global Python version // file here, allowing a request from there to enable `is_default_install`. is_default_install = true; vec![if reinstall { // On bare `--reinstall`, reinstall all Python versions PythonRequest::Any } else { PythonRequest::Default }] }) .into_iter() .map(|request| InstallRequest::new(request, &download_list)) .collect::<Result<Vec<_>>>()? } } else { targets .iter() .map(|target| PythonRequest::parse(target.as_str())) .map(|request| InstallRequest::new(request, &download_list)) .collect::<Result<Vec<_>>>()? }; if requests.is_empty() { match upgrade { PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) => { writeln!( printer.stderr(), "There are no installed versions to upgrade" )?; } PythonUpgrade::Enabled(PythonUpgradeSource::Install) => { writeln!( printer.stderr(), "No Python versions specified for upgrade; did you mean `uv python upgrade`?" )?; } PythonUpgrade::Disabled => {} } return Ok(ExitStatus::Success); } let requested_minor_versions = requests .iter() .filter_map(|request| { if let PythonRequest::Version(VersionRequest::MajorMinor(major, minor, ..)) = request.python_request() { uv_pep440::Version::from_str(&format!("{major}.{minor}")).ok() } else { None } }) .collect::<IndexSet<_>>(); if let PythonUpgrade::Enabled(source) = upgrade { if let Some(request) = requests.iter().find(|request| { request.request.includes_patch() || request.request.includes_prerelease() }) { writeln!( printer.stderr(), "error: `{source}` only accepts minor versions, got: {}", request.request.to_canonical_string() )?; if is_from_python_version_file { writeln!( printer.stderr(), "\n{}{} The version request came from a `.python-version` file; change the patch version in the file to upgrade instead", "hint".bold().cyan(), ":".bold(), )?; } return Ok(ExitStatus::Failure); } } // Find requests that are already satisfied let mut changelog = Changelog::default(); let (satisfied, unsatisfied): (Vec<_>, Vec<_>) = if reinstall { // In the reinstall case, we want to iterate over all matching installations instead of // stopping at the first match. let mut unsatisfied: Vec<Cow<InstallRequest>> = Vec::with_capacity(existing_installations.len() + requests.len()); for request in &requests { let mut matching_installations = existing_installations .iter() .filter(|installation| request.matches_installation(installation)) .peekable(); if matching_installations.peek().is_none() { debug!("No installation found for request `{}`", request); unsatisfied.push(Cow::Borrowed(request)); } for installation in matching_installations { changelog.existing.insert(installation.key().clone()); if matches!(&request.request, &PythonRequest::Any) { // Construct an install request matching the existing installation match InstallRequest::new( PythonRequest::Key(installation.into()), &download_list, ) { Ok(request) => { debug!("Will reinstall `{}`", installation.key()); unsatisfied.push(Cow::Owned(request)); } Err(err) => { // This shouldn't really happen, but maybe a new version of uv dropped // support for a key we previously supported warn_user!( "Failed to create reinstall request for existing installation `{}`: {err}", installation.key().green() ); } } } else { // TODO(zanieb): This isn't really right! But we need `--upgrade` or similar // to handle this case correctly without causing a breaking change. // If we have real requests, just ignore the existing installation debug!( "Ignoring match `{}` for request `{}` due to `--reinstall` flag", installation.key(), request ); unsatisfied.push(Cow::Borrowed(request)); break; } } } (vec![], unsatisfied) } else { // If we can find one existing installation that matches the request, it is satisfied requests.iter().partition_map(|request| { if let Some(installation) = existing_installations.iter().find(|installation| { if matches!(upgrade, PythonUpgrade::Enabled(_)) { // If this is an upgrade, the requested version is a minor version but the // requested download is the highest patch for that minor version. We need to // install it unless an exact match is found. request.download.key() == installation.key() } else { request.matches_installation(installation) } }) { debug!("Found `{}` for request `{}`", installation.key(), request); Either::Left(installation) } else { debug!("No installation found for request `{}`", request); Either::Right(Cow::Borrowed(request)) } }) }; // Check if Python downloads are banned if matches!(python_downloads, PythonDownloads::Never) && !unsatisfied.is_empty() { writeln!( printer.stderr(), "Python downloads are not allowed (`python-downloads = \"never\"`). Change to `python-downloads = \"manual\"` to allow explicit installs.", )?; return Ok(ExitStatus::Failure); } // Find downloads for the requests let downloads = unsatisfied .iter() .inspect(|request| { debug!( "Found download `{}` for request `{}`", request.download, request, ); }) .map(|request| request.download) // Ensure we only download each version once .unique_by(|download| download.key()) .collect::<Vec<_>>(); // Download and unpack the Python versions concurrently let reporter = PythonDownloadReporter::new(printer, Some(downloads.len() as u64)); let mut tasks = FuturesUnordered::new(); for download in &downloads { tasks.push(async { ( *download, download .fetch_with_retry( &client, &retry_policy, installations_dir, &scratch_dir, reinstall, python_install_mirror.as_deref(), pypy_install_mirror.as_deref(), Some(&reporter), ) .await, ) }); } let mut errors = vec![]; let mut downloaded = Vec::with_capacity(downloads.len()); let mut requests_by_new_installation = BTreeMap::new(); while let Some((download, result)) = tasks.next().await { match result { Ok(download_result) => { let path = match download_result { // We should only encounter already-available during concurrent installs DownloadResult::AlreadyAvailable(path) => path, DownloadResult::Fetched(path) => path, }; let installation = ManagedPythonInstallation::new(path, download); changelog.installed.insert(installation.key().clone()); for request in &requests { // Take note of which installations satisfied which requests if request.matches_installation(&installation) { requests_by_new_installation .entry(installation.key().clone()) .or_insert(Vec::new()) .push(request); } } if changelog.existing.contains(installation.key()) { changelog.uninstalled.insert(installation.key().clone()); } downloaded.push(installation.clone()); } Err(err) => { errors.push(( InstallErrorKind::DownloadUnpack, download.key().clone(), anyhow::Error::new(err), )); } } } let bin_dir = if matches!(bin, Some(false)) { None } else { Some(python_executable_dir()?) }; let installations: Vec<_> = downloaded.iter().chain(satisfied.iter().copied()).collect(); // Ensure that the installations are _complete_ for both downloaded installations and existing // installations that match the request for installation in &installations { installation.ensure_externally_managed()?; installation.ensure_sysconfig_patched()?; installation.ensure_canonical_executables()?; installation.ensure_build_file()?; if let Err(e) = installation.ensure_dylib_patched() { e.warn_user(installation); } let upgradeable = (default || is_default_install) || requested_minor_versions.contains(&installation.key().version().python_version()); if let Some(bin_dir) = bin_dir.as_ref() { create_bin_links( installation, bin_dir, reinstall, force, default, upgradeable, matches!( upgrade, PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) ), is_default_install, &existing_installations, &installations, &mut changelog, &mut errors, preview, ); } if !matches!(registry, Some(false)) { #[cfg(windows)] { match uv_python::windows_registry::create_registry_entry(installation) { Ok(()) => {} Err(err) => { errors.push(( InstallErrorKind::Registry, installation.key().clone(), err.into(), )); } } } } } let minor_versions = PythonInstallationMinorVersionKey::highest_installations_by_minor_version_key( installations .iter() .copied() .chain(existing_installations.iter()), ); for installation in minor_versions.values() { if matches!( upgrade, PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) ) { // During an upgrade, update existing symlinks but avoid // creating new ones. installation.update_minor_version_link(preview)?; } else { installation.ensure_minor_version_link(preview)?; } } if changelog.installed.is_empty() && errors.is_empty() { if is_default_install { if matches!( upgrade, PythonUpgrade::Enabled(PythonUpgradeSource::Install) ) { writeln!( printer.stderr(), "The default Python installation is already on the latest supported patch release. Use `uv python install <request>` to install another version.", )?; } else { writeln!( printer.stderr(), "Python is already installed. Use `uv python install <request>` to install another version.", )?; } } else if matches!( upgrade, PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) ) && requests.is_empty() { writeln!( printer.stderr(), "There are no installed versions to upgrade" )?; } else if let [request] = requests.as_slice() { // Convert to the inner request let request = &request.request; if is_unspecified_upgrade { writeln!( printer.stderr(), "All versions already on latest supported patch release" )?; } else if matches!(upgrade, PythonUpgrade::Enabled(_)) { writeln!( printer.stderr(), "{request} is already on the latest supported patch release" )?; } else { writeln!(printer.stderr(), "{request} is already installed")?; } } else { if matches!(upgrade, PythonUpgrade::Enabled(_)) { if is_unspecified_upgrade { writeln!( printer.stderr(), "All versions already on latest supported patch release" )?; } else { writeln!( printer.stderr(), "All requested versions already on latest supported patch release" )?; } } else { writeln!(printer.stderr(), "All requested versions already installed")?; } } return Ok(ExitStatus::Success); } if !changelog.installed.is_empty() { for install_key in &changelog.installed { // Make a note if the selected python is non-native for the architecture, if none of the // matching user requests were explicit. // // Emscripten is exempted as it is always "emulated". let native_arch = Arch::from_env(); if install_key.arch().family() != native_arch.family() && !install_key.os().is_emscripten() { let not_explicit = requests_by_new_installation .get(install_key) .and_then(|requests| { let all_non_explicit = requests.iter().all(|request| { if let PythonRequest::Key(key) = &request.request { !matches!(key.arch(), Some(ArchRequest::Explicit(_))) } else { true } }); if all_non_explicit { requests.iter().next() } else { None } }); if let Some(not_explicit) = not_explicit { let native_request = not_explicit.download_request.clone().with_arch(native_arch); writeln!( printer.stderr(), "{} uv selected a Python distribution with an emulated architecture ({}) for your platform because support for the native architecture ({}) is not yet mature; to override this behaviour, request the native architecture explicitly with: {}", "note:".bold(), install_key.arch(), native_arch, native_request )?; } } } if changelog.installed.len() == 1 { let installed = changelog.installed.iter().next().unwrap(); // Ex) "Installed Python 3.9.7 in 1.68s" writeln!( printer.stderr(), "{}", format!( "Installed {} {}", format!("Python {}", installed.version()).bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; } else { // Ex) "Installed 2 versions in 1.68s" writeln!( printer.stderr(), "{}", format!( "Installed {} {}", format!("{} versions", changelog.installed.len()).bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; } for event in changelog.events() { let executables = format_executables(&event, &changelog.installed_executables); match event.kind { ChangeEventKind::Added => { writeln!( printer.stderr(), " {} {}{executables}", "+".green(), event.key.bold() )?; } ChangeEventKind::Removed => { writeln!( printer.stderr(), " {} {}{executables}", "-".red(), event.key.bold() )?; } ChangeEventKind::Reinstalled => { writeln!( printer.stderr(), " {} {}{executables}", "~".yellow(), event.key.bold(), )?; } } } if let Some(bin_dir) = bin_dir.as_ref() { warn_if_not_on_path(bin_dir); } } if !errors.is_empty() { // If there are only side-effect install errors and the user didn't opt-in, we're only going // to warn let fatal = !errors.iter().all(|(kind, _, _)| match kind { InstallErrorKind::Bin => bin.is_none(), InstallErrorKind::Registry => registry.is_none(), InstallErrorKind::DownloadUnpack => false, }); for (kind, key, err) in errors .into_iter() .sorted_unstable_by(|(_, key_a, _), (_, key_b, _)| key_a.cmp(key_b)) { match kind { InstallErrorKind::DownloadUnpack => { write_error_chain( err.context(format!("Failed to install {key}")).as_ref(), printer.stderr(), "error", AnsiColors::Red, )?; } InstallErrorKind::Bin => { let (level, color) = match bin { None => ("warning", AnsiColors::Yellow), Some(false) => continue, Some(true) => ("error", AnsiColors::Red), }; write_error_chain( err.context(format!("Failed to install executable for {key}")) .as_ref(), printer.stderr(), level, color, )?; } InstallErrorKind::Registry => { let (level, color) = match registry { None => ("warning", AnsiColors::Yellow), Some(false) => continue, Some(true) => ("error", AnsiColors::Red), }; trace!("Error trace: {err:?}"); write_error_chain( err.context(format!("Failed to create registry entry for {key}")) .as_ref(), printer.stderr(), level, color, )?; } } } if fatal { return Ok(ExitStatus::Failure); } } Ok(ExitStatus::Success) } /// Link the binaries of a managed Python installation to the bin directory. /// /// This function is fallible, but errors are pushed to `errors` instead of being thrown. #[allow(clippy::fn_params_excessive_bools)] fn create_bin_links( installation: &ManagedPythonInstallation, bin: &Path, reinstall: bool, force: bool, default: bool, upgradeable: bool, upgrade: bool, is_default_install: bool, existing_installations: &[ManagedPythonInstallation], installations: &[&ManagedPythonInstallation], changelog: &mut Changelog, errors: &mut Vec<(InstallErrorKind, PythonInstallationKey, Error)>,
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/python/update_shell.rs
crates/uv/src/commands/python/update_shell.rs
#![cfg_attr(windows, allow(unreachable_code))] use std::fmt::Write; use anyhow::Result; use owo_colors::OwoColorize; use tokio::io::AsyncWriteExt; use tracing::debug; use uv_fs::Simplified; use uv_python::managed::python_executable_dir; use uv_shell::Shell; use crate::commands::ExitStatus; use crate::printer::Printer; /// Ensure that the executable directory is in PATH. pub(crate) async fn update_shell(printer: Printer) -> Result<ExitStatus> { let executable_directory = python_executable_dir()?; debug!( "Ensuring that the executable directory is in PATH: {}", executable_directory.simplified_display() ); #[cfg(windows)] { if uv_shell::windows::prepend_path(&executable_directory)? { writeln!( printer.stderr(), "Updated PATH to include executable directory {}", executable_directory.simplified_display().cyan() )?; writeln!(printer.stderr(), "Restart your shell to apply changes")?; } else { writeln!( printer.stderr(), "Executable directory {} is already in PATH", executable_directory.simplified_display().cyan() )?; } return Ok(ExitStatus::Success); } if Shell::contains_path(&executable_directory) { writeln!( printer.stderr(), "Executable directory {} is already in PATH", executable_directory.simplified_display().cyan() )?; return Ok(ExitStatus::Success); } // Determine the current shell. let Some(shell) = Shell::from_env() else { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the current shell could not be determined", executable_directory.simplified_display().cyan() )); }; // Look up the configuration files (e.g., `.bashrc`, `.zshrc`) for the shell. let files = shell.configuration_files(); if files.is_empty() { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but updating {shell} is currently unsupported", executable_directory.simplified_display().cyan() )); } // Prepare the command (e.g., `export PATH="$HOME/.cargo/bin:$PATH"`). let Some(command) = shell.prepend_path(&executable_directory) else { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the necessary command to update {shell} could not be determined", executable_directory.simplified_display().cyan() )); }; // Update each file, as necessary. let mut updated = false; for file in files { // Search for the command in the file, to avoid redundant updates. match fs_err::tokio::read_to_string(&file).await { Ok(contents) => { if contents .lines() .map(str::trim) .filter(|line| !line.starts_with('#')) .any(|line| line.contains(&command)) { debug!( "Skipping already-updated configuration file: {}", file.simplified_display() ); continue; } // Append the command to the file. fs_err::tokio::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&file) .await? .write_all(format!("{contents}\n# uv\n{command}\n").as_bytes()) .await?; writeln!( printer.stderr(), "Updated configuration file: {}", file.simplified_display().cyan() )?; updated = true; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { // Ensure that the directory containing the file exists. if let Some(parent) = file.parent() { fs_err::tokio::create_dir_all(&parent).await?; } // Append the command to the file. fs_err::tokio::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&file) .await? .write_all(format!("# uv\n{command}\n").as_bytes()) .await?; writeln!( printer.stderr(), "Created configuration file: {}", file.simplified_display().cyan() )?; updated = true; } Err(err) => { return Err(err.into()); } } } if updated { writeln!(printer.stderr(), "Restart your shell to apply changes")?; Ok(ExitStatus::Success) } else { Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the {shell} configuration files are already up-to-date", executable_directory.simplified_display().cyan() )) } }
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/src/commands/python/mod.rs
crates/uv/src/commands/python/mod.rs
pub(crate) mod dir; pub(crate) mod find; pub(crate) mod install; pub(crate) mod list; pub(crate) mod pin; pub(crate) mod uninstall; pub(crate) mod update_shell; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub(super) enum ChangeEventKind { /// The Python version was uninstalled. Removed, /// The Python version was installed. Added, /// The Python version was reinstalled. Reinstalled, } #[derive(Debug)] pub(super) struct ChangeEvent { key: uv_python::PythonInstallationKey, kind: ChangeEventKind, }
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/src/commands/python/dir.rs
crates/uv/src/commands/python/dir.rs
use std::fmt::Write; use anyhow::Context; use owo_colors::OwoColorize; use uv_fs::Simplified; use uv_python::managed::{ManagedPythonInstallations, python_executable_dir}; use crate::printer::Printer; /// Show the Python installation directory. pub(crate) fn dir(bin: bool, printer: Printer) -> anyhow::Result<()> { if bin { let bin = python_executable_dir()?; writeln!(printer.stdout(), "{}", bin.simplified_display().cyan())?; } else { let installed_toolchains = ManagedPythonInstallations::from_settings(None) .context("Failed to initialize toolchain settings")?; writeln!( printer.stdout(), "{}", installed_toolchains.root().simplified_display().cyan() )?; } 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/src/commands/python/pin.rs
crates/uv/src/commands/python/pin.rs
use std::fmt::Write; use std::path::Path; use std::str::FromStr; use anyhow::{Result, bail}; use owo_colors::OwoColorize; use tracing::debug; use uv_python::downloads::ManagedPythonDownloadList; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::DependencyGroupsWithDefaults; use uv_fs::Simplified; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PYTHON_VERSION_FILENAME, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest, PythonVersionFile, VersionFileDiscoveryOptions, }; use uv_settings::PythonInstallMirrors; use uv_warnings::warn_user_once; use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache}; use crate::commands::{ ExitStatus, project::find_requires_python, reporters::PythonDownloadReporter, }; use crate::printer::Printer; /// Pin to a specific Python version. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pin( project_dir: &Path, request: Option<String>, resolved: bool, python_preference: PythonPreference, python_downloads: PythonDownloads, no_project: bool, global: bool, rm: bool, install_mirrors: PythonInstallMirrors, client_builder: BaseClientBuilder<'_>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let workspace_cache = WorkspaceCache::default(); let virtual_project = if no_project { None } else { match VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await { Ok(virtual_project) => Some(virtual_project), Err(err) => { debug!("Failed to discover virtual project: {err}"); None } } }; // Search for an existing file, we won't necessarily write to this, we'll construct a target // path if there's a request later on. let version_file = PythonVersionFile::discover( project_dir, &VersionFileDiscoveryOptions::default().with_no_local(global), ) .await; if rm { let Some(file) = version_file? else { if global { bail!("No global Python pin found"); } bail!("No Python version file found"); }; if !global && file.is_global() { bail!("No Python version file found; use `--rm --global` to remove the global pin"); } fs_err::tokio::remove_file(file.path()).await?; writeln!( printer.stdout(), "Removed {} at `{}`", if global { "global Python pin" } else { "Python version file" }, file.path().user_display() )?; return Ok(ExitStatus::Success); } let Some(request) = request else { // Display the current pinned Python version if let Some(file) = version_file? { for pin in file.versions() { writeln!(printer.stdout(), "{}", pin.to_canonical_string())?; if let Some(virtual_project) = &virtual_project { let client = client_builder.clone().retries(0).build(); let download_list = ManagedPythonDownloadList::new( &client, install_mirrors.python_downloads_json_url.as_deref(), ) .await?; warn_if_existing_pin_incompatible_with_project( pin, virtual_project, python_preference, &download_list, cache, preview, ); } } return Ok(ExitStatus::Success); } bail!("No Python version file found; specify a version to create one") }; let request = PythonRequest::parse(&request); if let PythonRequest::ExecutableName(name) = request { bail!("Requests for arbitrary names (e.g., `{name}`) are not supported in version files"); } let reporter = PythonDownloadReporter::single(printer); let python = match PythonInstallation::find_or_download( Some(&request), EnvironmentPreference::OnlySystem, python_preference, python_downloads, &client_builder, cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await { Ok(python) => Some(python), // If no matching Python version is found, don't fail unless `resolved` was requested Err(uv_python::Error::MissingPython(err, ..)) if !resolved => { // N.B. We omit the hint and just show the inner error message warn_user_once!("{err}"); None } // If there was some other error, log it Err(err) if !resolved => { debug!("{err}"); None } // If `resolved` was requested, we must find an interpreter — fail otherwise Err(err) => return Err(err.into()), }; if let Some(virtual_project) = &virtual_project { if let Some(request_version) = pep440_version_from_request(&request) { assert_pin_compatible_with_project( &Pin { request: &request, version: &request_version, resolved: false, existing: false, }, virtual_project, )?; } else { if let Some(python) = &python { // Warn if the resolved Python is incompatible with the Python requirement unless --resolved is used if let Err(err) = assert_pin_compatible_with_project( &Pin { request: &request, version: python.python_version(), resolved: true, existing: false, }, virtual_project, ) { if resolved { return Err(err); } warn_user_once!("{err}"); } } } } let request = if resolved { // SAFETY: We exit early if Python is not found and resolved is `true` // TODO(zanieb): Maybe avoid reparsing here? PythonRequest::parse( &python .unwrap() .interpreter() .sys_executable() .user_display() .to_string(), ) } else { request }; let existing = version_file.ok().flatten(); // TODO(zanieb): Allow updating the discovered version file with an `--update` flag. let new = if global { let Some(new) = PythonVersionFile::global() else { // TODO(zanieb): We should find a nice way to surface that as an error bail!("Failed to determine directory for global Python pin"); }; new.with_versions(vec![request]) } else { PythonVersionFile::new(project_dir.join(PYTHON_VERSION_FILENAME)) .with_versions(vec![request]) }; new.write().await?; // If we updated an existing version file to a new version if let Some(existing) = existing .as_ref() .filter(|existing| existing.path() == new.path()) .and_then(PythonVersionFile::version) .filter(|version| *version != new.version().unwrap()) { writeln!( printer.stdout(), "Updated `{}` from `{}` -> `{}`", new.path().user_display().cyan(), existing.to_canonical_string().green(), new.version().unwrap().to_canonical_string().green() )?; } else { writeln!( printer.stdout(), "Pinned `{}` to `{}`", new.path().user_display().cyan(), new.version().unwrap().to_canonical_string().green() )?; } Ok(ExitStatus::Success) } fn pep440_version_from_request(request: &PythonRequest) -> Option<uv_pep440::Version> { let version_request = match request { PythonRequest::Version(version) | PythonRequest::ImplementationVersion(_, version) => { version } PythonRequest::Key(download_request) => download_request.version()?, _ => { return None; } }; if matches!(version_request, uv_python::VersionRequest::Range(_, _)) { return None; } // SAFETY: converting `VersionRequest` to `Version` is guaranteed to succeed if not a `Range` // and does not have a Python variant (e.g., freethreaded) attached. Some( uv_pep440::Version::from_str(&version_request.clone().without_python_variant().to_string()) .unwrap(), ) } /// Check if pinned request is compatible with the workspace/project's `Requires-Python`. fn warn_if_existing_pin_incompatible_with_project( pin: &PythonRequest, virtual_project: &VirtualProject, python_preference: PythonPreference, downloads_list: &ManagedPythonDownloadList, cache: &Cache, preview: Preview, ) { // Check if the pinned version is compatible with the project. if let Some(pin_version) = pep440_version_from_request(pin) { if let Err(err) = assert_pin_compatible_with_project( &Pin { request: pin, version: &pin_version, resolved: false, existing: true, }, virtual_project, ) { warn_user_once!("{err}"); return; } } // If there is not a version in the pinned request, attempt to resolve the pin into an // interpreter to check for compatibility on the current system. match PythonInstallation::find( pin, EnvironmentPreference::OnlySystem, python_preference, downloads_list, cache, preview, ) { Ok(python) => { let python_version = python.python_version(); debug!( "The pinned Python version `{}` resolves to `{}`", pin, python_version ); // Warn on incompatibilities when viewing existing pins if let Err(err) = assert_pin_compatible_with_project( &Pin { request: pin, version: python_version, resolved: true, existing: true, }, virtual_project, ) { warn_user_once!("{err}"); } } Err(err) => { warn_user_once!( "Failed to resolve pinned Python version `{}`: {err}", pin.to_canonical_string(), ); } } } /// Utility struct for representing pins in error messages. struct Pin<'a> { request: &'a PythonRequest, version: &'a uv_pep440::Version, resolved: bool, existing: bool, } /// Checks if the pinned Python version is compatible with the workspace/project's `Requires-Python`. fn assert_pin_compatible_with_project(pin: &Pin, virtual_project: &VirtualProject) -> Result<()> { // Don't factor in requires-python settings on dependency-groups let groups = DependencyGroupsWithDefaults::none(); let (requires_python, project_type) = match virtual_project { VirtualProject::Project(project_workspace) => { debug!( "Discovered project `{}` at: {}", project_workspace.project_name(), project_workspace.workspace().install_path().display() ); let requires_python = find_requires_python(project_workspace.workspace(), &groups)?; (requires_python, "project") } VirtualProject::NonProject(workspace) => { debug!( "Discovered virtual workspace at: {}", workspace.install_path().display() ); let requires_python = find_requires_python(workspace, &groups)?; (requires_python, "workspace") } }; let Some(requires_python) = requires_python else { return Ok(()); }; if requires_python.contains(pin.version) { return Ok(()); } let given = if pin.existing { "pinned" } else { "requested" }; let resolved = if pin.resolved { format!(" resolves to `{}` which ", pin.version) } else { String::new() }; Err(anyhow::anyhow!( "The {given} Python version `{}`{resolved} is incompatible with the {} `requires-python` value of `{}`.", pin.request.to_canonical_string(), project_type, requires_python )) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/auth/login.rs
crates/uv/src/commands/auth/login.rs
use std::fmt::Write; use anyhow::{Result, bail}; use console::Term; use owo_colors::OwoColorize; use url::Url; use uuid::Uuid; use uv_auth::{ AccessToken, AuthBackend, Credentials, PyxJwt, PyxOAuthTokens, PyxTokenStore, PyxTokens, Service, TextCredentialStore, }; use uv_client::{AuthIntegration, BaseClient, BaseClientBuilder}; use uv_distribution_types::IndexUrl; use uv_pep508::VerbatimUrl; use uv_preview::Preview; use crate::commands::ExitStatus; use crate::printer::Printer; // We retry no more than this many times when polling for login status. const STATUS_RETRY_LIMIT: u32 = 60; /// Login to a service. pub(crate) async fn login( service: Service, username: Option<String>, password: Option<String>, token: Option<String>, client_builder: BaseClientBuilder<'_>, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let pyx_store = PyxTokenStore::from_settings()?; if pyx_store.is_known_domain(service.url()) { if username.is_some() { bail!("Cannot specify a username when logging in to pyx"); } if password.is_some() { bail!("Cannot specify a password when logging in to pyx"); } let client = client_builder .auth_integration(AuthIntegration::NoAuthMiddleware) .build(); let access_token = pyx_login_with_browser(&pyx_store, &client, &printer).await?; let jwt = PyxJwt::decode(&access_token)?; if let Some(name) = jwt.name.as_deref() { writeln!(printer.stderr(), "Logged in to {}", name.bold().cyan())?; } else { writeln!( printer.stderr(), "Logged in to {}", pyx_store.api().bold().cyan() )?; } return Ok(ExitStatus::Success); } let backend = AuthBackend::from_settings(preview).await?; // If the URL includes a known index URL suffix, strip it // TODO(zanieb): Use a shared abstraction across `login` and `logout`? let url = service.url().clone(); let (service, url) = match IndexUrl::from(VerbatimUrl::from_url(url.clone())).root() { Some(root) => (Service::try_from(root.clone())?, root), None => (service, url), }; // Extract credentials from URL if present let url_credentials = Credentials::from_url(&url); let url_username = url_credentials.as_ref().and_then(|c| c.username()); let url_password = url_credentials.as_ref().and_then(|c| c.password()); let username = match (username, url_username) { (Some(cli), Some(url)) => { bail!( "Cannot specify a username both via the URL and CLI; found `--username {cli}` and `{url}`" ); } (Some(cli), None) => Some(cli), (None, Some(url)) => Some(url.to_string()), (None, None) => { // When using `--token`, we'll use a `__token__` placeholder username if token.is_some() { Some("__token__".to_string()) } else { None } } }; // Ensure that a username is not provided when using a token if token.is_some() { if let Some(username) = &username { if username != "__token__" { bail!("When using `--token`, a username cannot not be provided; found: {username}"); } } } // Prompt for a username if not provided let username = if let Some(username) = username { username } else { let term = Term::stderr(); if term.is_term() { let prompt = "username: "; uv_console::username(prompt, &term)? } else { bail!("No username provided; did you mean to provide `--username` or `--token`?"); } }; if username.is_empty() { bail!("Username cannot be empty"); } let password = match (password, url_password, token) { (Some(_), Some(_), _) => { bail!("Cannot specify a password both via the URL and CLI"); } (Some(_), None, Some(_)) => { bail!("Cannot specify a password via `--password` when using `--token`"); } (None, Some(_), Some(_)) => { bail!("Cannot include a password in the URL when using `--token`") } (None, None, Some(value)) | (Some(value), None, None) if value == "-" => { let mut input = String::new(); std::io::stdin().read_line(&mut input)?; input.trim().to_string() } (Some(cli), None, None) => cli, (None, Some(url), None) => url.to_string(), (None, None, Some(token)) => token, (None, None, None) => { let term = Term::stderr(); if term.is_term() { let prompt = "password: "; uv_console::password(prompt, &term)? } else { bail!("No password provided; did you mean to provide `--password` or `--token`?"); } } }; if password.is_empty() { bail!("Password cannot be empty"); } let display_url = if username == "__token__" { url.without_credentials().to_string() } else { format!("{username}@{}", url.without_credentials()) }; // TODO(zanieb): Add support for other authentication schemes here, e.g., `Credentials::Bearer` let credentials = Credentials::basic(Some(username), Some(password)); match backend { AuthBackend::System(provider) => { provider.store(&url, &credentials).await?; } AuthBackend::TextStore(mut store, _lock) => { store.insert(service.clone(), credentials); store.write(TextCredentialStore::default_file()?, _lock)?; } } writeln!( printer.stderr(), "Stored credentials for {}", display_url.bold().cyan() )?; Ok(ExitStatus::Success) } /// Log in via the [`PyxTokenStore`]. pub(crate) async fn pyx_login_with_browser( store: &PyxTokenStore, client: &BaseClient, printer: &Printer, ) -> Result<AccessToken> { // Generate a login code, like `67e55044-10b1-426f-9247-bb680e5fe0c8`. let cli_token = Uuid::new_v4(); let url = { let mut url = store.api().clone(); url.set_path(&format!("auth/cli/login/{cli_token}")); url }; match open::that(url.as_ref()) { Ok(()) => { writeln!(printer.stderr(), "Logging in with {}", url.cyan().bold())?; } Err(..) => { writeln!( printer.stderr(), "Open the following URL in your browser: {}", url.cyan().bold() )?; } } // Poll the server for the login code. let url = { let mut url = store.api().clone(); url.set_path(&format!("auth/cli/status/{cli_token}")); url }; let mut retry = 0; let credentials = loop { let response = client .for_host(store.api()) .get(Url::from(url.clone())) .send() .await?; match response.status() { // Retry on 404. reqwest::StatusCode::NOT_FOUND => { tokio::time::sleep(std::time::Duration::from_secs(1)).await; retry += 1; } // Parse the credentials on success. _ if response.status().is_success() => { let credentials = response.json::<PyxOAuthTokens>().await?; break Ok::<PyxTokens, anyhow::Error>(PyxTokens::OAuth(credentials)); } // Fail on any other status code (like a 500). status => { break Err(anyhow::anyhow!("Failed to login with code `{status}`")); } } if retry >= STATUS_RETRY_LIMIT { break Err(anyhow::anyhow!( "Login session timed out after {STATUS_RETRY_LIMIT} seconds" )); } }?; store.write(&credentials).await?; Ok(AccessToken::from(credentials)) }
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/src/commands/auth/helper.rs
crates/uv/src/commands/auth/helper.rs
use std::collections::HashMap; use std::fmt::Write; use std::io::Read; use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use tracing::debug; use uv_auth::{AuthBackend, Credentials, PyxTokenStore}; use uv_client::BaseClientBuilder; use uv_preview::{Preview, PreviewFeatures}; use uv_redacted::DisplaySafeUrl; use uv_warnings::warn_user; use crate::{commands::ExitStatus, printer::Printer}; /// Request format for the Bazel credential helper protocol. #[derive(Debug, Deserialize)] struct BazelCredentialRequest { uri: DisplaySafeUrl, } impl BazelCredentialRequest { fn from_str(s: &str) -> Result<Self> { serde_json::from_str(s).context("Failed to parse credential request as JSON") } fn from_stdin() -> Result<Self> { let mut buffer = String::new(); std::io::stdin() .read_to_string(&mut buffer) .context("Failed to read from stdin")?; Self::from_str(&buffer) } } /// Response format for the Bazel credential helper protocol. #[derive(Debug, Serialize, Default)] struct BazelCredentialResponse { headers: HashMap<String, Vec<String>>, } impl TryFrom<Credentials> for BazelCredentialResponse { fn try_from(creds: Credentials) -> Result<Self> { let header_str = creds .to_header_value() .to_str() // TODO: this is infallible in practice .context("Failed to convert header value to string")? .to_owned(); Ok(Self { headers: HashMap::from([("Authorization".to_owned(), vec![header_str])]), }) } type Error = anyhow::Error; } async fn credentials_for_url( url: &DisplaySafeUrl, client_builder: BaseClientBuilder<'_>, preview: Preview, ) -> Result<Option<Credentials>> { let pyx_store = PyxTokenStore::from_settings()?; // Use only the username from the URL, if present - discarding the password let url_credentials = Credentials::from_url(url); let username = url_credentials.as_ref().and_then(|c| c.username()); if url_credentials .as_ref() .map(|c| c.password().is_some()) .unwrap_or(false) { debug!("URL '{url}' contain a password; ignoring"); } if pyx_store.is_known_domain(url) { if username.is_some() { bail!( "Cannot specify a username for URLs under {}", url.host() .map(|host| host.to_string()) .unwrap_or(url.to_string()) ); } let client = client_builder .auth_integration(uv_client::AuthIntegration::NoAuthMiddleware) .build(); let token = pyx_store .access_token(client.for_host(pyx_store.api()).raw_client(), 0) .await .context("Authentication failure")? .context("No access token found")?; return Ok(Some(Credentials::bearer(token.into_bytes()))); } let backend = AuthBackend::from_settings(preview).await?; let credentials = match &backend { AuthBackend::System(provider) => provider.fetch(url, username).await, AuthBackend::TextStore(store, _lock) => store.get_credentials(url, username).cloned(), }; Ok(credentials) } /// Implement the Bazel credential helper protocol. /// /// Reads a JSON request from stdin containing a URI, looks up credentials /// for that URI using uv's authentication backends, and writes a JSON response /// to stdout containing HTTP headers (if credentials are found). /// /// Protocol specification TLDR: /// - Input (stdin): `{"uri": "https://example.com/path"}` /// - Output (stdout): `{"headers": {"Authorization": ["Basic ..."]}}` or `{"headers": {}}` /// - Errors: Written to stderr with non-zero exit code /// /// Full spec is [available here](https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md) pub(crate) async fn helper( client_builder: BaseClientBuilder<'_>, preview: Preview, printer: Printer, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::AUTH_HELPER) { warn_user!( "The `uv auth helper` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning", PreviewFeatures::AUTH_HELPER ); } let request = BazelCredentialRequest::from_stdin()?; // TODO: make this logic generic over the protocol by providing `request.uri` from a // trait - that should help with adding new protocols let credentials = credentials_for_url(&request.uri, client_builder, preview).await?; let response = serde_json::to_string( &credentials .map(BazelCredentialResponse::try_from) .unwrap_or_else(|| Ok(BazelCredentialResponse::default()))?, ) .context("Failed to serialize response as JSON")?; writeln!(printer.stdout_important(), "{response}")?; Ok(ExitStatus::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/src/commands/auth/mod.rs
crates/uv/src/commands/auth/mod.rs
pub(crate) mod dir; pub(crate) mod helper; pub(crate) mod login; pub(crate) mod logout; pub(crate) mod token;
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/src/commands/auth/logout.rs
crates/uv/src/commands/auth/logout.rs
use std::fmt::Write; use anyhow::{Context, Result, bail}; use owo_colors::OwoColorize; use uv_auth::{AuthBackend, Credentials, PyxTokenStore, Service, TextCredentialStore, Username}; use uv_client::BaseClientBuilder; use uv_distribution_types::IndexUrl; use uv_pep508::VerbatimUrl; use uv_preview::Preview; use crate::{commands::ExitStatus, printer::Printer}; /// Logout from a service. /// /// If no username is provided, defaults to `__token__`. pub(crate) async fn logout( service: Service, username: Option<String>, client_builder: BaseClientBuilder<'_>, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let pyx_store = PyxTokenStore::from_settings()?; if pyx_store.is_known_domain(service.url()) { return pyx_logout(&pyx_store, client_builder, printer).await; } let backend = AuthBackend::from_settings(preview).await?; // TODO(zanieb): Use a shared abstraction across `login` and `logout`? let url = service.url().clone(); let (service, url) = match IndexUrl::from(VerbatimUrl::from_url(url.clone())).root() { Some(root) => (Service::try_from(root.clone())?, root), None => (service, url), }; // Extract credentials from URL if present let url_credentials = Credentials::from_url(&url); let url_username = url_credentials.as_ref().and_then(|c| c.username()); let username = match (username, url_username) { (Some(cli), Some(url)) => { bail!( "Cannot specify a username both via the URL and CLI; found `--username {cli}` and `{url}`" ); } (Some(cli), None) => cli, (None, Some(url)) => url.to_string(), (None, None) => "__token__".to_string(), }; if username.is_empty() { bail!("Username cannot be empty"); } let display_url = if username == "__token__" { url.without_credentials().to_string() } else { format!("{username}@{}", url.without_credentials()) }; // TODO(zanieb): Consider exhaustively logging out from all backends match backend { AuthBackend::System(provider) => { provider .remove(&url, &username) .await .with_context(|| format!("Unable to remove credentials for {display_url}"))?; } AuthBackend::TextStore(mut store, _lock) => { if store .remove(&service, Username::from(Some(username.clone()))) .is_none() { bail!("No matching entry found for {display_url}"); } store .write(TextCredentialStore::default_file()?, _lock) .with_context(|| "Failed to persist changes to credentials after removal")?; } } writeln!( printer.stderr(), "Removed credentials for {}", display_url.bold().cyan() )?; Ok(ExitStatus::Success) } /// Log out via the [`PyxTokenStore`], invalidating the existing tokens. async fn pyx_logout( store: &PyxTokenStore, client_builder: BaseClientBuilder<'_>, printer: Printer, ) -> Result<ExitStatus> { // Initialize the client. let client = client_builder.build(); // Retrieve the token store. let Some(tokens) = store.read().await? else { writeln!( printer.stderr(), "{}", format_args!("No credentials found for {}", store.api().bold().cyan()) )?; return Ok(ExitStatus::Success); }; // Add the token to the request. let url = { let mut url = store.api().clone(); url.set_path("auth/cli/logout"); url }; // Build a basic request first, then authenticate it let request = reqwest::Request::new(reqwest::Method::GET, url.into()); let request = Credentials::from(tokens).authenticate(request); // Hit the logout endpoint using the client's execute method let response = client.execute(request).await?; match response.error_for_status_ref() { Ok(..) => {} Err(err) if matches!(err.status(), Some(reqwest::StatusCode::UNAUTHORIZED)) => { tracing::debug!( "Received 401 (Unauthorized) response from logout endpoint; removing tokens..." ); } Err(err) => { return Err(err.into()); } } // Remove the tokens from the store. match store.delete().await { Ok(..) => {} Err(err) if matches!(err.kind(), std::io::ErrorKind::NotFound) => {} Err(err) => return Err(err.into()), } writeln!( printer.stderr(), "{}", format_args!("Logged out from {}", store.api().bold().cyan()) )?; Ok(ExitStatus::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/src/commands/auth/dir.rs
crates/uv/src/commands/auth/dir.rs
use owo_colors::OwoColorize; use std::fmt::Write; use uv_auth::{PyxTokenStore, Service, TextCredentialStore}; use uv_fs::Simplified; use crate::printer::Printer; /// Show the credentials directory. pub(crate) fn dir(service: Option<&Service>, printer: Printer) -> anyhow::Result<()> { if let Some(service) = service { let pyx_store = PyxTokenStore::from_settings()?; if pyx_store.is_known_domain(service.url()) { writeln!( printer.stdout(), "{}", pyx_store.root().simplified_display().cyan() )?; return Ok(()); } } let root = TextCredentialStore::directory_path()?; writeln!(printer.stdout(), "{}", root.simplified_display().cyan())?; 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/src/commands/auth/token.rs
crates/uv/src/commands/auth/token.rs
use std::fmt::Write; use anyhow::{Result, bail}; use tracing::debug; use uv_auth::{AuthBackend, Service}; use uv_auth::{Credentials, PyxTokenStore}; use uv_client::{AuthIntegration, BaseClient, BaseClientBuilder}; use uv_preview::Preview; use crate::commands::ExitStatus; use crate::commands::auth::login; use crate::printer::Printer; /// Show the token that will be used for a service. pub(crate) async fn token( service: Service, username: Option<String>, client_builder: BaseClientBuilder<'_>, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let pyx_store = PyxTokenStore::from_settings()?; if pyx_store.is_known_domain(service.url()) { if username.is_some() { bail!("Cannot specify a username when logging in to pyx"); } let client = client_builder .auth_integration(AuthIntegration::NoAuthMiddleware) .build(); pyx_refresh(&pyx_store, &client, printer).await?; return Ok(ExitStatus::Success); } let backend = AuthBackend::from_settings(preview).await?; let url = service.url(); // Extract credentials from URL if present let url_credentials = Credentials::from_url(url); let url_username = url_credentials.as_ref().and_then(|c| c.username()); let username = match (username, url_username) { (Some(cli), Some(url)) => { bail!( "Cannot specify a username both via the URL and CLI; found `--username {cli}` and `{url}`" ); } (Some(cli), None) => cli, (None, Some(url)) => url.to_string(), (None, None) => "__token__".to_string(), }; if username.is_empty() { bail!("Username cannot be empty"); } let display_url = if username == "__token__" { url.without_credentials().to_string() } else { format!("{username}@{}", url.without_credentials()) }; let credentials = match &backend { AuthBackend::System(provider) => provider .fetch(url, Some(&username)) .await .ok_or_else(|| anyhow::anyhow!("Failed to fetch credentials for {display_url}"))?, AuthBackend::TextStore(store, _lock) => store .get_credentials(url, Some(&username)) .cloned() .ok_or_else(|| anyhow::anyhow!("Failed to fetch credentials for {display_url}"))?, }; let Some(password) = credentials.password() else { bail!( "No {} found for {display_url}", if username != "__token__" { "password" } else { "token" } ); }; writeln!(printer.stdout(), "{password}")?; Ok(ExitStatus::Success) } /// Refresh the authentication tokens in the [`PyxTokenStore`], prompting for login if necessary. async fn pyx_refresh(store: &PyxTokenStore, client: &BaseClient, printer: Printer) -> Result<()> { // Retrieve the token store. let token = match store .access_token(client.for_host(store.api()).raw_client(), 0) .await { // If the tokens were successfully refreshed, return them. Ok(Some(token)) => token, // If the token store is empty, prompt for login. Ok(None) => { debug!("Token store is empty; prompting for login..."); login::pyx_login_with_browser(store, client, &printer).await? } // Similarly, if the refresh token expired, prompt for login. Err(err) if err.is_unauthorized() => { if store.has_auth_token() { return Err( anyhow::Error::from(err).context("Failed to authenticate with access token") ); } else if store.has_api_key() { return Err(anyhow::Error::from(err).context("Failed to authenticate with API key")); } debug!( "Received 401 (Unauthorized) response from refresh endpoint; prompting for login..." ); login::pyx_login_with_browser(store, client, &printer).await? } Err(err) => { return Err(err.into()); } }; writeln!(printer.stdout(), "{}", token.as_str())?; 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/src/commands/workspace/list.rs
crates/uv/src/commands/workspace/list.rs
use std::fmt::Write; use std::path::Path; use anyhow::Result; use owo_colors::OwoColorize; use uv_fs::Simplified; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache}; use crate::commands::ExitStatus; use crate::printer::Printer; /// List workspace members pub(crate) async fn list( project_dir: &Path, paths: bool, preview: Preview, printer: Printer, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::WORKSPACE_LIST) { warn_user!( "The `uv workspace list` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::WORKSPACE_LIST ); } let workspace_cache = WorkspaceCache::default(); let workspace = Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache).await?; for (name, member) in workspace.packages() { if paths { writeln!( printer.stdout(), "{}", member.root().simplified_display().cyan() )?; } else { writeln!(printer.stdout(), "{}", name.cyan())?; } } Ok(ExitStatus::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/src/commands/workspace/mod.rs
crates/uv/src/commands/workspace/mod.rs
pub(crate) mod dir; pub(crate) mod list; pub(crate) mod metadata;
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/workspace/dir.rs
crates/uv/src/commands/workspace/dir.rs
use std::fmt::Write; use std::path::Path; use anyhow::{Result, bail}; use owo_colors::OwoColorize; use uv_fs::Simplified; use uv_normalize::PackageName; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache}; use crate::commands::ExitStatus; use crate::printer::Printer; /// Print the path to the workspace dir pub(crate) async fn dir( package_name: Option<PackageName>, project_dir: &Path, preview: Preview, printer: Printer, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::WORKSPACE_DIR) { warn_user!( "The `uv workspace dir` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::WORKSPACE_DIR ); } let workspace_cache = WorkspaceCache::default(); let workspace = Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache).await?; let dir = match package_name { None => workspace.install_path(), Some(package) => { if let Some(p) = workspace.packages().get(&package) { p.root() } else { bail!("Package `{package}` not found in workspace.") } } }; writeln!(printer.stdout(), "{}", dir.simplified_display().cyan())?; Ok(ExitStatus::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/src/commands/workspace/metadata.rs
crates/uv/src/commands/workspace/metadata.rs
use std::fmt::Write; use std::path::Path; use anyhow::Result; use serde::Serialize; use uv_fs::PortablePathBuf; use uv_normalize::PackageName; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache}; use crate::commands::ExitStatus; use crate::printer::Printer; /// The schema version for the metadata report. #[derive(Serialize, Debug, Default)] #[serde(rename_all = "snake_case")] enum SchemaVersion { /// An unstable, experimental schema. #[default] Preview, } /// The schema metadata for the metadata report. #[derive(Serialize, Debug, Default)] struct SchemaReport { /// The version of the schema. version: SchemaVersion, } /// Report for a single workspace member. #[derive(Serialize, Debug)] struct WorkspaceMemberReport { /// The name of the workspace member. name: PackageName, /// The path to the workspace member's root directory. path: PortablePathBuf, } /// The report for a metadata operation. #[derive(Serialize, Debug)] struct MetadataReport { /// The schema of this report. schema: SchemaReport, /// The workspace root directory. workspace_root: PortablePathBuf, /// The workspace members. members: Vec<WorkspaceMemberReport>, } /// Display metadata about the workspace. pub(crate) async fn metadata( project_dir: &Path, preview: Preview, printer: Printer, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::WORKSPACE_METADATA) { warn_user!( "The `uv workspace metadata` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::WORKSPACE_METADATA ); } let workspace_cache = WorkspaceCache::default(); let workspace = Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache).await?; let members = workspace .packages() .values() .map(|package| WorkspaceMemberReport { name: package.project().name.clone(), path: PortablePathBuf::from(package.root().as_path()), }) .collect(); let report = MetadataReport { schema: SchemaReport::default(), workspace_root: PortablePathBuf::from(workspace.install_path().as_path()), members, }; writeln!( printer.stdout(), "{}", serde_json::to_string_pretty(&report)? )?; Ok(ExitStatus::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/src/commands/project/install_target.rs
crates/uv/src/commands/project/install_target.rs
use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::path::Path; use std::str::FromStr; use itertools::Either; use rustc_hash::FxHashSet; use uv_configuration::{Constraints, DependencyGroupsWithDefaults, ExtrasSpecification}; use uv_distribution_types::Index; use uv_normalize::{ExtraName, PackageName}; use uv_pypi_types::{DependencyGroupSpecifier, LenientRequirement, VerbatimParsedUrl}; use uv_resolver::{Installable, Lock, Package}; use uv_scripts::Pep723Script; use uv_workspace::Workspace; use uv_workspace::pyproject::{Source, Sources, ToolUvSources}; use crate::commands::project::ProjectError; /// A target that can be installed from a lockfile. #[derive(Debug, Copy, Clone)] pub(crate) enum InstallTarget<'lock> { /// A project (which could be a workspace root or member). Project { workspace: &'lock Workspace, name: &'lock PackageName, lock: &'lock Lock, }, /// Multiple specific projects in a workspace. Projects { workspace: &'lock Workspace, names: &'lock [PackageName], lock: &'lock Lock, }, /// An entire workspace. Workspace { workspace: &'lock Workspace, lock: &'lock Lock, }, /// An entire workspace with a (legacy) non-project root. NonProjectWorkspace { workspace: &'lock Workspace, lock: &'lock Lock, }, /// A PEP 723 script. Script { script: &'lock Pep723Script, lock: &'lock Lock, }, } impl<'lock> Installable<'lock> for InstallTarget<'lock> { fn install_path(&self) -> &'lock Path { match self { Self::Project { workspace, .. } => workspace.install_path(), Self::Projects { workspace, .. } => workspace.install_path(), Self::Workspace { workspace, .. } => workspace.install_path(), Self::NonProjectWorkspace { workspace, .. } => workspace.install_path(), Self::Script { script, .. } => script.path.parent().unwrap(), } } fn lock(&self) -> &'lock Lock { match self { Self::Project { lock, .. } => lock, Self::Projects { lock, .. } => lock, Self::Workspace { lock, .. } => lock, Self::NonProjectWorkspace { lock, .. } => lock, Self::Script { lock, .. } => lock, } } #[allow(refining_impl_trait)] fn roots(&self) -> Box<dyn Iterator<Item = &PackageName> + '_> { match self { Self::Project { name, .. } => Box::new(std::iter::once(*name)), Self::Projects { names, .. } => Box::new(names.iter()), Self::NonProjectWorkspace { lock, .. } => Box::new(lock.members().iter()), Self::Workspace { lock, .. } => { // Identify the workspace members. // // The members are encoded directly in the lockfile, unless the workspace contains a // single member at the root, in which case, we identify it by its source. if lock.members().is_empty() { Box::new(lock.root().into_iter().map(Package::name)) } else { Box::new(lock.members().iter()) } } Self::Script { .. } => Box::new(std::iter::empty()), } } fn project_name(&self) -> Option<&PackageName> { match self { Self::Project { name, .. } => Some(name), Self::Projects { .. } => None, Self::Workspace { .. } => None, Self::NonProjectWorkspace { .. } => None, Self::Script { .. } => None, } } } impl<'lock> InstallTarget<'lock> { /// Return an iterator over the [`Index`] definitions in the target. pub(crate) fn indexes(self) -> impl Iterator<Item = &'lock Index> { match self { Self::Project { workspace, .. } | Self::Projects { workspace, .. } | Self::Workspace { workspace, .. } | Self::NonProjectWorkspace { workspace, .. } => { Either::Left(workspace.indexes().iter().chain( workspace.packages().values().flat_map(|member| { member .pyproject_toml() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.index.as_ref()) .into_iter() .flatten() }), )) } Self::Script { script, .. } => Either::Right( script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.top_level.index.as_deref()) .into_iter() .flatten(), ), } } /// Return an iterator over all [`Sources`] defined by the target. pub(crate) fn sources(&self) -> impl Iterator<Item = &Source> { match self { Self::Project { workspace, .. } | Self::Projects { workspace, .. } | Self::Workspace { workspace, .. } | Self::NonProjectWorkspace { workspace, .. } => { Either::Left(workspace.sources().values().flat_map(Sources::iter).chain( workspace.packages().values().flat_map(|member| { member .pyproject_toml() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.sources.as_ref()) .map(ToolUvSources::inner) .into_iter() .flat_map(|sources| sources.values().flat_map(Sources::iter)) }), )) } Self::Script { script, .. } => { Either::Right(script.sources().values().flat_map(Sources::iter)) } } } /// Return an iterator over all requirements defined by the target. pub(crate) fn requirements( &self, ) -> impl Iterator<Item = Cow<'lock, uv_pep508::Requirement<VerbatimParsedUrl>>> { match self { Self::Project { workspace, .. } | Self::Projects { workspace, .. } | Self::Workspace { workspace, .. } | Self::NonProjectWorkspace { workspace, .. } => { Either::Left( // Iterate over the non-member requirements in the workspace. workspace .requirements() .into_iter() .map(Cow::Owned) .chain( workspace .workspace_dependency_groups() .ok() .into_iter() .flat_map(|dependency_groups| { dependency_groups .into_values() .flat_map(|group| group.requirements) .map(Cow::Owned) }), ) .chain(workspace.packages().values().flat_map(|member| { // Iterate over all dependencies in each member. let dependencies = member .pyproject_toml() .project .as_ref() .and_then(|project| project.dependencies.as_ref()) .into_iter() .flatten(); let optional_dependencies = member .pyproject_toml() .project .as_ref() .and_then(|project| project.optional_dependencies.as_ref()) .into_iter() .flat_map(|optional| optional.values()) .flatten(); let dependency_groups = member .pyproject_toml() .dependency_groups .as_ref() .into_iter() .flatten() .flat_map(|(_, dependencies)| { dependencies.iter().filter_map(|specifier| { if let DependencyGroupSpecifier::Requirement(requirement) = specifier { Some(requirement) } else { None } }) }); let dev_dependencies = member .pyproject_toml() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.dev_dependencies.as_ref()) .into_iter() .flatten(); dependencies .chain(optional_dependencies) .chain(dependency_groups) .filter_map(|requires_dist| { LenientRequirement::<VerbatimParsedUrl>::from_str(requires_dist) .map(uv_pep508::Requirement::from) .map(Cow::Owned) .ok() }) .chain(dev_dependencies.map(Cow::Borrowed)) })), ) } Self::Script { script, .. } => Either::Right( script .metadata .dependencies .iter() .flatten() .map(Cow::Borrowed), ), } } pub(crate) fn build_constraints(&self) -> Constraints { self.lock().build_constraints(self.install_path()) } /// Validate the extras requested by the [`ExtrasSpecification`]. #[allow(clippy::result_large_err)] pub(crate) fn validate_extras(self, extras: &ExtrasSpecification) -> Result<(), ProjectError> { if extras.is_empty() { return Ok(()); } match self { Self::Project { lock, .. } | Self::Projects { lock, .. } | Self::Workspace { lock, .. } | Self::NonProjectWorkspace { lock, .. } => { if !lock.supports_provides_extra() { return Ok(()); } let roots = self.roots().collect::<FxHashSet<_>>(); let member_packages: Vec<&Package> = lock .packages() .iter() .filter(|package| roots.contains(package.name())) .collect(); // Collect all known extras from the member packages. let known_extras = member_packages .iter() .flat_map(|package| package.provides_extras().iter()) .collect::<FxHashSet<_>>(); for extra in extras.explicit_names() { if !known_extras.contains(extra) { return match self { Self::Project { .. } => { Err(ProjectError::MissingExtraProject(extra.clone())) } Self::Projects { .. } => { Err(ProjectError::MissingExtraProjects(extra.clone())) } _ => Err(ProjectError::MissingExtraProjects(extra.clone())), }; } } } Self::Script { .. } => { // We shouldn't get here if the list is empty so we can assume it isn't let extra = extras .explicit_names() .next() .expect("non-empty extras") .clone(); return Err(ProjectError::MissingExtraScript(extra)); } } Ok(()) } /// Validate the dependency groups requested by the [`DependencyGroupSpecifier`]. #[allow(clippy::result_large_err)] pub(crate) fn validate_groups( self, groups: &DependencyGroupsWithDefaults, ) -> Result<(), ProjectError> { // If no groups were specified, short-circuit. if groups.explicit_names().next().is_none() { return Ok(()); } match self { Self::Workspace { lock, workspace } | Self::NonProjectWorkspace { lock, workspace } => { let roots = self.roots().collect::<FxHashSet<_>>(); let member_packages: Vec<&Package> = lock .packages() .iter() .filter(|package| roots.contains(package.name())) .collect(); // Extract the dependency groups that are exclusive to the workspace root. let known_groups = member_packages .iter() .flat_map(|package| package.dependency_groups().keys().map(Cow::Borrowed)) .chain( workspace .workspace_dependency_groups() .ok() .into_iter() .flat_map(|dependency_groups| { dependency_groups.into_keys().map(Cow::Owned) }), ) .collect::<FxHashSet<_>>(); for group in groups.explicit_names() { if !known_groups.contains(group) { return Err(ProjectError::MissingGroupProjects(group.clone())); } } } Self::Project { lock, .. } | Self::Projects { lock, .. } => { let roots = self.roots().collect::<FxHashSet<_>>(); let member_packages: Vec<&Package> = lock .packages() .iter() .filter(|package| roots.contains(package.name())) .collect(); // Extract the dependency groups defined in the relevant member(s). let known_groups = member_packages .iter() .flat_map(|package| package.dependency_groups().keys()) .collect::<FxHashSet<_>>(); for group in groups.explicit_names() { if !known_groups.contains(group) { return match self { Self::Project { .. } => { Err(ProjectError::MissingGroupProject(group.clone())) } Self::Projects { .. } => { Err(ProjectError::MissingGroupProjects(group.clone())) } _ => unreachable!(), }; } } } Self::Script { .. } => { if let Some(group) = groups.explicit_names().next() { return Err(ProjectError::MissingGroupScript(group.clone())); } } } Ok(()) } /// Returns the names of all packages in the workspace that will be installed. /// /// Note this only includes workspace members. pub(crate) fn packages( &self, extras: &ExtrasSpecification, groups: &DependencyGroupsWithDefaults, ) -> BTreeSet<&PackageName> { match self { Self::Project { lock, .. } | Self::Projects { lock, .. } => { let roots = self.roots().collect::<FxHashSet<_>>(); // Collect the packages by name for efficient lookup. let packages = lock .packages() .iter() .map(|package| (package.name(), package)) .collect::<BTreeMap<_, _>>(); // We'll include all specified projects let mut required_members = BTreeSet::new(); for name in &roots { required_members.insert(*name); } // Find all workspace member dependencies recursively for all specified packages let mut queue: VecDeque<(&PackageName, Option<&ExtraName>)> = VecDeque::new(); let mut seen: FxHashSet<(&PackageName, Option<&ExtraName>)> = FxHashSet::default(); for name in roots { let Some(root_package) = packages.get(name) else { continue; }; if groups.prod() { // Add the root package if seen.insert((name, None)) { queue.push_back((name, None)); } // Add explicitly activated extras for the root package for extra in extras.extra_names(root_package.optional_dependencies().keys()) { if seen.insert((name, Some(extra))) { queue.push_back((name, Some(extra))); } } } // Add activated dependency groups for the root package for (group_name, dependencies) in root_package.resolved_dependency_groups() { if !groups.contains(group_name) { continue; } for dependency in dependencies { let dep_name = dependency.package_name(); if seen.insert((dep_name, None)) { queue.push_back((dep_name, None)); } for extra in dependency.extra() { if seen.insert((dep_name, Some(extra))) { queue.push_back((dep_name, Some(extra))); } } } } } while let Some((package_name, extra)) = queue.pop_front() { if lock.members().contains(package_name) { required_members.insert(package_name); } let Some(package) = packages.get(package_name) else { continue; }; let Some(dependencies) = extra .map(|extra_name| { package .optional_dependencies() .get(extra_name) .map(Vec::as_slice) }) .unwrap_or(Some(package.dependencies())) else { continue; }; for dependency in dependencies { let name = dependency.package_name(); if seen.insert((name, None)) { queue.push_back((name, None)); } for extra in dependency.extra() { if seen.insert((name, Some(extra))) { queue.push_back((name, Some(extra))); } } } } required_members } Self::Workspace { lock, .. } | Self::NonProjectWorkspace { lock, .. } => { // Return all workspace members lock.members().iter().collect() } Self::Script { .. } => { // Scripts don't have workspace members BTreeSet::new() } } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/project/environment.rs
crates/uv/src/commands/project/environment.rs
use std::path::Path; use tracing::debug; use crate::commands::pip::loggers::{InstallLogger, ResolveLogger}; use crate::commands::pip::operations::Modifications; use crate::commands::project::{ EnvironmentSpecification, PlatformState, ProjectError, resolve_environment, sync_environment, }; use crate::printer::Printer; use crate::settings::ResolverInstallerSettings; use uv_cache::{Cache, CacheBucket}; use uv_cache_key::{cache_digest, hash_digest}; use uv_client::BaseClientBuilder; use uv_configuration::{Concurrency, Constraints, TargetTriple}; use uv_distribution_types::{Name, Resolution}; use uv_fs::PythonExt; use uv_preview::Preview; use uv_python::{Interpreter, PythonEnvironment, canonicalize_executable}; /// An ephemeral [`PythonEnvironment`] for running an individual command. #[derive(Debug)] pub(crate) struct EphemeralEnvironment(PythonEnvironment); impl From<PythonEnvironment> for EphemeralEnvironment { fn from(environment: PythonEnvironment) -> Self { Self(environment) } } impl From<EphemeralEnvironment> for PythonEnvironment { fn from(environment: EphemeralEnvironment) -> Self { environment.0 } } impl EphemeralEnvironment { /// Set the ephemeral overlay for a Python environment. #[allow(clippy::result_large_err)] pub(crate) fn set_overlay(&self, contents: impl AsRef<[u8]>) -> Result<(), ProjectError> { let site_packages = self .0 .site_packages() .next() .ok_or(ProjectError::NoSitePackages)?; let overlay_path = site_packages.join("_uv_ephemeral_overlay.pth"); fs_err::write(overlay_path, contents)?; Ok(()) } /// Enable system site packages for a Python environment. #[allow(clippy::result_large_err)] pub(crate) fn set_system_site_packages(&self) -> Result<(), ProjectError> { self.0 .set_pyvenv_cfg("include-system-site-packages", "true")?; Ok(()) } /// Set the `extends-environment` key in the `pyvenv.cfg` file to the given path. /// /// Ephemeral environments created by `uv run --with` extend a parent (virtual or system) /// environment by adding a `.pth` file to the ephemeral environment's `site-packages` /// directory. The `pth` file contains Python code to dynamically add the parent /// environment's `site-packages` directory to Python's import search paths in addition to /// the ephemeral environment's `site-packages` directory. This works well at runtime, but /// is too dynamic for static analysis tools like ty to understand. As such, we /// additionally write the `sys.prefix` of the parent environment to the /// `extends-environment` key of the ephemeral environment's `pyvenv.cfg` file, making it /// easier for these tools to statically and reliably understand the relationship between /// the two environments. #[allow(clippy::result_large_err)] pub(crate) fn set_parent_environment( &self, parent_environment_sys_prefix: &Path, ) -> Result<(), ProjectError> { self.0.set_pyvenv_cfg( "extends-environment", &parent_environment_sys_prefix.escape_for_python(), )?; Ok(()) } /// Returns the path to the environment's scripts directory. pub(crate) fn scripts(&self) -> &Path { self.0.scripts() } /// Returns the path to the environment's Python executable. pub(crate) fn sys_executable(&self) -> &Path { self.0.interpreter().sys_executable() } pub(crate) fn sys_prefix(&self) -> &Path { self.0.interpreter().sys_prefix() } } /// A [`PythonEnvironment`] stored in the cache. #[derive(Debug)] pub(crate) struct CachedEnvironment(PythonEnvironment); impl From<CachedEnvironment> for PythonEnvironment { fn from(environment: CachedEnvironment) -> Self { environment.0 } } impl CachedEnvironment { /// Get or create an [`CachedEnvironment`] based on a given set of requirements. pub(crate) async fn from_spec( spec: EnvironmentSpecification<'_>, build_constraints: Constraints, interpreter: &Interpreter, python_platform: Option<&TargetTriple>, settings: &ResolverInstallerSettings, client_builder: &BaseClientBuilder<'_>, state: &PlatformState, resolve: Box<dyn ResolveLogger>, install: Box<dyn InstallLogger>, installer_metadata: bool, concurrency: Concurrency, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<Self, ProjectError> { let interpreter = Self::base_interpreter(interpreter, cache)?; // Resolve the requirements with the interpreter. let resolution = Resolution::from( resolve_environment( spec, &interpreter, python_platform, build_constraints.clone(), &settings.resolver, client_builder, state, resolve, concurrency, cache, printer, preview, ) .await?, ); // Hash the resolution by hashing the generated lockfile. // TODO(charlie): If the resolution contains any mutable metadata (like a path or URL // dependency), skip this step. let resolution_hash = { let mut distributions = resolution.distributions().collect::<Vec<_>>(); distributions.sort_unstable_by_key(|dist| dist.name()); hash_digest(&distributions) }; // Construct a hash for the environment. // // Use the canonicalized base interpreter path since that's the interpreter we performed the // resolution with and the interpreter the environment will be created with. // // We cache environments independent of the environment they'd be layered on top of. The // assumption is such that the environment will _not_ be modified by the user or uv; // otherwise, we risk cache poisoning. For example, if we were to write a `.pth` file to // the cached environment, it would be shared across all projects that use the same // interpreter and the same cached dependencies. // // TODO(zanieb): We should include the version of the base interpreter in the hash, so if // the interpreter at the canonicalized path changes versions we construct a new // environment. let interpreter_hash = cache_digest(&canonicalize_executable(interpreter.sys_executable())?); // Search in the content-addressed cache. let cache_entry = cache.entry(CacheBucket::Environments, interpreter_hash, resolution_hash); if let Ok(root) = cache.resolve_link(cache_entry.path()) { if let Ok(environment) = PythonEnvironment::from_root(root, cache) { return Ok(Self(environment)); } } // Create the environment in the cache, then relocate it to its content-addressed location. let temp_dir = cache.venv_dir()?; let venv = uv_virtualenv::create_venv( temp_dir.path(), interpreter, uv_virtualenv::Prompt::None, false, uv_virtualenv::OnExisting::Remove(uv_virtualenv::RemovalReason::TemporaryEnvironment), true, false, false, preview, )?; sync_environment( venv, &resolution, Modifications::Exact, build_constraints, settings.into(), client_builder, state, install, installer_metadata, concurrency, cache, printer, preview, ) .await?; // Now that the environment is complete, sync it to its content-addressed location. let id = cache.persist(temp_dir.keep(), cache_entry.path()).await?; let root = cache.archive(&id); Ok(Self(PythonEnvironment::from_root(root, cache)?)) } /// Return the [`Interpreter`] to use for the cached environment, based on a given /// [`Interpreter`]. /// /// When caching, always use the base interpreter, rather than that of the virtual /// environment. fn base_interpreter( interpreter: &Interpreter, cache: &Cache, ) -> Result<Interpreter, uv_python::Error> { let base_python = if cfg!(unix) { interpreter.find_base_python()? } else { interpreter.to_base_python()? }; if base_python == interpreter.sys_executable() { debug!( "Caching via base interpreter: `{}`", interpreter.sys_executable().display() ); Ok(interpreter.clone()) } else { let base_interpreter = Interpreter::query(base_python, cache)?; debug!( "Caching via base interpreter: `{}`", base_interpreter.sys_executable().display() ); Ok(base_interpreter) } } }
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/src/commands/project/version.rs
crates/uv/src/commands/project/version.rs
use std::fmt::Write; use std::path::Path; use std::str::FromStr; use anyhow::{Context, Result, anyhow}; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::Cache; use uv_cli::version::VersionInfo; use uv_cli::{VersionBump, VersionBumpSpec, VersionFormat}; use uv_client::BaseClientBuilder; use uv_configuration::{ Concurrency, DependencyGroups, DependencyGroupsWithDefaults, DryRun, ExtrasSpecification, InstallOptions, }; use uv_fs::Simplified; use uv_normalize::DefaultExtras; use uv_normalize::PackageName; use uv_pep440::{BumpCommand, PrereleaseKind, Version}; use uv_preview::Preview; use uv_python::{PythonDownloads, PythonPreference, PythonRequest}; use uv_settings::PythonInstallMirrors; use uv_workspace::pyproject_mut::Error; use uv_workspace::{ DiscoveryOptions, WorkspaceCache, WorkspaceError, pyproject_mut::{DependencyTarget, PyProjectTomlMut}, }; use uv_workspace::{VirtualProject, Workspace}; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger}; use crate::commands::pip::operations::Modifications; use crate::commands::project::add::{AddTarget, PythonTarget}; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::LockMode; use crate::commands::project::{ ProjectEnvironment, ProjectError, ProjectInterpreter, UniversalState, default_dependency_groups, }; use crate::commands::{ExitStatus, diagnostics, project}; use crate::printer::Printer; use crate::settings::{LockCheck, ResolverInstallerSettings}; /// Display version information for uv itself (`uv self version`) pub(crate) fn self_version( short: bool, output_format: VersionFormat, printer: Printer, ) -> Result<ExitStatus> { let version_info = uv_cli::version::uv_self_version(); print_version(version_info, None, short, output_format, printer)?; Ok(ExitStatus::Success) } /// Read or update project version (`uv version`) #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn project_version( value: Option<String>, mut bump: Vec<VersionBumpSpec>, short: bool, output_format: VersionFormat, project_dir: &Path, package: Option<PackageName>, explicit_project: bool, dry_run: bool, lock_check: LockCheck, frozen: bool, active: Option<bool>, no_sync: bool, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Read the metadata let project = find_target(project_dir, package.as_ref(), explicit_project).await?; let pyproject_path = project.root().join("pyproject.toml"); let Some(name) = project.project_name().cloned() else { return Err(anyhow!( "Missing `project.name` field in: {}", pyproject_path.user_display() )); }; // Short-circuit early for a frozen read let is_read_only = value.is_none() && bump.is_empty(); if frozen && is_read_only { return Box::pin(print_frozen_version( project, &name, project_dir, active, python, install_mirrors, &settings, client_builder, python_preference, python_downloads, concurrency, no_config, cache, short, output_format, printer, preview, )) .await; } let mut toml = PyProjectTomlMut::from_toml( project.pyproject_toml().raw.as_ref(), DependencyTarget::PyProjectToml, )?; let old_version = toml.version().map_err(|err| match err { Error::MalformedWorkspace => { if toml.has_dynamic_version() { anyhow!( "We cannot get or set dynamic project versions in: {}", pyproject_path.user_display() ) } else { anyhow!( "There is no 'project.version' field in: {}", pyproject_path.user_display() ) } } err => { anyhow!("{err}: {}", pyproject_path.user_display()) } })?; // Figure out new metadata let new_version = if let Some(value) = value { match Version::from_str(&value) { Ok(version) => Some(version), Err(err) => match &*value { "major" | "minor" | "patch" | "alpha" | "beta" | "rc" | "dev" | "post" | "stable" => { return Err(anyhow!( "Invalid version `{value}`, did you mean to pass `--bump {value}`?" )); } _ => { return Err(err)?; } }, } } else if !bump.is_empty() { // While we can rationalize many of these combinations of operations together, // we want to conservatively refuse to support any of them until users demand it. // // The most complex thing we *do* allow is `--bump major --bump beta --bump dev` // because that makes perfect sense and is reasonable to do. let release_components: Vec<_> = bump .iter() .filter(|spec| { matches!( spec.bump, VersionBump::Major | VersionBump::Minor | VersionBump::Patch ) }) .collect(); let prerelease_components: Vec<_> = bump .iter() .filter(|spec| { matches!( spec.bump, VersionBump::Alpha | VersionBump::Beta | VersionBump::Rc | VersionBump::Dev ) }) .collect(); let post_count = bump .iter() .filter(|spec| spec.bump == VersionBump::Post) .count(); let stable_count = bump .iter() .filter(|spec| spec.bump == VersionBump::Stable) .count(); // Very little reason to do "bump to stable" and then do other things, // even if we can make sense of it. if stable_count > 0 && bump.len() > 1 { let components = bump .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", "); return Err(anyhow!( "`--bump stable` cannot be used with another `--bump` value, got: {components}" )); } // Very little reason to "bump to post" and then do other things, // how is it a post-release otherwise? if post_count > 0 && bump.len() > 1 { let components = bump .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", "); return Err(anyhow!( "`--bump post` cannot be used with another `--bump` value, got: {components}" )); } // `--bump major --bump minor` makes perfect sense (1.2.3 => 2.1.0) // ...but it's weird and probably a mistake? // `--bump major --bump major` perfect sense (1.2.3 => 3.0.0) // ...but it's weird and probably a mistake? if release_components.len() > 1 { let components = release_components .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", "); return Err(anyhow!( "Only one release version component can be provided to `--bump`, got: {components}" )); } // `--bump alpha --bump beta` is basically completely incoherent // `--bump beta --bump beta` makes perfect sense (1.2.3b4 => 1.2.3b6) // ...but it's weird and probably a mistake? // `--bump beta --bump dev` makes perfect sense (1.2.3 => 1.2.3b1.dev1) // ...but we want to discourage mixing `dev` with pre-releases if prerelease_components.len() > 1 { let components = prerelease_components .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", "); return Err(anyhow!( "Only one pre-release version component can be provided to `--bump`, got: {components}" )); } // Sort the given commands so the user doesn't have to care about // the ordering of `--bump minor --bump beta` (only one ordering is ever useful) bump.sort(); // Apply all the bumps let mut new_version = old_version.clone(); for spec in &bump { match spec.bump { VersionBump::Major => new_version.bump(BumpCommand::BumpRelease { index: 0, value: spec.value, }), VersionBump::Minor => new_version.bump(BumpCommand::BumpRelease { index: 1, value: spec.value, }), VersionBump::Patch => new_version.bump(BumpCommand::BumpRelease { index: 2, value: spec.value, }), VersionBump::Stable => new_version.bump(BumpCommand::MakeStable), VersionBump::Alpha => new_version.bump(BumpCommand::BumpPrerelease { kind: PrereleaseKind::Alpha, value: spec.value, }), VersionBump::Beta => new_version.bump(BumpCommand::BumpPrerelease { kind: PrereleaseKind::Beta, value: spec.value, }), VersionBump::Rc => new_version.bump(BumpCommand::BumpPrerelease { kind: PrereleaseKind::Rc, value: spec.value, }), VersionBump::Post => new_version.bump(BumpCommand::BumpPost { value: spec.value }), VersionBump::Dev => new_version.bump(BumpCommand::BumpDev { value: spec.value }), } } if new_version <= old_version { if old_version.is_stable() && new_version.is_pre() { return Err(anyhow!( "{old_version} => {new_version} didn't increase the version; when bumping to a pre-release version you also need to increase a release version component, e.g., with `--bump <major|minor|patch>`" )); } return Err(anyhow!( "{old_version} => {new_version} didn't increase the version; provide the exact version to force an update" )); } Some(new_version) } else { None }; // Update the toml and lock let status = if dry_run { ExitStatus::Success } else if let Some(new_version) = &new_version { let project = update_project(project, new_version, &mut toml, &pyproject_path)?; Box::pin(lock_and_sync( project, project_dir, lock_check, frozen, active, no_sync, python, install_mirrors, &settings, client_builder, python_preference, python_downloads, installer_metadata, concurrency, no_config, cache, printer, preview, )) .await? } else { debug!("No changes to version; skipping update"); ExitStatus::Success }; // Report the results let old_version = VersionInfo::new(Some(&name), &old_version); let new_version = new_version.map(|version| VersionInfo::new(Some(&name), &version)); print_version(old_version, new_version, short, output_format, printer)?; Ok(status) } /// Add hint to use `uv self version` when workspace discovery fails due to missing pyproject.toml /// and --project was not explicitly passed fn hint_uv_self_version(err: WorkspaceError, explicit_project: bool) -> anyhow::Error { if matches!(err, WorkspaceError::MissingPyprojectToml) && !explicit_project { anyhow!( "{}\n\n{}{} If you meant to view uv's version, use `{}` instead", err, "hint".bold().cyan(), ":".bold(), "uv self version".green() ) } else { err.into() } } /// Find the pyproject.toml we're modifying /// /// Note that `uv version` never needs to support PEP 723 scripts, as those are unversioned. async fn find_target( project_dir: &Path, package: Option<&PackageName>, explicit_project: bool, ) -> Result<VirtualProject> { // Find the project in the workspace. // No workspace caching since `uv version` changes the workspace definition. let project = if let Some(package) = package { VirtualProject::Project( Workspace::discover( project_dir, &DiscoveryOptions { project: uv_workspace::ProjectDiscovery::Required, ..DiscoveryOptions::default() }, &WorkspaceCache::default(), ) .await .map_err(|err| hint_uv_self_version(err, explicit_project))? .with_current_project(package.clone()) .with_context(|| format!("Package `{package}` not found in workspace"))?, ) } else { VirtualProject::discover( project_dir, &DiscoveryOptions { project: uv_workspace::ProjectDiscovery::Required, ..DiscoveryOptions::default() }, &WorkspaceCache::default(), ) .await .map_err(|err| hint_uv_self_version(err, explicit_project))? }; Ok(project) } /// Update the pyproject.toml on-disk and in-memory with a new version fn update_project( project: VirtualProject, new_version: &Version, toml: &mut PyProjectTomlMut, pyproject_path: &Path, ) -> Result<VirtualProject> { // Save to disk toml.set_version(new_version)?; let content = toml.to_string(); fs_err::write(pyproject_path, &content)?; // Update the `pyproject.toml` in-memory. let project = project .with_pyproject_toml(toml::from_str(&content).map_err(ProjectError::PyprojectTomlParse)?)? .ok_or(ProjectError::PyprojectTomlUpdate)?; Ok(project) } /// Do the minimal work to try to find the package in the lockfile and print its version async fn print_frozen_version( project: VirtualProject, name: &PackageName, project_dir: &Path, active: Option<bool>, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: &ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, no_config: bool, cache: &Cache, short: bool, output_format: VersionFormat, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Discover the interpreter (this is the same interpreter --no-sync uses). let interpreter = ProjectInterpreter::discover( project.workspace(), project_dir, &DependencyGroupsWithDefaults::none(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); let target = AddTarget::Project(project, Box::new(PythonTarget::Interpreter(interpreter))); // Initialize any shared state. let state = UniversalState::default(); // Lock and sync the environment, if necessary. let lock = match Box::pin( project::lock::LockOperation::new( LockMode::Frozen, &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &WorkspaceCache::default(), printer, preview, ) .execute((&target).into()), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // Try to find the package of interest in the lock let Some(package) = lock .packages() .iter() .find(|package| package.name() == name) else { return Err(anyhow!( "Failed to find the {name}'s version in the frozen lockfile" )); }; let Some(version) = package.version() else { return Err(anyhow!( "Failed to find the {name}'s version in the frozen lockfile" )); }; // Finally, print! let old_version = VersionInfo::new(Some(name), version); print_version(old_version, None, short, output_format, printer)?; Ok(ExitStatus::Success) } /// Re-lock and re-sync the project after a series of edits. #[allow(clippy::fn_params_excessive_bools)] async fn lock_and_sync( project: VirtualProject, project_dir: &Path, lock_check: LockCheck, frozen: bool, active: Option<bool>, no_sync: bool, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: &ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // If frozen, don't touch the lock or sync at all if frozen { return Ok(ExitStatus::Success); } // Determine the groups and extras that should be enabled. let default_groups = default_dependency_groups(project.pyproject_toml())?; let default_extras = DefaultExtras::default(); let groups = DependencyGroups::default().with_defaults(default_groups); let extras = ExtrasSpecification::default().with_defaults(default_extras); let install_options = InstallOptions::default(); // Convert to an `AddTarget` by attaching the appropriate interpreter or environment. let target = if no_sync { // Discover the interpreter. let interpreter = ProjectInterpreter::discover( project.workspace(), project_dir, &groups, python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); AddTarget::Project(project, Box::new(PythonTarget::Interpreter(interpreter))) } else { // Discover or create the virtual environment. let environment = ProjectEnvironment::get_or_init( project.workspace(), &groups, python.as_deref().map(PythonRequest::parse), &install_mirrors, &client_builder, python_preference, python_downloads, no_sync, no_config, active, cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()?; AddTarget::Project(project, Box::new(PythonTarget::Environment(environment))) }; // Determine the lock mode. let mode = if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(target.interpreter(), lock_check) } else { LockMode::Write(target.interpreter()) }; // Initialize any shared state. let state = UniversalState::default(); let workspace_cache = WorkspaceCache::default(); // Lock and sync the environment, if necessary. let lock = match Box::pin( project::lock::LockOperation::new( mode, &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &workspace_cache, printer, preview, ) .execute((&target).into()), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; let AddTarget::Project(project, environment) = target else { // If we're not adding to a project, exit early. return Ok(ExitStatus::Success); }; let PythonTarget::Environment(venv) = &*environment else { // If we're not syncing, exit early. return Ok(ExitStatus::Success); }; // Perform a full sync, because we don't know what exactly is affected by the version. // Identify the installation target. let target = match &project { VirtualProject::Project(project) => InstallTarget::Project { workspace: project.workspace(), name: project.project_name(), lock: &lock, }, VirtualProject::NonProject(workspace) => InstallTarget::NonProjectWorkspace { workspace, lock: &lock, }, }; let state = state.fork(); match project::sync::do_sync( target, venv, &extras, &groups, None, install_options, Modifications::Sufficient, None, settings.into(), &client_builder, &state, Box::new(DefaultInstallLogger), installer_metadata, concurrency, cache, workspace_cache, DryRun::Disabled, printer, preview, ) .await { Ok(_) => {} Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } Ok(ExitStatus::Success) } fn print_version( old_version: VersionInfo, new_version: Option<VersionInfo>, short: bool, output_format: VersionFormat, printer: Printer, ) -> Result<()> { match output_format { VersionFormat::Text => { if let Some(name) = &old_version.package_name { if !short { write!(printer.stdout(), "{name} ")?; } } if let Some(new_version) = new_version { if short { writeln!(printer.stdout(), "{}", new_version.cyan())?; } else { writeln!( printer.stdout(), "{} => {}", old_version.cyan(), new_version.cyan() )?; } } else { writeln!(printer.stdout(), "{}", old_version.cyan())?; } } VersionFormat::Json => { let final_version = new_version.unwrap_or(old_version); let string = serde_json::to_string_pretty(&final_version)?; writeln!(printer.stdout(), "{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/src/commands/project/sync.rs
crates/uv/src/commands/project/sync.rs
use std::fmt::Write; use std::ops::Deref; use std::path::Path; use std::sync::Arc; use anyhow::{Context, Result}; use itertools::Itertools; use owo_colors::OwoColorize; use serde::Serialize; use tracing::warn; use uv_cache::Cache; use uv_cli::SyncFormat; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ Concurrency, Constraints, DependencyGroups, DependencyGroupsWithDefaults, DryRun, EditableMode, ExtrasSpecification, ExtrasSpecificationWithDefaults, HashCheckingMode, InstallOptions, TargetTriple, Upgrade, }; use uv_dispatch::BuildDispatch; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::{ DirectorySourceDist, Dist, Index, Name, Requirement, Resolution, ResolvedDist, SourceDist, }; use uv_fs::{PortablePathBuf, Simplified}; use uv_installer::{InstallationStrategy, SitePackages}; use uv_normalize::{DefaultExtras, DefaultGroups, PackageName}; use uv_pep508::{MarkerTree, VersionOrUrl}; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::{ParsedArchiveUrl, ParsedGitUrl, ParsedUrl}; use uv_python::{PythonDownloads, PythonEnvironment, PythonPreference, PythonRequest}; use uv_resolver::{FlatIndex, ForkStrategy, Installable, Lock, PrereleaseMode, ResolutionMode}; use uv_scripts::Pep723Script; use uv_settings::PythonInstallMirrors; use uv_types::{BuildIsolation, HashStrategy}; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::pyproject::Source; use uv_workspace::{DiscoveryOptions, MemberDiscovery, VirtualProject, Workspace, WorkspaceCache}; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger, InstallLogger}; use crate::commands::pip::operations::{ChangedDist, Changelog, Modifications}; use crate::commands::pip::resolution_markers; use crate::commands::pip::{operations, resolution_tags}; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::{LockMode, LockOperation, LockResult}; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ EnvironmentUpdate, PlatformState, ProjectEnvironment, ProjectError, ScriptEnvironment, UniversalState, default_dependency_groups, detect_conflicts, script_extra_build_requires, script_specification, update_environment, }; use crate::commands::{ExitStatus, diagnostics}; use crate::printer::Printer; use crate::settings::{ InstallerSettingsRef, LockCheck, LockCheckSource, ResolverInstallerSettings, ResolverSettings, }; /// Sync the project environment. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn sync( project_dir: &Path, lock_check: LockCheck, frozen: bool, dry_run: DryRun, active: Option<bool>, all_packages: bool, package: Vec<PackageName>, extras: ExtrasSpecification, groups: DependencyGroups, editable: Option<EditableMode>, install_options: InstallOptions, modifications: Modifications, python: Option<String>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, python_preference: PythonPreference, python_downloads: PythonDownloads, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, script: Option<Pep723Script>, installer_metadata: bool, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, output_format: SyncFormat, ) -> Result<ExitStatus> { if preview.is_enabled(PreviewFeatures::JSON_OUTPUT) && matches!(output_format, SyncFormat::Json) { warn_user!( "The `--output-format json` option is experimental and the schema may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::JSON_OUTPUT ); } // Identify the target. let workspace_cache = WorkspaceCache::default(); let target = if let Some(script) = script { SyncTarget::Script(script) } else { // Identify the project. let project = if frozen { VirtualProject::discover( project_dir, &DiscoveryOptions { members: MemberDiscovery::None, ..DiscoveryOptions::default() }, &workspace_cache, ) .await? } else if let [name] = package.as_slice() { VirtualProject::Project( Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await? .with_current_project(name.clone()) .with_context(|| format!("Package `{name}` not found in workspace"))?, ) } else { let project = VirtualProject::discover( project_dir, &DiscoveryOptions::default(), &workspace_cache, ) .await?; for name in &package { if !project.workspace().packages().contains_key(name) { return Err(anyhow::anyhow!("Package `{name}` not found in workspace")); } } project }; // TODO(lucab): improve warning content // <https://github.com/astral-sh/uv/issues/7428> if project.workspace().pyproject_toml().has_scripts() && !project.workspace().pyproject_toml().is_package(true) { warn_user!( "Skipping installation of entry points (`project.scripts`) because this project is not packaged; to install entry points, set `tool.uv.package = true` or define a `build-system`" ); } SyncTarget::Project(project) }; // Determine the groups and extras to include. let default_groups = match &target { SyncTarget::Project(project) => default_dependency_groups(project.pyproject_toml())?, SyncTarget::Script(..) => DefaultGroups::default(), }; let default_extras = match &target { SyncTarget::Project(_project) => DefaultExtras::default(), SyncTarget::Script(..) => DefaultExtras::default(), }; let groups = groups.with_defaults(default_groups); let extras = extras.with_defaults(default_extras); // Discover or create the virtual environment. let environment = match &target { SyncTarget::Project(project) => SyncEnvironment::Project( ProjectEnvironment::get_or_init( project.workspace(), &groups, python.as_deref().map(PythonRequest::parse), &install_mirrors, &client_builder, python_preference, python_downloads, false, no_config, active, cache, dry_run, printer, preview, ) .await?, ), SyncTarget::Script(script) => SyncEnvironment::Script( ScriptEnvironment::get_or_init( script.into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, dry_run, printer, preview, ) .await?, ), }; let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); let sync_report = SyncReport { dry_run: dry_run.enabled(), environment: EnvironmentReport::from(&environment), action: SyncAction::from(&environment), target: TargetName::from(&target), changes: PackageChangesReport::default(), }; // Show the intermediate results if relevant if let Some(message) = sync_report.format(output_format) { writeln!(printer.stderr(), "{message}")?; } // Special-case: we're syncing a script that doesn't have an associated lockfile. In that case, // we don't create a lockfile, so the resolve-and-install semantics are different. if let SyncTarget::Script(script) = &target { let lockfile = LockTarget::from(script).lock_path(); if !lockfile.is_file() { if frozen { return Err(anyhow::anyhow!( "`uv sync --frozen` requires a script lockfile; run `{}` to lock the script", format!("uv lock --script {}", script.path.user_display()).green(), )); } if let LockCheck::Enabled(lock_check) = lock_check { return Err(anyhow::anyhow!( "`uv sync {lock_check}` requires a script lockfile; run `{}` to lock the script", format!("uv lock --script {}", script.path.user_display()).green(), )); } // Parse the requirements from the script. let spec = script_specification( script.into(), &settings.resolver, client_builder.credentials_cache(), )? .unwrap_or_default(); let script_extra_build_requires = script_extra_build_requires( script.into(), &settings.resolver, client_builder.credentials_cache(), )? .into_inner(); // Parse the build constraints from the script. let build_constraints = script .metadata .tool .as_ref() .and_then(|tool| { tool.uv .as_ref() .and_then(|uv| uv.build_constraint_dependencies.as_ref()) }) .map(|constraints| { Constraints::from_requirements( constraints .iter() .map(|constraint| Requirement::from(constraint.clone())), ) }); match update_environment( environment.clone(), spec, modifications, python_platform.as_ref(), build_constraints.unwrap_or_default(), script_extra_build_requires, &settings, &client_builder, &PlatformState::default(), Box::new(DefaultResolveLogger), Box::new(DefaultInstallLogger), installer_metadata, concurrency, cache, workspace_cache.clone(), dry_run, printer, preview, ) .await { Ok(EnvironmentUpdate { changelog, .. }) => { // Generate a report for the script without a lockfile let report = Report { schema: SchemaReport::default(), target: TargetName::from(&target), project: None, script: Some(ScriptReport::from(script)), sync: SyncReport { changes: PackageChangesReport::from_changelog(&changelog), ..sync_report }, lock: None, dry_run: dry_run.enabled(), }; if let Some(output) = report.format(output_format) { writeln!(printer.stdout_important(), "{output}")?; } return Ok(ExitStatus::Success); } // TODO(zanieb): We should respect `--output-format json` for the error case Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } } } // Initialize any shared state. let state = UniversalState::default(); // Determine the lock mode. let mode = if frozen { LockMode::Frozen } else if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(environment.interpreter(), lock_check) } else if dry_run.enabled() { LockMode::DryRun(environment.interpreter()) } else { LockMode::Write(environment.interpreter()) }; let lock_target = match &target { SyncTarget::Project(project) => LockTarget::from(project.workspace()), SyncTarget::Script(script) => LockTarget::from(script), }; let outcome = match Box::pin( LockOperation::new( mode, &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &workspace_cache, printer, preview, ) .execute(lock_target), ) .await { Ok(result) => Outcome::Success(result), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(ProjectError::LockMismatch(prev, cur, lock_source)) => { if dry_run.enabled() { // The lockfile is mismatched, but we're in dry-run mode. We should proceed with the // sync operation, but exit with a non-zero status. Outcome::LockMismatch(prev, cur, lock_source) } else { writeln!( printer.stderr(), "{}", ProjectError::LockMismatch(prev, cur, lock_source) .to_string() .bold() )?; return Ok(ExitStatus::Failure); } } Err(err) => return Err(err.into()), }; let lock_report = LockReport::from((&lock_target, &mode, &outcome)); if let Some(message) = lock_report.format(output_format) { writeln!(printer.stderr(), "{message}")?; } // Identify the installation target. let sync_target = identify_installation_target(&target, outcome.lock(), all_packages, &package); let state = state.fork(); // Perform the sync operation. let changelog = match do_sync( sync_target, &environment, &extras, &groups, editable, install_options, modifications, python_platform.as_ref(), (&settings).into(), &client_builder, &state, Box::new(DefaultInstallLogger), installer_metadata, concurrency, cache, workspace_cache, dry_run, printer, preview, ) .await { Ok(changelog) => changelog, Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; let report = Report { schema: SchemaReport::default(), target: TargetName::from(&target), project: target.project().map(ProjectReport::from), script: target.script().map(ScriptReport::from), sync: SyncReport { changes: PackageChangesReport::from_changelog(&changelog), ..sync_report }, lock: Some(lock_report), dry_run: dry_run.enabled(), }; if let Some(output) = report.format(output_format) { writeln!(printer.stdout_important(), "{output}")?; } match outcome { Outcome::Success(..) => Ok(ExitStatus::Success), Outcome::LockMismatch(prev, cur, lock_source) => { writeln!( printer.stderr(), "{}", ProjectError::LockMismatch(prev, cur, lock_source) .to_string() .bold() )?; Ok(ExitStatus::Failure) } } } /// The outcome of a `lock` operation within a `sync` operation. #[derive(Debug)] #[allow(clippy::large_enum_variant)] enum Outcome { /// The `lock` operation was successful. Success(LockResult), /// The `lock` operation successfully resolved, but failed due to a mismatch (e.g., with `--locked`). LockMismatch(Option<Box<Lock>>, Box<Lock>, LockCheckSource), } impl Outcome { /// Return the [`Lock`] associated with this outcome. fn lock(&self) -> &Lock { match self { Self::Success(lock) => match lock { LockResult::Changed(_, lock) => lock, LockResult::Unchanged(lock) => lock, }, Self::LockMismatch(_prev, cur, _lock_source) => cur, } } } fn identify_installation_target<'a>( target: &'a SyncTarget, lock: &'a Lock, all_packages: bool, package: &'a [PackageName], ) -> InstallTarget<'a> { match &target { SyncTarget::Project(project) => { match &project { VirtualProject::Project(project) => { if all_packages { InstallTarget::Workspace { workspace: project.workspace(), lock, } } else { match package { // By default, install the root project. [] => InstallTarget::Project { workspace: project.workspace(), name: project.project_name(), lock, }, [name] => InstallTarget::Project { workspace: project.workspace(), name, lock, }, names => InstallTarget::Projects { workspace: project.workspace(), names, lock, }, } } } VirtualProject::NonProject(workspace) => { if all_packages { InstallTarget::NonProjectWorkspace { workspace, lock } } else { match package { // By default, install the entire workspace. [] => InstallTarget::NonProjectWorkspace { workspace, lock }, [name] => InstallTarget::Project { workspace, name, lock, }, names => InstallTarget::Projects { workspace, names, lock, }, } } } } } SyncTarget::Script(script) => InstallTarget::Script { script, lock }, } } #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] enum SyncTarget { /// Sync a project environment. Project(VirtualProject), /// Sync a PEP 723 script environment. Script(Pep723Script), } impl SyncTarget { fn project(&self) -> Option<&VirtualProject> { match self { Self::Project(project) => Some(project), Self::Script(_) => None, } } fn script(&self) -> Option<&Pep723Script> { match self { Self::Project(_) => None, Self::Script(script) => Some(script), } } } #[derive(Debug)] enum SyncEnvironment { /// A Python environment for a project. Project(ProjectEnvironment), /// A Python environment for a script. Script(ScriptEnvironment), } impl SyncEnvironment { fn dry_run_target(&self) -> Option<&Path> { match self { Self::Project(env) => env.dry_run_target(), Self::Script(env) => env.dry_run_target(), } } } impl Deref for SyncEnvironment { type Target = PythonEnvironment; fn deref(&self) -> &Self::Target { match self { Self::Project(environment) => environment, Self::Script(environment) => environment, } } } /// Sync a lockfile with an environment. #[allow(clippy::fn_params_excessive_bools)] pub(super) async fn do_sync( target: InstallTarget<'_>, venv: &PythonEnvironment, extras: &ExtrasSpecificationWithDefaults, groups: &DependencyGroupsWithDefaults, editable: Option<EditableMode>, install_options: InstallOptions, modifications: Modifications, python_platform: Option<&TargetTriple>, settings: InstallerSettingsRef<'_>, client_builder: &BaseClientBuilder<'_>, state: &PlatformState, logger: Box<dyn InstallLogger>, installer_metadata: bool, concurrency: Concurrency, cache: &Cache, workspace_cache: WorkspaceCache, dry_run: DryRun, printer: Printer, preview: Preview, ) -> Result<Changelog, ProjectError> { // Extract the project settings. let InstallerSettingsRef { index_locations, index_strategy, keyring_provider, dependency_metadata, config_setting, config_settings_package, build_isolation, extra_build_dependencies, extra_build_variables, exclude_newer, link_mode, compile_bytecode, reinstall, build_options, sources, } = settings; if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } // Lower the extra build dependencies with source resolution. let extra_build_requires = match &target { InstallTarget::Workspace { workspace, .. } | InstallTarget::Project { workspace, .. } | InstallTarget::Projects { workspace, .. } | InstallTarget::NonProjectWorkspace { workspace, .. } => { LoweredExtraBuildDependencies::from_workspace( extra_build_dependencies.clone(), workspace, index_locations, sources, client_builder.credentials_cache(), )? } InstallTarget::Script { script, .. } => { // Try to get extra build dependencies from the script metadata let resolver_settings = ResolverSettings { build_options: build_options.clone(), config_setting: config_setting.clone(), config_settings_package: config_settings_package.clone(), dependency_metadata: dependency_metadata.clone(), exclude_newer: exclude_newer.clone(), fork_strategy: ForkStrategy::default(), index_locations: index_locations.clone(), index_strategy, keyring_provider, link_mode, build_isolation: build_isolation.clone(), extra_build_dependencies: extra_build_dependencies.clone(), extra_build_variables: extra_build_variables.clone(), prerelease: PrereleaseMode::default(), resolution: ResolutionMode::default(), sources, torch_backend: None, upgrade: Upgrade::default(), }; script_extra_build_requires( (*script).into(), &resolver_settings, client_builder.credentials_cache(), )? } } .into_inner(); let client_builder = client_builder.clone().keyring(keyring_provider); // Validate that the Python version is supported by the lockfile. if !target .lock() .requires_python() .contains(venv.interpreter().python_version()) { return Err(ProjectError::LockedPythonIncompatibility( venv.interpreter().python_version().clone(), target.lock().requires_python().clone(), )); } // Validate that the set of requested extras and development groups are compatible. detect_conflicts(&target, extras, groups)?; // Validate that the set of requested extras and development groups are defined in the lockfile. target.validate_extras(extras)?; target.validate_groups(groups)?; // Determine the markers to use for resolution. let marker_env = resolution_markers(None, python_platform, venv.interpreter()); // Validate that the platform is supported by the lockfile. let environments = target.lock().supported_environments(); if !environments.is_empty() { if !environments .iter() .any(|env| env.evaluate(&marker_env, &[])) { return Err(ProjectError::LockedPlatformIncompatibility( // For error reporting, we use the "simplified" // supported environments, because these correspond to // what the end user actually wrote. The non-simplified // environments, by contrast, are explicitly // constrained by `requires-python`. target .lock() .simplified_supported_environments() .into_iter() .filter_map(MarkerTree::contents) .map(|env| format!("`{env}`")) .join(", "), )); } } // Determine the tags to use for the resolution. let tags = resolution_tags(None, python_platform, venv.interpreter())?; // Read the lockfile. let resolution = target.to_resolution( &marker_env, &tags, extras, groups, build_options, &install_options, )?; // Always skip virtual projects, which shouldn't be built or installed. let resolution = apply_no_virtual_project(resolution); // If necessary, convert editable to non-editable distributions. let resolution = apply_editable_mode(resolution, editable); // Constrain any build requirements marked as `match-runtime = true`. let extra_build_requires = extra_build_requires.match_runtime(&resolution)?; // Populate credentials from the target. store_credentials_from_target(target, &client_builder); // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder, cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .markers(venv.interpreter().markers()) .platform(venv.interpreter().platform()) .build(); // Determine whether to enable build isolation. let build_isolation = match build_isolation { uv_configuration::BuildIsolation::Isolate => BuildIsolation::Isolated, uv_configuration::BuildIsolation::Shared => BuildIsolation::Shared(venv), uv_configuration::BuildIsolation::SharedPackage(packages) => { BuildIsolation::SharedPackage(venv, packages) } }; // Read the build constraints from the lockfile. let build_constraints = target.build_constraints(); // TODO(charlie): These are all default values. We should consider whether we want to make them // optional on the downstream APIs. let build_hasher = HashStrategy::default(); // Extract the hashes from the lockfile. let hasher = HashStrategy::from_resolution(&resolution, HashCheckingMode::Verify)?; // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, Some(&tags), &hasher, build_options) }; // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, cache, &build_constraints, venv.interpreter(), index_locations, &flat_index, dependency_metadata, state.clone().into_inner(), index_strategy, config_setting, config_settings_package, build_isolation, &extra_build_requires, extra_build_variables, link_mode, build_options, &build_hasher, exclude_newer.clone(), sources, workspace_cache.clone(), concurrency, preview, ); let site_packages = SitePackages::from_environment(venv)?; // Sync the environment. let changelog = operations::install( &resolution, site_packages, InstallationStrategy::Strict, modifications, reinstall, build_options, link_mode, compile_bytecode, &hasher, &tags, &client, state.in_flight(), concurrency, &build_dispatch, cache, venv, logger, installer_metadata, dry_run, printer, preview, ) .await?; Ok(changelog) } /// Filter out any virtual workspace members. fn apply_no_virtual_project(resolution: Resolution) -> Resolution { resolution.filter(|dist| { let ResolvedDist::Installable { dist, .. } = dist else { return true; }; let Dist::Source(dist) = dist.as_ref() else { return true; }; let SourceDist::Directory(dist) = dist else { return true; }; !dist.r#virtual.unwrap_or(false) }) } /// If necessary, convert any editable requirements to non-editable. fn apply_editable_mode(resolution: Resolution, editable: Option<EditableMode>) -> Resolution { match editable { // No modifications are necessary for editable mode; retain any editable distributions. None => resolution, // Filter out any non-editable distributions. Some(EditableMode::Editable) => resolution.map(|dist| { let ResolvedDist::Installable { dist, version } = dist else { return None; }; let Dist::Source(SourceDist::Directory(DirectorySourceDist { name, install_path, editable: None | Some(false), r#virtual, url, })) = dist.as_ref() else { return None; }; Some(ResolvedDist::Installable { dist: Arc::new(Dist::Source(SourceDist::Directory(DirectorySourceDist { name: name.clone(), install_path: install_path.clone(), editable: Some(true), r#virtual: *r#virtual, url: url.clone(), }))), version: version.clone(), }) }), // Filter out any editable distributions. Some(EditableMode::NonEditable) => resolution.map(|dist| { let ResolvedDist::Installable { dist, version } = dist else { return None; }; let Dist::Source(SourceDist::Directory(DirectorySourceDist { name, install_path, editable: None | Some(true), r#virtual, url, })) = dist.as_ref() else { return None; }; Some(ResolvedDist::Installable { dist: Arc::new(Dist::Source(SourceDist::Directory(DirectorySourceDist {
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/src/commands/project/lock_target.rs
crates/uv/src/commands/project/lock_target.rs
use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use itertools::Either; use uv_auth::CredentialsCache; use uv_configuration::{DependencyGroupsWithDefaults, SourceStrategy}; use uv_distribution::LoweredRequirement; use uv_distribution_types::{Index, IndexLocations, Requirement, RequiresPython}; use uv_normalize::{GroupName, PackageName}; use uv_pep508::RequirementOrigin; use uv_pypi_types::{Conflicts, SupportedEnvironments, VerbatimParsedUrl}; use uv_resolver::{Lock, LockVersion, VERSION}; use uv_scripts::Pep723Script; use uv_workspace::dependency_groups::{DependencyGroupError, FlatDependencyGroup}; use uv_workspace::{Editability, Workspace, WorkspaceMember}; use crate::commands::project::{ProjectError, find_requires_python}; /// A target that can be resolved into a lockfile. #[derive(Debug, Copy, Clone)] pub(crate) enum LockTarget<'lock> { Workspace(&'lock Workspace), Script(&'lock Pep723Script), } impl<'lock> From<&'lock Workspace> for LockTarget<'lock> { fn from(workspace: &'lock Workspace) -> Self { Self::Workspace(workspace) } } impl<'lock> From<&'lock Pep723Script> for LockTarget<'lock> { fn from(script: &'lock Pep723Script) -> Self { LockTarget::Script(script) } } impl<'lock> LockTarget<'lock> { /// Return the set of requirements that are attached to the target directly, as opposed to being /// attached to any members within the target. pub(crate) fn requirements(self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> { match self { Self::Workspace(workspace) => workspace.requirements(), Self::Script(script) => script.metadata.dependencies.clone().unwrap_or_default(), } } /// Returns the set of overrides for the [`LockTarget`]. pub(crate) fn overrides(self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> { match self { Self::Workspace(workspace) => workspace.overrides(), Self::Script(script) => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.override_dependencies.as_ref()) .into_iter() .flatten() .cloned() .collect(), } } /// Returns the set of dependency exclusions for the [`LockTarget`]. pub(crate) fn exclude_dependencies(self) -> Vec<uv_normalize::PackageName> { match self { Self::Workspace(workspace) => workspace.exclude_dependencies(), Self::Script(script) => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.exclude_dependencies.as_ref()) .into_iter() .flatten() .cloned() .collect(), } } /// Returns the set of constraints for the [`LockTarget`]. pub(crate) fn constraints(self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> { match self { Self::Workspace(workspace) => workspace.constraints(), Self::Script(script) => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.constraint_dependencies.as_ref()) .into_iter() .flatten() .cloned() .collect(), } } /// Returns the set of build constraints for the [`LockTarget`]. pub(crate) fn build_constraints(self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> { match self { Self::Workspace(workspace) => workspace.build_constraints(), Self::Script(script) => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.build_constraint_dependencies.as_ref()) .into_iter() .flatten() .cloned() .collect(), } } /// Return the dependency groups that are attached to the target directly, as opposed to being /// attached to any members within the target. pub(crate) fn dependency_groups( self, ) -> Result<BTreeMap<GroupName, FlatDependencyGroup>, DependencyGroupError> { match self { Self::Workspace(workspace) => workspace.workspace_dependency_groups(), Self::Script(_) => Ok(BTreeMap::new()), } } /// Returns the set of all members within the target. pub(crate) fn members_requirements(self) -> impl Iterator<Item = Requirement> + 'lock { match self { Self::Workspace(workspace) => Either::Left(workspace.members_requirements()), Self::Script(_) => Either::Right(std::iter::empty()), } } /// Returns the set of all dependency groups within the target. pub(crate) fn group_requirements(self) -> impl Iterator<Item = Requirement> + 'lock { match self { Self::Workspace(workspace) => Either::Left(workspace.group_requirements()), Self::Script(_) => Either::Right(std::iter::empty()), } } /// Return the list of members to include in the [`Lock`]. pub(crate) fn members(self) -> Vec<PackageName> { match self { Self::Workspace(workspace) => { let mut members = workspace.packages().keys().cloned().collect::<Vec<_>>(); members.sort(); // If this is a non-virtual project with a single member, we can omit it from the lockfile. // If any members are added or removed, it will inherently mismatch. If the member is // renamed, it will also mismatch. if members.len() == 1 && !workspace.is_non_project() { members.clear(); } members } Self::Script(_) => Vec::new(), } } /// Return the list of packages. pub(crate) fn packages(self) -> &'lock BTreeMap<PackageName, WorkspaceMember> { match self { Self::Workspace(workspace) => workspace.packages(), Self::Script(_) => { static EMPTY: BTreeMap<PackageName, WorkspaceMember> = BTreeMap::new(); &EMPTY } } } /// Return the set of required workspace members, i.e., those that are required by other /// members. pub(crate) fn required_members(self) -> &'lock BTreeMap<PackageName, Editability> { match self { Self::Workspace(workspace) => workspace.required_members(), Self::Script(_) => { static EMPTY: BTreeMap<PackageName, Editability> = BTreeMap::new(); &EMPTY } } } /// Returns the set of supported environments for the [`LockTarget`]. pub(crate) fn environments(self) -> Option<&'lock SupportedEnvironments> { match self { Self::Workspace(workspace) => workspace.environments(), Self::Script(_) => { // TODO(charlie): Add support for environments in scripts. None } } } /// Returns the set of required platforms for the [`LockTarget`]. pub(crate) fn required_environments(self) -> Option<&'lock SupportedEnvironments> { match self { Self::Workspace(workspace) => workspace.required_environments(), Self::Script(_) => { // TODO(charlie): Add support for environments in scripts. None } } } /// Returns the set of conflicts for the [`LockTarget`]. pub(crate) fn conflicts(self) -> Conflicts { match self { Self::Workspace(workspace) => workspace.conflicts(), Self::Script(_) => Conflicts::empty(), } } /// Return an iterator over the [`Index`] definitions in the [`LockTarget`]. pub(crate) fn indexes(self) -> impl Iterator<Item = &'lock Index> { match self { Self::Workspace(workspace) => Either::Left(workspace.indexes().iter().chain( workspace.packages().values().flat_map(|member| { member .pyproject_toml() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.index.as_ref()) .into_iter() .flatten() }), )), Self::Script(script) => Either::Right( script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.top_level.index.as_deref()) .into_iter() .flatten(), ), } } /// Return the `Requires-Python` bound for the [`LockTarget`]. #[allow(clippy::result_large_err)] pub(crate) fn requires_python(self) -> Result<Option<RequiresPython>, ProjectError> { match self { Self::Workspace(workspace) => { // When locking, don't try to enforce requires-python bounds that appear on groups let groups = DependencyGroupsWithDefaults::none(); find_requires_python(workspace, &groups) } Self::Script(script) => Ok(script .metadata .requires_python .as_ref() .map(RequiresPython::from_specifiers)), } } /// Return the path to the lock root. pub(crate) fn install_path(self) -> &'lock Path { match self { Self::Workspace(workspace) => workspace.install_path(), Self::Script(script) => script.path.parent().unwrap(), } } /// Return the path to the lockfile. pub(crate) fn lock_path(self) -> PathBuf { match self { // `uv.lock` Self::Workspace(workspace) => workspace.install_path().join("uv.lock"), // `script.py.lock` Self::Script(script) => { let mut file_name = match script.path.file_name() { Some(f) => f.to_os_string(), None => panic!("Script path has no file name"), }; file_name.push(".lock"); script.path.with_file_name(file_name) } } } /// Read the lockfile from the workspace. /// /// Returns `Ok(None)` if the lockfile does not exist. pub(crate) async fn read(self) -> Result<Option<Lock>, ProjectError> { match fs_err::tokio::read_to_string(self.lock_path()).await { Ok(encoded) => { match toml::from_str::<Lock>(&encoded) { Ok(lock) => { // If the lockfile uses an unsupported version, raise an error. if lock.version() != VERSION { return Err(ProjectError::UnsupportedLockVersion( VERSION, lock.version(), )); } Ok(Some(lock)) } Err(err) => { // If we failed to parse the lockfile, determine whether it's a supported // version. if let Ok(lock) = toml::from_str::<LockVersion>(&encoded) { if lock.version() != VERSION { return Err(ProjectError::UnparsableLockVersion( VERSION, lock.version(), err, )); } } Err(ProjectError::UvLockParse(err)) } } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(err) => Err(err.into()), } } /// Read the lockfile from the workspace as bytes. pub(crate) async fn read_bytes(self) -> Result<Option<Vec<u8>>, std::io::Error> { match fs_err::tokio::read(self.lock_path()).await { Ok(encoded) => Ok(Some(encoded)), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(err) => Err(err), } } /// Write the lockfile to disk. pub(crate) async fn commit(self, lock: &Lock) -> Result<(), ProjectError> { let encoded = lock.to_toml()?; fs_err::tokio::write(self.lock_path(), encoded).await?; Ok(()) } /// Lower the requirements for the [`LockTarget`], relative to the target root. pub(crate) fn lower( self, requirements: Vec<uv_pep508::Requirement<VerbatimParsedUrl>>, locations: &IndexLocations, sources: SourceStrategy, credentials_cache: &CredentialsCache, ) -> Result<Vec<Requirement>, uv_distribution::MetadataError> { match self { Self::Workspace(workspace) => { let name = workspace .pyproject_toml() .project .as_ref() .map(|project| project.name.clone()); // We model these as `build-requires`, since, like build requirements, it doesn't define extras // or dependency groups. let metadata = uv_distribution::BuildRequires::from_workspace( uv_pypi_types::BuildRequires { name, requires_dist: requirements, }, workspace, locations, sources, credentials_cache, )?; Ok(metadata .requires_dist .into_iter() .map(|requirement| requirement.with_origin(RequirementOrigin::Workspace)) .collect::<Vec<_>>()) } Self::Script(script) => { // Collect any `tool.uv.index` from the script. let empty = Vec::default(); let indexes = match sources { SourceStrategy::Enabled => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.top_level.index.as_deref()) .unwrap_or(&empty), SourceStrategy::Disabled => &empty, }; // Collect any `tool.uv.sources` from the script. let empty = BTreeMap::default(); let sources = match sources { SourceStrategy::Enabled => script .metadata .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.sources.as_ref()) .unwrap_or(&empty), SourceStrategy::Disabled => &empty, }; Ok(requirements .into_iter() .flat_map(|requirement| { let requirement_name = requirement.name.clone(); LoweredRequirement::from_non_workspace_requirement( requirement, script.path.parent().unwrap(), sources, indexes, locations, credentials_cache, ) .map(move |requirement| match requirement { Ok(requirement) => Ok(requirement.into_inner()), Err(err) => Err(uv_distribution::MetadataError::LoweringError( requirement_name.clone(), Box::new(err), )), }) }) .collect::<Result<_, _>>()?) } } } }
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/src/commands/project/lock.rs
crates/uv/src/commands/project/lock.rs
#![allow(clippy::single_match_else)] use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; use std::path::Path; use std::sync::Arc; use owo_colors::OwoColorize; use rustc_hash::{FxBuildHasher, FxHashMap}; use tracing::debug; use uv_cache::{Cache, Refresh}; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ Concurrency, Constraints, DependencyGroupsWithDefaults, DryRun, ExtrasSpecification, Reinstall, Upgrade, }; use uv_dispatch::BuildDispatch; use uv_distribution::{DistributionDatabase, LoweredExtraBuildDependencies}; use uv_distribution_types::{ DependencyMetadata, HashGeneration, Index, IndexLocations, NameRequirementSpecification, Requirement, RequiresPython, UnresolvedRequirementSpecification, }; use uv_git::ResolvedRepositoryReference; use uv_git_types::GitOid; use uv_normalize::{GroupName, PackageName}; use uv_pep440::Version; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::{ConflictKind, Conflicts, SupportedEnvironments}; use uv_python::{Interpreter, PythonDownloads, PythonEnvironment, PythonPreference, PythonRequest}; use uv_requirements::ExtrasResolver; use uv_requirements::upgrade::{LockedRequirements, read_lock_requirements}; use uv_resolver::{ FlatIndex, InMemoryIndex, Lock, Options, OptionsBuilder, Package, PythonRequirement, ResolverEnvironment, ResolverManifest, SatisfiesResult, UniversalMarker, }; use uv_scripts::Pep723Script; use uv_settings::PythonInstallMirrors; use uv_types::{BuildContext, BuildIsolation, EmptyInstalledPackages, HashStrategy}; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::{DiscoveryOptions, Editability, Workspace, WorkspaceCache, WorkspaceMember}; use crate::commands::pip::loggers::{DefaultResolveLogger, ResolveLogger, SummaryResolveLogger}; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ ProjectError, ProjectInterpreter, ScriptInterpreter, UniversalState, init_script_python_requirement, script_extra_build_requires, }; use crate::commands::reporters::{PythonDownloadReporter, ResolverReporter}; use crate::commands::{ExitStatus, ScriptPath, diagnostics, pip}; use crate::printer::Printer; use crate::settings::{LockCheck, LockCheckSource, ResolverSettings}; /// The result of running a lock operation. #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] pub(crate) enum LockResult { /// The lock was unchanged. Unchanged(Lock), /// The lock was changed. Changed(Option<Lock>, Lock), } impl LockResult { pub(crate) fn lock(&self) -> &Lock { match self { Self::Unchanged(lock) => lock, Self::Changed(_, lock) => lock, } } pub(crate) fn into_lock(self) -> Lock { match self { Self::Unchanged(lock) => lock, Self::Changed(_, lock) => lock, } } } /// Resolve the project requirements into a lockfile. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn lock( project_dir: &Path, lock_check: LockCheck, frozen: bool, dry_run: DryRun, refresh: Refresh, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: ResolverSettings, client_builder: BaseClientBuilder<'_>, script: Option<ScriptPath>, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> anyhow::Result<ExitStatus> { // If necessary, initialize the PEP 723 script. let script = match script { Some(ScriptPath::Path(path)) => { let reporter = PythonDownloadReporter::single(printer); let requires_python = init_script_python_requirement( python.as_deref(), &install_mirrors, project_dir, false, python_preference, python_downloads, no_config, &client_builder, cache, &reporter, preview, ) .await?; Some(Pep723Script::init(&path, requires_python.specifiers()).await?) } Some(ScriptPath::Script(script)) => Some(script), None => None, }; // Find the project requirements. let workspace_cache = WorkspaceCache::default(); let workspace; let target = if let Some(script) = script.as_ref() { LockTarget::Script(script) } else { workspace = Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await?; LockTarget::Workspace(&workspace) }; // Determine the lock mode. let interpreter; let mode = if frozen { LockMode::Frozen } else { interpreter = match target { LockTarget::Workspace(workspace) => ProjectInterpreter::discover( workspace, project_dir, // Don't enable any groups' requires-python for interpreter discovery &DependencyGroupsWithDefaults::none(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, Some(false), cache, printer, preview, ) .await? .into_interpreter(), LockTarget::Script(script) => ScriptInterpreter::discover( script.into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, Some(false), cache, printer, preview, ) .await? .into_interpreter(), }; if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(&interpreter, lock_check) } else if dry_run.enabled() { LockMode::DryRun(&interpreter) } else { LockMode::Write(&interpreter) } }; // Initialize any shared state. let state = UniversalState::default(); // Perform the lock operation. match Box::pin( LockOperation::new( mode, &settings, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &workspace_cache, printer, preview, ) .with_refresh(&refresh) .execute(target), ) .await { Ok(lock) => { if dry_run.enabled() { // In `--dry-run` mode, show all changes. if let LockResult::Changed(previous, lock) = &lock { let mut changed = false; for event in LockEvent::detect_changes(previous.as_ref(), lock, dry_run) { changed = true; writeln!(printer.stderr(), "{event}")?; } // If we didn't report any version changes, but the lockfile changed, report back. if !changed { writeln!(printer.stderr(), "{}", "Lockfile changes detected".bold())?; } } else { writeln!( printer.stderr(), "{}", "No lockfile changes detected".bold() )?; } } else { if let LockResult::Changed(Some(previous), lock) = &lock { for event in LockEvent::detect_changes(Some(previous), lock, dry_run) { writeln!(printer.stderr(), "{event}")?; } } } Ok(ExitStatus::Success) } Err(err @ ProjectError::LockMismatch(..)) => { writeln!(printer.stderr(), "{}", err.to_string().bold())?; Ok(ExitStatus::Failure) } Err(ProjectError::Operation(err)) => { diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())) } Err(err) => Err(err.into()), } } #[derive(Debug, Clone, Copy)] pub(super) enum LockMode<'env> { /// Write the lockfile to disk. Write(&'env Interpreter), /// Perform a resolution, but don't write the lockfile to disk. DryRun(&'env Interpreter), /// Error if the lockfile is not up-to-date with the project requirements. Locked(&'env Interpreter, LockCheckSource), /// Use the existing lockfile without performing a resolution. Frozen, } /// A lock operation. pub(super) struct LockOperation<'env> { mode: LockMode<'env>, constraints: Vec<NameRequirementSpecification>, refresh: Option<&'env Refresh>, settings: &'env ResolverSettings, client_builder: &'env BaseClientBuilder<'env>, state: &'env UniversalState, logger: Box<dyn ResolveLogger>, concurrency: Concurrency, cache: &'env Cache, workspace_cache: &'env WorkspaceCache, printer: Printer, preview: Preview, } impl<'env> LockOperation<'env> { /// Initialize a [`LockOperation`]. pub(super) fn new( mode: LockMode<'env>, settings: &'env ResolverSettings, client_builder: &'env BaseClientBuilder<'env>, state: &'env UniversalState, logger: Box<dyn ResolveLogger>, concurrency: Concurrency, cache: &'env Cache, workspace_cache: &'env WorkspaceCache, printer: Printer, preview: Preview, ) -> Self { Self { mode, constraints: vec![], refresh: None, settings, client_builder, state, logger, concurrency, cache, workspace_cache, printer, preview, } } /// Set the external constraints for the [`LockOperation`]. #[must_use] pub(super) fn with_constraints( mut self, constraints: Vec<NameRequirementSpecification>, ) -> Self { self.constraints = constraints; self } /// Set the refresh strategy for the [`LockOperation`]. #[must_use] pub(super) fn with_refresh(mut self, refresh: &'env Refresh) -> Self { self.refresh = Some(refresh); self } /// Perform a [`LockOperation`]. pub(super) async fn execute(self, target: LockTarget<'_>) -> Result<LockResult, ProjectError> { match self.mode { LockMode::Frozen => { // Read the existing lockfile, but don't attempt to lock the project. let existing = target .read() .await? .ok_or_else(|| ProjectError::MissingLockfile)?; // Check if the discovered workspace members match the locked workspace members. if let LockTarget::Workspace(workspace) = target { for package_name in workspace.packages().keys() { existing .find_by_name(package_name) .map_err(|_| ProjectError::LockWorkspaceMismatch(package_name.clone()))? .ok_or_else(|| { ProjectError::LockWorkspaceMismatch(package_name.clone()) })?; } } Ok(LockResult::Unchanged(existing)) } LockMode::Locked(interpreter, lock_source) => { // Read the existing lockfile. let existing = target .read() .await? .ok_or_else(|| ProjectError::MissingLockfile)?; // Perform the lock operation, but don't write the lockfile to disk. let result = Box::pin(do_lock( target, interpreter, Some(existing), self.constraints, self.refresh, self.settings, self.client_builder, self.state, self.logger, self.concurrency, self.cache, self.workspace_cache, self.printer, self.preview, )) .await?; // If the lockfile changed, return an error. if let LockResult::Changed(prev, cur) = result { return Err(ProjectError::LockMismatch( prev.map(Box::new), Box::new(cur), lock_source, )); } Ok(result) } LockMode::Write(interpreter) | LockMode::DryRun(interpreter) => { // Read the existing lockfile. let existing = match target.read().await { Ok(Some(existing)) => Some(existing), Ok(None) => None, Err(ProjectError::Lock(err)) => { warn_user!( "Failed to read existing lockfile; ignoring locked requirements: {err}" ); None } Err(err) => return Err(err), }; // Perform the lock operation. let result = Box::pin(do_lock( target, interpreter, existing, self.constraints, self.refresh, self.settings, self.client_builder, self.state, self.logger, self.concurrency, self.cache, self.workspace_cache, self.printer, self.preview, )) .await?; // If the lockfile changed, write it to disk. if !matches!(self.mode, LockMode::DryRun(_)) { if let LockResult::Changed(_, lock) = &result { target.commit(lock).await?; } } Ok(result) } } } } /// Lock the project requirements into a lockfile. async fn do_lock( target: LockTarget<'_>, interpreter: &Interpreter, existing_lock: Option<Lock>, external: Vec<NameRequirementSpecification>, refresh: Option<&Refresh>, settings: &ResolverSettings, client_builder: &BaseClientBuilder<'_>, state: &UniversalState, logger: Box<dyn ResolveLogger>, concurrency: Concurrency, cache: &Cache, workspace_cache: &WorkspaceCache, printer: Printer, preview: Preview, ) -> Result<LockResult, ProjectError> { let start = std::time::Instant::now(); // Extract the project settings. let ResolverSettings { index_locations, index_strategy, keyring_provider, resolution, prerelease, fork_strategy, dependency_metadata, config_setting, config_settings_package, build_isolation, extra_build_dependencies, extra_build_variables, exclude_newer, link_mode, upgrade, build_options, sources, torch_backend: _, } = settings; if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } // Collect the requirements, etc. let members = target.members(); let packages = target.packages(); let required_members = target.required_members(); let requirements = target.requirements(); let overrides = target.overrides(); let excludes = target.exclude_dependencies(); let constraints = target.constraints(); let build_constraints = target.build_constraints(); let dependency_groups = target.dependency_groups()?; let source_trees = vec![]; // If necessary, lower the overrides and constraints. let requirements = target.lower( requirements, index_locations, *sources, client_builder.credentials_cache(), )?; let overrides = target.lower( overrides, index_locations, *sources, client_builder.credentials_cache(), )?; let constraints = target.lower( constraints, index_locations, *sources, client_builder.credentials_cache(), )?; let build_constraints = target.lower( build_constraints, index_locations, *sources, client_builder.credentials_cache(), )?; let dependency_groups = dependency_groups .into_iter() .map(|(name, group)| { let requirements = target.lower( group.requirements, index_locations, *sources, client_builder.credentials_cache(), )?; Ok((name, requirements)) }) .collect::<Result<BTreeMap<_, _>, ProjectError>>()?; // Collect the conflicts. let mut conflicts = target.conflicts(); if let LockTarget::Workspace(workspace) = target { if let Some(groups) = &workspace.pyproject_toml().dependency_groups { if let Some(project) = &workspace.pyproject_toml().project { conflicts.expand_transitive_group_includes(&project.name, groups); } } } // Check if any conflicts contain project-level conflicts if !preview.is_enabled(PreviewFeatures::PACKAGE_CONFLICTS) && conflicts.iter().any(|set| { set.iter() .any(|item| matches!(item.kind(), ConflictKind::Project)) }) { warn_user_once!( "Declaring conflicts for packages (`package = ...`) is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::PACKAGE_CONFLICTS ); } // Collect the list of supported environments. let environments = { let environments = target.environments(); // Ensure that the environments are disjoint. if let Some(environments) = &environments { for (lhs, rhs) in environments .as_markers() .iter() .zip(environments.as_markers().iter().skip(1)) { if !lhs.is_disjoint(*rhs) { let mut hint = lhs.negate(); hint.and(*rhs); let lhs = lhs .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); let rhs = rhs .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); let hint = hint .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); return Err(ProjectError::OverlappingMarkers(lhs, rhs, hint)); } } } environments }; // Collect the list of required platforms. let required_environments = if let Some(required_environments) = target.required_environments() { // Ensure that the environments are disjoint. for (lhs, rhs) in required_environments .as_markers() .iter() .zip(required_environments.as_markers().iter().skip(1)) { if !lhs.is_disjoint(*rhs) { let mut hint = lhs.negate(); hint.and(*rhs); let lhs = lhs .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); let rhs = rhs .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); let hint = hint .contents() .map(|contents| contents.to_string()) .unwrap_or_else(|| "true".to_string()); return Err(ProjectError::OverlappingMarkers(lhs, rhs, hint)); } } Some(required_environments) } else { None }; // Determine the supported Python range. If no range is defined, and warn and default to the // current minor version. let requires_python = target.requires_python()?; let requires_python = if let Some(requires_python) = requires_python { if requires_python.is_unbounded() { let default = RequiresPython::greater_than_equal_version(&interpreter.python_minor_version()); warn_user_once!( "The workspace `requires-python` value (`{requires_python}`) does not contain a lower bound. Add a lower bound to indicate the minimum compatible Python version (e.g., `{default}`)." ); } else if requires_python.is_exact_without_patch() { warn_user_once!( "The workspace `requires-python` value (`{requires_python}`) contains an exact match without a patch version. When omitted, the patch version is implicitly `0` (e.g., `{requires_python}.0`). Did you mean `{requires_python}.*`?" ); } requires_python } else { let default = RequiresPython::greater_than_equal_version(&interpreter.python_minor_version()); warn_user_once!( "No `requires-python` value found in the workspace. Defaulting to `{default}`." ); default }; // If any of the forks are incompatible with the Python requirement, error. for environment in environments .map(SupportedEnvironments::as_markers) .into_iter() .flatten() .copied() { if requires_python.to_marker_tree().is_disjoint(environment) { return if let Some(contents) = environment.contents() { Err(ProjectError::DisjointEnvironment( contents, requires_python.specifiers().clone(), )) } else { Err(ProjectError::EmptyEnvironment) }; } } // Determine the Python requirement. let python_requirement = PythonRequirement::from_requires_python(interpreter, requires_python.clone()); // Initialize the client. let client_builder = client_builder.clone().keyring(*keyring_provider); for index in target.indexes() { if let Some(credentials) = index.credentials() { if let Some(root_url) = index.root_url() { client_builder.store_credentials(&root_url, credentials.clone()); } client_builder.store_credentials(index.raw_url(), credentials); } } // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder, cache.clone()) .index_locations(index_locations.clone()) .index_strategy(*index_strategy) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Determine whether to enable build isolation. let environment; let build_isolation = match build_isolation { uv_configuration::BuildIsolation::Isolate => BuildIsolation::Isolated, uv_configuration::BuildIsolation::Shared => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); BuildIsolation::Shared(&environment) } uv_configuration::BuildIsolation::SharedPackage(packages) => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); BuildIsolation::SharedPackage(&environment, packages) } }; let options = OptionsBuilder::new() .resolution_mode(*resolution) .prerelease_mode(*prerelease) .fork_strategy(*fork_strategy) .exclude_newer(exclude_newer.clone()) .index_strategy(*index_strategy) .build_options(build_options.clone()) .required_environments(required_environments.cloned().unwrap_or_default()) .build(); let hasher = HashStrategy::Generate(HashGeneration::Url); // TODO(charlie): These are all default values. We should consider whether we want to make them // optional on the downstream APIs. let build_hasher = HashStrategy::default(); let extras = ExtrasSpecification::default(); let groups = BTreeMap::new(); // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, None, &hasher, build_options) }; // Lower the extra build dependencies. let extra_build_requires = match &target { LockTarget::Workspace(workspace) => LoweredExtraBuildDependencies::from_workspace( extra_build_dependencies.clone(), workspace, index_locations, *sources, client.credentials_cache(), )?, LockTarget::Script(script) => { // Try to get extra build dependencies from the script metadata script_extra_build_requires((*script).into(), settings, client.credentials_cache())? } } .into_inner(); // Convert to the `Constraints` format. let dispatch_constraints = Constraints::from_requirements(build_constraints.iter().cloned()); // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, cache, &dispatch_constraints, interpreter, index_locations, &flat_index, dependency_metadata, state.fork().into_inner(), *index_strategy, config_setting, config_settings_package, build_isolation, &extra_build_requires, extra_build_variables, *link_mode, build_options, &build_hasher, exclude_newer.clone(), *sources, workspace_cache.clone(), concurrency, preview, ); let database = DistributionDatabase::new(&client, &build_dispatch, concurrency.downloads); // If any of the resolution-determining settings changed, invalidate the lock. let existing_lock = if let Some(existing_lock) = existing_lock { match ValidatedLock::validate( existing_lock, target.install_path(), packages, &members, required_members, &requirements, &dependency_groups, &constraints, &overrides, &excludes, &build_constraints, &conflicts, environments, required_environments, dependency_metadata, interpreter, &requires_python, index_locations, upgrade, refresh, &options, &hasher, state.index(), &database, printer, ) .await { Ok(result) => Some(result), Err(ProjectError::Lock(err)) if err.is_resolution() => { // Resolver errors are not recoverable, as such errors can leave the resolver in a // broken state. Specifically, tasks that fail with an error can be left as pending. return Err(ProjectError::Lock(err)); } Err(err) => { warn_user!("Failed to validate existing lockfile: {err}"); None } } } else { None }; match existing_lock { // Resolution from the lockfile succeeded. Some(ValidatedLock::Satisfies(lock)) => { // Print the success message after completing resolution. logger.on_complete(lock.len(), start, printer)?; Ok(LockResult::Unchanged(lock)) } // The lockfile did not contain enough information to obtain a resolution, fallback // to a fresh resolve. _ => { // Determine whether we can reuse the existing package versions. let versions_lock = existing_lock.as_ref().and_then(|lock| match &lock { ValidatedLock::Satisfies(lock) => Some(lock), ValidatedLock::Preferable(lock) => Some(lock), ValidatedLock::Versions(lock) => Some(lock), ValidatedLock::Unusable(_) => None, }); // If an existing lockfile exists, build up a set of preferences. let LockedRequirements { preferences, git } = versions_lock .map(|lock| read_lock_requirements(lock, target.install_path(), upgrade)) .transpose()? .unwrap_or_default(); // Populate the Git resolver. for ResolvedRepositoryReference { reference, sha } in git { debug!("Inserting Git reference into resolver: `{reference:?}` at `{sha}`"); state.git().insert(reference, sha); } // Determine whether we can reuse the existing package forks. let forks_lock = existing_lock.as_ref().and_then(|lock| match &lock { ValidatedLock::Satisfies(lock) => Some(lock), ValidatedLock::Preferable(lock) => Some(lock), ValidatedLock::Versions(_) => None, ValidatedLock::Unusable(_) => None, }); // When we run the same resolution from the lockfile again, we could get a different result the // second time due to the preferences causing us to skip a fork point (see the // `preferences-dependent-forking` packse scenario). To avoid this, we store the forks in the // lockfile. We read those after all the lockfile filters, to allow the forks to change when // the environment changed, e.g. the python bound check above can lead to different forking. let resolver_env = ResolverEnvironment::universal( forks_lock .map(|lock| { lock.fork_markers() .iter() .copied() .map(UniversalMarker::combined) .collect() }) .unwrap_or_else(|| { environments .cloned() .map(SupportedEnvironments::into_markers) .unwrap_or_default() }), ); // Resolve the requirements. let resolution = pip::operations::resolve( ExtrasResolver::new(&hasher, state.index(), database) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(target.members_requirements()) .await .map_err(|err| ProjectError::Operation(err.into()))? .into_iter() .chain(target.group_requirements()) .chain(requirements.iter().cloned()) .chain( dependency_groups .values() .flat_map(|requirements| requirements.iter().cloned()), ) .map(UnresolvedRequirementSpecification::from)
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/src/commands/project/tree.rs
crates/uv/src/commands/project/tree.rs
use std::path::Path; use anstream::print; use anyhow::{Error, Result}; use futures::StreamExt; use tokio::sync::Semaphore; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; use uv_client::{BaseClientBuilder, RegistryClientBuilder}; use uv_configuration::{Concurrency, DependencyGroups, TargetTriple}; use uv_distribution_types::IndexCapabilities; use uv_normalize::DefaultGroups; use uv_normalize::PackageName; use uv_preview::Preview; use uv_python::{PythonDownloads, PythonPreference, PythonRequest, PythonVersion}; use uv_resolver::{PackageMap, TreeDisplay}; use uv_scripts::Pep723Script; use uv_settings::PythonInstallMirrors; use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache}; use crate::commands::pip::latest::LatestClient; use crate::commands::pip::loggers::DefaultResolveLogger; use crate::commands::pip::resolution_markers; use crate::commands::project::lock::{LockMode, LockOperation}; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ ProjectError, ProjectInterpreter, ScriptInterpreter, UniversalState, default_dependency_groups, }; use crate::commands::reporters::LatestVersionReporter; use crate::commands::{ExitStatus, diagnostics}; use crate::printer::Printer; use crate::settings::LockCheck; use crate::settings::ResolverSettings; /// Run a command. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn tree( project_dir: &Path, groups: DependencyGroups, lock_check: LockCheck, frozen: bool, universal: bool, depth: u8, prune: Vec<PackageName>, package: Vec<PackageName>, no_dedupe: bool, invert: bool, outdated: bool, show_sizes: bool, python_version: Option<PythonVersion>, python_platform: Option<TargetTriple>, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: ResolverSettings, client_builder: &BaseClientBuilder<'_>, script: Option<Pep723Script>, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Find the project requirements. let workspace_cache = WorkspaceCache::default(); let workspace; let target = if let Some(script) = script.as_ref() { LockTarget::Script(script) } else { workspace = Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await?; LockTarget::Workspace(&workspace) }; // Determine the groups to include. let default_groups = match target { LockTarget::Workspace(workspace) => default_dependency_groups(workspace.pyproject_toml())?, LockTarget::Script(_) => DefaultGroups::default(), }; let groups = groups.with_defaults(default_groups); // Find an interpreter for the project, unless `--frozen` and `--universal` are both set. let interpreter = if frozen && universal { None } else { Some(match target { LockTarget::Script(script) => ScriptInterpreter::discover( script.into(), python.as_deref().map(PythonRequest::parse), client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, Some(false), cache, printer, preview, ) .await? .into_interpreter(), LockTarget::Workspace(workspace) => ProjectInterpreter::discover( workspace, project_dir, &groups, python.as_deref().map(PythonRequest::parse), client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, Some(false), cache, printer, preview, ) .await? .into_interpreter(), }) }; // Determine the lock mode. let mode = if frozen { LockMode::Frozen } else if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(interpreter.as_ref().unwrap(), lock_check) } else if matches!(target, LockTarget::Script(_)) && !target.lock_path().is_file() { // If we're locking a script, avoid creating a lockfile if it doesn't already exist. LockMode::DryRun(interpreter.as_ref().unwrap()) } else { LockMode::Write(interpreter.as_ref().unwrap()) }; // Initialize any shared state. let state = UniversalState::default(); // Update the lockfile, if necessary. let lock = match Box::pin( LockOperation::new( mode, &settings, client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &WorkspaceCache::default(), printer, preview, ) .execute(target), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // Determine the markers to use for resolution. let markers = (!universal).then(|| { resolution_markers( python_version.as_ref(), python_platform.as_ref(), interpreter.as_ref().unwrap(), ) }); // If necessary, look up the latest version of each package. let latest = if outdated { // Filter to packages that are derived from a registry. let packages = lock .packages() .iter() .filter_map(|package| { // TODO(charlie): We would need to know the format here. let index = match package.index(target.install_path()) { Ok(Some(index)) => index, Ok(None) => return None, Err(err) => return Some(Err(err)), }; Some(Ok((package, index))) }) .collect::<Result<Vec<_>, _>>()?; if packages.is_empty() { PackageMap::default() } else { let ResolverSettings { index_locations, index_strategy: _, keyring_provider, resolution: _, prerelease: _, fork_strategy: _, dependency_metadata: _, config_setting: _, config_settings_package: _, build_isolation: _, extra_build_dependencies: _, extra_build_variables: _, exclude_newer: _, link_mode: _, upgrade: _, build_options: _, sources: _, torch_backend: _, } = &settings; let capabilities = IndexCapabilities::default(); // Initialize the registry client. let client = RegistryClientBuilder::new( client_builder.clone(), cache.clone().with_refresh(Refresh::All(Timestamp::now())), ) .index_locations(index_locations.clone()) .keyring(*keyring_provider) .build(); let download_concurrency = Semaphore::new(concurrency.downloads); // Initialize the client to fetch the latest version of each package. let client = LatestClient { client: &client, capabilities: &capabilities, prerelease: lock.prerelease_mode(), exclude_newer: &lock.exclude_newer(), requires_python: Some(lock.requires_python()), tags: None, }; let reporter = LatestVersionReporter::from(printer).with_length(packages.len() as u64); // Fetch the latest version for each package. let download_concurrency = &download_concurrency; let mut fetches = futures::stream::iter(packages) .map(async |(package, index)| { // This probably already doesn't work for `--find-links`? let Some(filename) = client .find_latest(package.name(), Some(&index), download_concurrency) .await? else { return Ok(None); }; Ok::<Option<_>, Error>(Some((package, filename.into_version()))) }) .buffer_unordered(concurrency.downloads); let mut map = PackageMap::default(); while let Some(entry) = fetches.next().await.transpose()? { let Some((package, version)) = entry else { reporter.on_fetch_progress(); continue; }; reporter.on_fetch_version(package.name(), &version); if package.version().is_some_and(|package| version > *package) { map.insert(package.clone(), version); } } reporter.on_fetch_complete(); map } } else { PackageMap::default() }; // Render the tree. let tree = TreeDisplay::new( &lock, markers.as_ref(), &latest, depth.into(), &prune, &package, &groups, no_dedupe, invert, show_sizes, ); print!("{tree}"); Ok(ExitStatus::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/src/commands/project/mod.rs
crates/uv/src/commands/project/mod.rs
use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; use std::path::{Path, PathBuf}; use std::sync::Arc; use itertools::Itertools; use owo_colors::OwoColorize; use tracing::{debug, trace, warn}; use uv_auth::CredentialsCache; use uv_cache::{Cache, CacheBucket}; use uv_cache_key::cache_digest; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ Concurrency, Constraints, DependencyGroupsWithDefaults, DryRun, ExtrasSpecification, GitLfsSetting, Reinstall, TargetTriple, Upgrade, }; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution::{DistributionDatabase, LoweredExtraBuildDependencies, LoweredRequirement}; use uv_distribution_types::{ ExtraBuildRequirement, ExtraBuildRequires, Index, Requirement, RequiresPython, Resolution, UnresolvedRequirement, UnresolvedRequirementSpecification, }; use uv_fs::{CWD, LockedFile, LockedFileError, LockedFileMode, Simplified}; use uv_git::ResolvedRepositoryReference; use uv_installer::{InstallationStrategy, SatisfiesResult, SitePackages}; use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, ExtraName, GroupName, PackageName}; use uv_pep440::{TildeVersionSpecifier, Version, VersionSpecifiers}; use uv_pep508::MarkerTreeContents; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::{ConflictItem, ConflictKind, ConflictSet, Conflicts}; use uv_python::{ EnvironmentPreference, Interpreter, InvalidEnvironmentKind, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonSource, PythonVariant, PythonVersionFile, VersionFileDiscoveryOptions, VersionRequest, satisfies_python_preference, }; use uv_requirements::upgrade::{LockedRequirements, read_lock_requirements}; use uv_requirements::{NamedRequirementsResolver, RequirementsSpecification}; use uv_resolver::{ FlatIndex, Installable, Lock, OptionsBuilder, Preference, PythonRequirement, ResolverEnvironment, ResolverOutput, }; use uv_scripts::Pep723ItemRef; use uv_settings::PythonInstallMirrors; use uv_static::EnvVars; use uv_torch::{TorchSource, TorchStrategy}; use uv_types::{BuildIsolation, EmptyInstalledPackages, HashStrategy}; use uv_virtualenv::remove_virtualenv; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::dependency_groups::DependencyGroupError; use uv_workspace::pyproject::{ExtraBuildDependency, PyProjectToml}; use uv_workspace::{RequiresPythonSources, Workspace, WorkspaceCache}; use crate::commands::pip::loggers::{InstallLogger, ResolveLogger}; use crate::commands::pip::operations::{Changelog, Modifications}; use crate::commands::project::install_target::InstallTarget; use crate::commands::reporters::{PythonDownloadReporter, ResolverReporter}; use crate::commands::{capitalize, conjunction, pip}; use crate::printer::Printer; use crate::settings::{ InstallerSettingsRef, LockCheckSource, ResolverInstallerSettings, ResolverSettings, }; pub(crate) mod add; pub(crate) mod environment; pub(crate) mod export; pub(crate) mod format; pub(crate) mod init; mod install_target; pub(crate) mod lock; mod lock_target; pub(crate) mod remove; pub(crate) mod run; pub(crate) mod sync; pub(crate) mod tree; pub(crate) mod version; #[derive(thiserror::Error, Debug)] pub(crate) enum ProjectError { #[error( "The lockfile at `uv.lock` needs to be updated, but `{2}` was provided. To update the lockfile, run `uv lock`." )] LockMismatch(Option<Box<Lock>>, Box<Lock>, LockCheckSource), #[error( "Unable to find lockfile at `uv.lock`. To create a lockfile, run `uv lock` or `uv sync`." )] MissingLockfile, #[error( "The lockfile at `uv.lock` needs to be updated, but `--frozen` was provided: Missing workspace member `{0}`. To update the lockfile, run `uv lock`." )] LockWorkspaceMismatch(PackageName), #[error( "The lockfile at `uv.lock` uses an unsupported schema version (v{1}, but only v{0} is supported). Downgrade to a compatible uv version, or remove the `uv.lock` prior to running `uv lock` or `uv sync`." )] UnsupportedLockVersion(u32, u32), #[error( "Failed to parse `uv.lock`, which uses an unsupported schema version (v{1}, but only v{0} is supported). Downgrade to a compatible uv version, or remove the `uv.lock` prior to running `uv lock` or `uv sync`." )] UnparsableLockVersion(u32, u32, #[source] toml::de::Error), #[error("Failed to serialize `uv.lock`")] LockSerialization(#[from] toml_edit::ser::Error), #[error( "The current Python version ({0}) is not compatible with the locked Python requirement: `{1}`" )] LockedPythonIncompatibility(Version, RequiresPython), #[error( "The current Python platform is not compatible with the lockfile's supported environments: {0}" )] LockedPlatformIncompatibility(String), #[error(transparent)] Conflict(#[from] ConflictError), #[error( "The requested interpreter resolved to Python {_0}, which is incompatible with the project's Python requirement: `{_1}`{}", format_optional_requires_python_sources(_2, *_3) )] RequestedPythonProjectIncompatibility(Version, RequiresPython, RequiresPythonSources, bool), #[error( "The Python request from `{_0}` resolved to Python {_1}, which is incompatible with the project's Python requirement: `{_2}`{}\nUse `uv python pin` to update the `.python-version` file to a compatible version", format_optional_requires_python_sources(_3, *_4) )] DotPythonVersionProjectIncompatibility( String, Version, RequiresPython, RequiresPythonSources, bool, ), #[error( "The resolved Python interpreter (Python {_0}) is incompatible with the project's Python requirement: `{_1}`{}", format_optional_requires_python_sources(_2, *_3) )] RequiresPythonProjectIncompatibility(Version, RequiresPython, RequiresPythonSources, bool), #[error( "The requested interpreter resolved to Python {0}, which is incompatible with the script's Python requirement: `{1}`" )] RequestedPythonScriptIncompatibility(Version, RequiresPython), #[error( "The Python request from `{0}` resolved to Python {1}, which is incompatible with the script's Python requirement: `{2}`" )] DotPythonVersionScriptIncompatibility(String, Version, RequiresPython), #[error( "The resolved Python interpreter (Python {0}) is incompatible with the script's Python requirement: `{1}`" )] RequiresPythonScriptIncompatibility(Version, RequiresPython), #[error("Group `{0}` is not defined in the project's `dependency-groups` table")] MissingGroupProject(GroupName), #[error("Group `{0}` is not defined in any project's `dependency-groups` table")] MissingGroupProjects(GroupName), #[error("PEP 723 scripts do not support dependency groups, but group `{0}` was specified")] MissingGroupScript(GroupName), #[error( "Default group `{0}` (from `tool.uv.default-groups`) is not defined in the project's `dependency-groups` table" )] MissingDefaultGroup(GroupName), #[error("Extra `{0}` is not defined in the project's `optional-dependencies` table")] MissingExtraProject(ExtraName), #[error("Extra `{0}` is not defined in any project's `optional-dependencies` table")] MissingExtraProjects(ExtraName), #[error("PEP 723 scripts do not support optional dependencies, but extra `{0}` was specified")] MissingExtraScript(ExtraName), #[error("Supported environments must be disjoint, but the following markers overlap: `{0}` and `{1}`.\n\n{hint}{colon} replace `{1}` with `{2}`.", hint = "hint".bold().cyan(), colon = ":".bold())] OverlappingMarkers(String, String, String), #[error("Environment markers `{0}` don't overlap with Python requirement `{1}`")] DisjointEnvironment(MarkerTreeContents, VersionSpecifiers), #[error( "Found conflicting Python requirements:\n{}", format_requires_python_sources(_0) )] DisjointRequiresPython(BTreeMap<(PackageName, Option<GroupName>), VersionSpecifiers>), #[error("Environment marker is empty")] EmptyEnvironment, #[error("Project virtual environment directory `{0}` cannot be used because {1}")] InvalidProjectEnvironmentDir(PathBuf, String), #[error("Failed to parse `uv.lock`")] UvLockParse(#[source] toml::de::Error), #[error("Failed to parse `pyproject.toml`")] PyprojectTomlParse(#[source] toml::de::Error), #[error("Failed to update `pyproject.toml`")] PyprojectTomlUpdate, #[error("Failed to parse PEP 723 script metadata")] Pep723ScriptTomlParse(#[source] toml::de::Error), #[error("Failed to find `site-packages` directory for environment")] NoSitePackages, #[error("Attempted to drop a temporary virtual environment while still in-use")] DroppedEnvironment, #[error(transparent)] DependencyGroup(#[from] DependencyGroupError), #[error(transparent)] Client(#[from] uv_client::Error), #[error(transparent)] Python(#[from] uv_python::Error), #[error(transparent)] Virtualenv(#[from] uv_virtualenv::Error), #[error(transparent)] HashStrategy(#[from] uv_types::HashStrategyError), #[error(transparent)] Tags(#[from] uv_platform_tags::TagsError), #[error(transparent)] FlatIndex(#[from] uv_client::FlatIndexError), #[error(transparent)] Lock(#[from] uv_resolver::LockError), #[error(transparent)] Operation(#[from] pip::operations::Error), #[error(transparent)] Interpreter(#[from] uv_python::InterpreterError), #[error(transparent)] Tool(#[from] uv_tool::Error), #[error(transparent)] Name(#[from] uv_normalize::InvalidNameError), #[error(transparent)] Requirements(#[from] uv_requirements::Error), #[error(transparent)] Metadata(#[from] uv_distribution::MetadataError), #[error(transparent)] Lowering(#[from] uv_distribution::LoweringError), #[error(transparent)] Workspace(#[from] uv_workspace::WorkspaceError), #[error(transparent)] PyprojectMut(#[from] uv_workspace::pyproject_mut::Error), #[error(transparent)] ExtraBuildRequires(#[from] uv_distribution_types::ExtraBuildRequiresError), #[error(transparent)] Fmt(#[from] std::fmt::Error), #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] RetryParsing(#[from] uv_client::RetryParsingError), #[error(transparent)] Accelerator(#[from] uv_torch::AcceleratorError), #[error(transparent)] Anyhow(#[from] anyhow::Error), } #[derive(Debug)] pub(crate) struct ConflictError { /// The set from which the conflict was derived. pub(crate) set: ConflictSet, /// The items from the set that were enabled, and thus create the conflict. pub(crate) conflicts: Vec<ConflictItem>, /// Enabled dependency groups with defaults applied. pub(crate) groups: DependencyGroupsWithDefaults, } impl std::fmt::Display for ConflictError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Format the set itself. let set = self .set .iter() .map(|item| match item.kind() { ConflictKind::Project => format!("{}", item.package()), ConflictKind::Extra(extra) => format!("`{}[{}]`", item.package(), extra), ConflictKind::Group(group) => format!("`{}:{}`", item.package(), group), }) .join(", "); // If all the conflicts are of the same kind, show a more succinct error. if self .conflicts .iter() .all(|conflict| matches!(conflict.kind(), ConflictKind::Extra(..))) { write!( f, "Extras {} are incompatible with the declared conflicts: {{{set}}}", conjunction( self.conflicts .iter() .map(|conflict| match conflict.kind() { ConflictKind::Extra(extra) => format!("`{extra}`"), ConflictKind::Group(..) | ConflictKind::Project => unreachable!(), }) .collect() ) ) } else if self .conflicts .iter() .all(|conflict| matches!(conflict.kind(), ConflictKind::Group(..))) { write!( f, "Groups {} are incompatible with the conflicts: {{{set}}}", conjunction( self.conflicts .iter() .map(|conflict| match conflict.kind() { ConflictKind::Group(group) if self.groups.contains_because_default(group) => format!("`{group}` (enabled by default)"), ConflictKind::Group(group) => format!("`{group}`"), ConflictKind::Extra(..) | ConflictKind::Project => unreachable!(), }) .collect() ) ) } else { write!( f, "{} are incompatible with the declared conflicts: {{{set}}}", conjunction( self.conflicts .iter() .enumerate() .map(|(i, conflict)| { let conflict = match conflict.kind() { ConflictKind::Project => { format!("package `{}`", conflict.package()) } ConflictKind::Extra(extra) => format!("extra `{extra}`"), ConflictKind::Group(group) if self.groups.contains_because_default(group) => { format!("group `{group}` (enabled by default)") } ConflictKind::Group(group) => format!("group `{group}`"), }; if i == 0 { capitalize(&conflict) } else { conflict } }) .collect() ) ) } } } impl std::error::Error for ConflictError {} /// A [`SharedState`] instance to use for universal resolution. #[derive(Default, Clone)] pub(crate) struct UniversalState(SharedState); impl std::ops::Deref for UniversalState { type Target = SharedState; fn deref(&self) -> &Self::Target { &self.0 } } impl UniversalState { /// Fork the [`UniversalState`] to create a [`PlatformState`]. pub(crate) fn fork(&self) -> PlatformState { PlatformState(self.0.fork()) } } /// A [`SharedState`] instance to use for platform-specific resolution. #[derive(Default, Clone)] pub(crate) struct PlatformState(SharedState); impl std::ops::Deref for PlatformState { type Target = SharedState; fn deref(&self) -> &Self::Target { &self.0 } } impl PlatformState { /// Fork the [`PlatformState`] to create a [`UniversalState`]. pub(crate) fn fork(&self) -> UniversalState { UniversalState(self.0.fork()) } /// Create a [`SharedState`] from the [`PlatformState`]. pub(crate) fn into_inner(self) -> SharedState { self.0 } } /// Compute the `Requires-Python` bound for the [`Workspace`]. /// /// For a [`Workspace`] with multiple packages, the `Requires-Python` bound is the union of the /// `Requires-Python` bounds of all the packages. #[allow(clippy::result_large_err)] pub(crate) fn find_requires_python( workspace: &Workspace, groups: &DependencyGroupsWithDefaults, ) -> Result<Option<RequiresPython>, ProjectError> { let requires_python = workspace.requires_python(groups)?; // If there are no `Requires-Python` specifiers in the workspace, return `None`. if requires_python.is_empty() { return Ok(None); } for ((package, group), specifiers) in &requires_python { if let [spec] = &specifiers[..] { if let Some(spec) = TildeVersionSpecifier::from_specifier_ref(spec) { if spec.has_patch() { continue; } let (lower, upper) = spec.bounding_specifiers(); let spec_0 = spec.with_patch_version(0); let (lower_0, upper_0) = spec_0.bounding_specifiers(); warn_user_once!( "The `requires-python` specifier (`{spec}`) in `{package}{group}` \ uses the tilde specifier (`~=`) without a patch version. This will be \ interpreted as `{lower}, {upper}`. Did you mean `{spec_0}` to constrain the \ version as `{lower_0}, {upper_0}`? We recommend only using \ the tilde specifier with a patch version to avoid ambiguity.", group = if let Some(group) = group { format!(":{group}") } else { String::new() }, ); } } } match RequiresPython::intersection(requires_python.iter().map(|(.., specifiers)| specifiers)) { Some(requires_python) => Ok(Some(requires_python)), None => Err(ProjectError::DisjointRequiresPython(requires_python)), } } /// Returns an error if the [`Interpreter`] does not satisfy the [`Workspace`] `requires-python`. /// /// If no [`Workspace`] is provided, the `requires-python` will be validated against the originating /// source (e.g., a `.python-version` file or a `--python` command-line argument). #[allow(clippy::result_large_err)] pub(crate) fn validate_project_requires_python( interpreter: &Interpreter, workspace: Option<&Workspace>, groups: &DependencyGroupsWithDefaults, requires_python: &RequiresPython, source: &PythonRequestSource, ) -> Result<(), ProjectError> { if requires_python.contains(interpreter.python_version()) { return Ok(()); } // Find all the individual requires_python constraints that conflict let conflicting_requires = workspace .and_then(|workspace| workspace.requires_python(groups).ok()) .into_iter() .flatten() .filter(|(.., requires)| !requires.contains(interpreter.python_version())) .collect::<RequiresPythonSources>(); let workspace_non_trivial = workspace .map(|workspace| workspace.packages().len() > 1) .unwrap_or(false); match source { PythonRequestSource::UserRequest => { Err(ProjectError::RequestedPythonProjectIncompatibility( interpreter.python_version().clone(), requires_python.clone(), conflicting_requires, workspace_non_trivial, )) } PythonRequestSource::DotPythonVersion(file) => { Err(ProjectError::DotPythonVersionProjectIncompatibility( file.path().user_display().to_string(), interpreter.python_version().clone(), requires_python.clone(), conflicting_requires, workspace_non_trivial, )) } PythonRequestSource::RequiresPython => { Err(ProjectError::RequiresPythonProjectIncompatibility( interpreter.python_version().clone(), requires_python.clone(), conflicting_requires, workspace_non_trivial, )) } } } /// Returns an error if the [`Interpreter`] does not satisfy script or workspace `requires-python`. #[allow(clippy::result_large_err)] fn validate_script_requires_python( interpreter: &Interpreter, requires_python: &RequiresPython, source: &PythonRequestSource, ) -> Result<(), ProjectError> { if requires_python.contains(interpreter.python_version()) { return Ok(()); } match source { PythonRequestSource::UserRequest => { Err(ProjectError::RequestedPythonScriptIncompatibility( interpreter.python_version().clone(), requires_python.clone(), )) } PythonRequestSource::DotPythonVersion(file) => { Err(ProjectError::DotPythonVersionScriptIncompatibility( file.file_name().to_string(), interpreter.python_version().clone(), requires_python.clone(), )) } PythonRequestSource::RequiresPython => { Err(ProjectError::RequiresPythonScriptIncompatibility( interpreter.python_version().clone(), requires_python.clone(), )) } } } /// An interpreter suitable for a PEP 723 script. #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] pub(crate) enum ScriptInterpreter { /// An interpreter to use to create a new script environment. Interpreter(Interpreter), /// An interpreter from an existing script environment. Environment(PythonEnvironment), } impl ScriptInterpreter { /// Return the expected virtual environment path for the [`Pep723Script`]. /// /// If `--active` is set, the active virtual environment will be preferred. /// /// See: [`Workspace::venv`]. pub(crate) fn root(script: Pep723ItemRef<'_>, active: Option<bool>, cache: &Cache) -> PathBuf { /// Resolve the `VIRTUAL_ENV` variable, if any. fn from_virtual_env_variable() -> Option<PathBuf> { let value = std::env::var_os(EnvVars::VIRTUAL_ENV)?; if value.is_empty() { return None; } let path = PathBuf::from(value); if path.is_absolute() { return Some(path); } // Resolve the path relative to current directory. Some(CWD.join(path)) } // Determine the stable path to the script environment in the cache. let cache_env = { let entry = match script { // For local scripts, use a hash of the path to the script. Pep723ItemRef::Script(script) => { let digest = cache_digest(&script.path); if let Some(file_name) = script .path .file_stem() .and_then(|name| name.to_str()) .and_then(cache_name) { format!("{file_name}-{digest}") } else { digest } } // For remote scripts, use a hash of the URL. Pep723ItemRef::Remote(.., url) => cache_digest(url), // Otherwise, use a hash of the metadata. Pep723ItemRef::Stdin(metadata) => cache_digest(&metadata.raw), }; cache .shard(CacheBucket::Environments, entry) .into_path_buf() }; // If `--active` is set, prefer the active virtual environment. if let Some(from_virtual_env) = from_virtual_env_variable() { if !uv_fs::is_same_file_allow_missing(&from_virtual_env, &cache_env).unwrap_or(false) { match active { Some(true) => { debug!( "Using active virtual environment `{}` instead of script environment `{}`", from_virtual_env.user_display(), cache_env.user_display() ); return from_virtual_env; } Some(false) => {} None => { warn_user_once!( "`VIRTUAL_ENV={}` does not match the script environment path `{}` and will be ignored; use `--active` to target the active environment instead", from_virtual_env.user_display(), cache_env.user_display() ); } } } } else { if active.unwrap_or_default() { debug!( "Use of the active virtual environment was requested, but `VIRTUAL_ENV` is not set" ); } } // Otherwise, use the cache root. cache_env } /// Discover the interpreter to use for the current [`Pep723Item`]. pub(crate) async fn discover( script: Pep723ItemRef<'_>, python_request: Option<PythonRequest>, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, install_mirrors: &PythonInstallMirrors, keep_incompatible: bool, no_config: bool, active: Option<bool>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<Self, ProjectError> { // For now, we assume that scripts are never evaluated in the context of a workspace. let workspace = None; let ScriptPython { source, python_request, requires_python, } = ScriptPython::from_request(python_request, workspace, script, no_config).await?; let root = Self::root(script, active, cache); match PythonEnvironment::from_root(&root, cache) { Ok(venv) => { match environment_is_usable( &venv, EnvironmentKind::Script, python_request.as_ref(), python_preference, requires_python .as_ref() .map(|(requires_python, _)| requires_python), cache, ) { Ok(()) => return Ok(Self::Environment(venv)), Err(err) if keep_incompatible => { warn_user!( "Using incompatible environment (`{}`) due to `--no-sync` ({err})", root.user_display().cyan(), ); return Ok(Self::Environment(venv)); } Err(err) => { debug!("{err}"); } } } Err(uv_python::Error::MissingEnvironment(_)) => {} Err(err) => warn!("Ignoring existing script environment: {err}"), } let reporter = PythonDownloadReporter::single(printer); let interpreter = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::Any, python_preference, python_downloads, client_builder, cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); if let Err(err) = match requires_python { Some((requires_python, RequiresPythonSource::Project)) => { validate_project_requires_python( &interpreter, workspace, &DependencyGroupsWithDefaults::none(), &requires_python, &source, ) } Some((requires_python, RequiresPythonSource::Script)) => { validate_script_requires_python(&interpreter, &requires_python, &source) } None => Ok(()), } { warn_user!("{err}"); } Ok(Self::Interpreter(interpreter)) } /// Consume the [`PythonInstallation`] and return the [`Interpreter`]. pub(crate) fn into_interpreter(self) -> Interpreter { match self { Self::Interpreter(interpreter) => interpreter, Self::Environment(venv) => venv.into_interpreter(), } } /// Grab a file lock for the script to prevent concurrent writes across processes. pub(crate) async fn lock(script: Pep723ItemRef<'_>) -> Result<LockedFile, LockedFileError> { match script { Pep723ItemRef::Script(script) => { LockedFile::acquire( std::env::temp_dir().join(format!("uv-{}.lock", cache_digest(&script.path))), LockedFileMode::Exclusive, script.path.simplified_display(), ) .await } Pep723ItemRef::Remote(.., url) => { LockedFile::acquire( std::env::temp_dir().join(format!("uv-{}.lock", cache_digest(url))), LockedFileMode::Exclusive, url.to_string(), ) .await } Pep723ItemRef::Stdin(metadata) => { LockedFile::acquire( std::env::temp_dir().join(format!("uv-{}.lock", cache_digest(&metadata.raw))), LockedFileMode::Exclusive, "stdin".to_string(), ) .await } } } } #[derive(Debug)] pub(crate) enum EnvironmentKind { Script, Project, } impl std::fmt::Display for EnvironmentKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Script => write!(f, "script"), Self::Project => write!(f, "project"), } } } #[derive(Debug, thiserror::Error)] pub(crate) enum EnvironmentIncompatibilityError { #[error("The {0} environment's Python version does not satisfy the request: `{1}`")] PythonRequest(EnvironmentKind, PythonRequest), #[error("The {0} environment's Python version does not meet the Python requirement: `{1}`")] RequiresPython(EnvironmentKind, RequiresPython), #[error( "The interpreter in the {0} environment has a different version ({1}) than it was created with ({2})" )] PyenvVersionConflict(EnvironmentKind, Version, Version), #[error("The {0} environment's Python interpreter does not meet the Python preference: `{1}`")] PythonPreference(EnvironmentKind, PythonPreference), } /// Whether an environment is usable for a project or script, i.e., if it matches the requirements. fn environment_is_usable( environment: &PythonEnvironment, kind: EnvironmentKind, python_request: Option<&PythonRequest>, python_preference: PythonPreference, requires_python: Option<&RequiresPython>, cache: &Cache, ) -> Result<(), EnvironmentIncompatibilityError> { if let Some((cfg_version, int_version)) = environment.get_pyvenv_version_conflict() { return Err(EnvironmentIncompatibilityError::PyenvVersionConflict( kind, int_version, cfg_version, )); } if let Some(request) = python_request { if request.satisfied(environment.interpreter(), cache) { debug!("The {kind} environment's Python version satisfies the request: `{request}`"); } else { return Err(EnvironmentIncompatibilityError::PythonRequest( kind, request.clone(), )); } } if let Some(requires_python) = requires_python { if requires_python.contains(environment.interpreter().python_version()) { trace!( "The {kind} environment's Python version meets the Python requirement: `{requires_python}`" ); } else { return Err(EnvironmentIncompatibilityError::RequiresPython( kind, requires_python.clone(), )); } } if satisfies_python_preference( PythonSource::DiscoveredEnvironment, environment.interpreter(), python_preference, ) { trace!( "The virtual environment's Python interpreter meets the Python preference: `{}`",
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/src/commands/project/format.rs
crates/uv/src/commands/project/format.rs
use std::path::Path; use std::str::FromStr; use anyhow::{Context, Result}; use tokio::process::Command; use uv_bin_install::{Binary, bin_install}; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_pep440::Version; use uv_preview::{Preview, PreviewFeatures}; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache, WorkspaceError}; use crate::child::run_to_completion; use crate::commands::ExitStatus; use crate::commands::reporters::BinaryDownloadReporter; use crate::printer::Printer; /// Run the formatter. pub(crate) async fn format( project_dir: &Path, check: bool, diff: bool, extra_args: Vec<String>, version: Option<String>, client_builder: BaseClientBuilder<'_>, cache: Cache, printer: Printer, preview: Preview, no_project: bool, ) -> Result<ExitStatus> { // Check if the format feature is in preview if !preview.is_enabled(PreviewFeatures::FORMAT) { warn_user!( "`uv format` is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::FORMAT ); } let workspace_cache = WorkspaceCache::default(); // If `no_project` is provided, we use the provided directory // Otherwise, we discover the project and use the project root. let target_dir = if no_project { project_dir.to_owned() } else { match VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await { // If we found a project, we use the project root Ok(proj) => proj.root().to_owned(), // If there is a problem finding a project, we just use the provided directory, // e.g., for unmanaged projects Err( WorkspaceError::MissingPyprojectToml | WorkspaceError::MissingProject(_) | WorkspaceError::NonWorkspace(_), ) => project_dir.to_owned(), Err(err) => return Err(err.into()), } }; // Parse version if provided let version = version.as_deref().map(Version::from_str).transpose()?; let retry_policy = client_builder.retry_policy(); // Python downloads are performing their own retries to catch stream errors, disable the // default retries to avoid the middleware from performing uncontrolled retries. let client = client_builder.retries(0).build(); // Get the path to Ruff, downloading it if necessary let reporter = BinaryDownloadReporter::single(printer); let default_version = Binary::Ruff.default_version(); let version = version.as_ref().unwrap_or(&default_version); let ruff_path = bin_install( Binary::Ruff, version, &client, &retry_policy, &cache, &reporter, ) .await .with_context(|| format!("Failed to install ruff {version}"))?; let mut command = Command::new(&ruff_path); command.current_dir(target_dir); command.arg("format"); if check { command.arg("--check"); } if diff { command.arg("--diff"); } // Add any additional arguments passed after `--` command.args(extra_args.iter()); let handle = command.spawn().context("Failed to spawn `ruff format`")?; run_to_completion(handle).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/src/commands/project/run.rs
crates/uv/src/commands/project/run.rs
use std::borrow::Cow; use std::env::VarError; use std::ffi::OsString; use std::fmt::Write; use std::io; use std::io::Read; use std::path::{Path, PathBuf}; use anyhow::{Context, anyhow, bail}; use futures::StreamExt; use itertools::Itertools; use owo_colors::OwoColorize; use thiserror::Error; use tokio::process::Command; use tracing::{debug, trace, warn}; use url::Url; use uv_cache::Cache; use uv_cli::ExternalCommand; use uv_client::BaseClientBuilder; use uv_configuration::{ Concurrency, Constraints, DependencyGroups, DryRun, EditableMode, EnvFile, ExtrasSpecification, InstallOptions, TargetTriple, }; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::Requirement; use uv_fs::which::is_executable; use uv_fs::{PythonExt, Simplified, create_symlink}; use uv_installer::{InstallationStrategy, SatisfiesResult, SitePackages}; use uv_normalize::{DefaultExtras, DefaultGroups, PackageName}; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, Interpreter, PyVenvConfiguration, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVersionFile, VersionFileDiscoveryOptions, }; use uv_redacted::DisplaySafeUrl; use uv_requirements::{RequirementsSource, RequirementsSpecification}; use uv_resolver::{Installable, Lock, Preference}; use uv_scripts::Pep723Item; use uv_settings::PythonInstallMirrors; use uv_shell::runnable::WindowsRunnable; use uv_static::EnvVars; use uv_warnings::warn_user; use uv_workspace::{DiscoveryOptions, VirtualProject, Workspace, WorkspaceCache, WorkspaceError}; use crate::child::run_to_completion; /// GitHub Gist API response structure #[derive(serde::Deserialize)] struct GistResponse { files: std::collections::HashMap<String, GistFile>, } #[derive(serde::Deserialize)] struct GistFile { raw_url: String, } use crate::commands::pip::loggers::{ DefaultInstallLogger, DefaultResolveLogger, SummaryInstallLogger, SummaryResolveLogger, }; use crate::commands::pip::operations::Modifications; use crate::commands::project::environment::{CachedEnvironment, EphemeralEnvironment}; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::LockMode; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ EnvironmentSpecification, PreferenceLocation, ProjectEnvironment, ProjectError, ScriptEnvironment, ScriptInterpreter, UniversalState, WorkspacePython, default_dependency_groups, script_extra_build_requires, script_specification, update_environment, validate_project_requires_python, }; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::{ExitStatus, diagnostics, project}; use crate::printer::Printer; use crate::settings::{LockCheck, ResolverInstallerSettings, ResolverSettings}; /// Run a command. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn run( project_dir: &Path, script: Option<Pep723Item>, command: Option<RunCommand>, requirements: Vec<RequirementsSource>, show_resolution: bool, lock_check: LockCheck, frozen: bool, active: Option<bool>, no_sync: bool, isolated: bool, all_packages: bool, package: Option<PackageName>, no_project: bool, no_config: bool, extras: ExtrasSpecification, groups: DependencyGroups, editable: Option<EditableMode>, modifications: Modifications, python: Option<String>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, cache: Cache, printer: Printer, env_file: EnvFile, preview: Preview, max_recursion_depth: u32, ) -> anyhow::Result<ExitStatus> { // Check if max recursion depth was exceeded. This most commonly happens // for scripts with a shebang line like `#!/usr/bin/env -S uv run`, so try // to provide guidance for that case. let recursion_depth = read_recursion_depth_from_environment_variable()?; if recursion_depth > max_recursion_depth { bail!( r" `uv run` was recursively invoked {recursion_depth} times which exceeds the limit of {max_recursion_depth}. hint: If you are running a script with `{}` in the shebang, you may need to include the `{}` flag.", "uv run".green(), "--script".green(), ); } // These cases seem quite complex because (in theory) they should change the "current package". // Let's ban them entirely for now. let mut requirements_from_stdin: bool = false; for source in &requirements { match source { RequirementsSource::PyprojectToml(_) => { bail!("Adding requirements from a `pyproject.toml` is not supported in `uv run`"); } RequirementsSource::SetupPy(_) => { bail!("Adding requirements from a `setup.py` is not supported in `uv run`"); } RequirementsSource::SetupCfg(_) => { bail!("Adding requirements from a `setup.cfg` is not supported in `uv run`"); } RequirementsSource::Extensionless(path) => { if path == Path::new("-") { requirements_from_stdin = true; } } _ => {} } } // Fail early if stdin is used for multiple purposes. if matches!( command, Some(RunCommand::PythonStdin(..) | RunCommand::PythonGuiStdin(..)) ) && requirements_from_stdin { bail!("Cannot read both requirements file and script from stdin"); } // Initialize any shared state. let lock_state = UniversalState::default(); let sync_state = lock_state.fork(); let workspace_cache = WorkspaceCache::default(); // Read from the `.env` file, if necessary. for env_file_path in env_file.iter().rev().map(PathBuf::as_path) { match dotenvy::from_path(env_file_path) { Err(dotenvy::Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { bail!( "No environment file found at: `{}`", env_file_path.simplified_display() ); } Err(dotenvy::Error::Io(err)) => { bail!( "Failed to read environment file `{}`: {err}", env_file_path.simplified_display() ); } Err(dotenvy::Error::LineParse(content, position)) => { warn_user!( "Failed to parse environment file `{}` at position {position}: {content}", env_file_path.simplified_display(), ); } Err(err) => { warn_user!( "Failed to parse environment file `{}`: {err}", env_file_path.simplified_display(), ); } Ok(()) => { debug!( "Read environment file at: `{}`", env_file_path.simplified_display() ); } } } // Initialize any output reporters. let download_reporter = PythonDownloadReporter::single(printer); // The lockfile used for the base environment. let mut base_lock: Option<(Lock, PathBuf)> = None; // Determine whether the command to execute is a PEP 723 script. let temp_dir; let script_interpreter = if let Some(script) = script { match &script { Pep723Item::Script(script) => { debug!( "Reading inline script metadata from `{}`", script.path.user_display() ); } Pep723Item::Stdin(..) => { if requirements_from_stdin { bail!("Cannot read both requirements file and script from stdin"); } debug!("Reading inline script metadata from stdin"); } Pep723Item::Remote(..) => { debug!("Reading inline script metadata from remote URL"); } } // If a lockfile already exists, lock the script. if let Some(target) = script .as_script() .map(LockTarget::from) .filter(|target| target.lock_path().is_file()) { debug!("Found existing lockfile for script"); // Discover the interpreter for the script. let environment = ScriptEnvironment::get_or_init( (&script).into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, no_sync, no_config, active.map_or(Some(false), Some), &cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()?; let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); // Determine the lock mode. let mode = if frozen { LockMode::Frozen } else if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(environment.interpreter(), lock_check) } else { LockMode::Write(environment.interpreter()) }; // Generate a lockfile. let lock = match Box::pin( project::lock::LockOperation::new( mode, &settings.resolver, &client_builder, &lock_state, if show_resolution { Box::new(DefaultResolveLogger) } else { Box::new(SummaryResolveLogger) }, concurrency, &cache, &workspace_cache, printer, preview, ) .execute(target), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .with_context("script") .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // Sync the environment. let target = InstallTarget::Script { script: script.as_script().unwrap(), lock: &lock, }; let install_options = InstallOptions::default(); match project::sync::do_sync( target, &environment, &extras.with_defaults(DefaultExtras::default()), &groups.with_defaults(DefaultGroups::default()), editable, install_options, modifications, python_platform.as_ref(), (&settings).into(), &client_builder, &sync_state, if show_resolution { Box::new(DefaultInstallLogger) } else { Box::new(SummaryInstallLogger) }, installer_metadata, concurrency, &cache, workspace_cache.clone(), DryRun::Disabled, printer, preview, ) .await { Ok(_) => {} Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .with_context("script") .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } // Respect any locked preferences when resolving `--with` dependencies downstream. let install_path = target.install_path().to_path_buf(); base_lock = Some((lock, install_path)); Some(environment.into_interpreter()) } else { // If no lockfile is found, warn against `--locked` and `--frozen`. if let LockCheck::Enabled(lock_check) = lock_check { warn_user!( "No lockfile found for Python script (ignoring `{lock_check}`); run `{}` to generate a lockfile", "uv lock --script".green(), ); } if frozen { warn_user!( "No lockfile found for Python script (ignoring `--frozen`); run `{}` to generate a lockfile", "uv lock --script".green(), ); } // Install the script requirements, if necessary. Otherwise, use an isolated environment. if let Some(spec) = script_specification( (&script).into(), &settings.resolver, client_builder.credentials_cache(), )? { let script_extra_build_requires = script_extra_build_requires( (&script).into(), &settings.resolver, client_builder.credentials_cache(), )? .into_inner(); let environment = ScriptEnvironment::get_or_init( (&script).into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, no_sync, no_config, active.map_or(Some(false), Some), &cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()?; let build_constraints = script .metadata() .tool .as_ref() .and_then(|tool| { tool.uv .as_ref() .and_then(|uv| uv.build_constraint_dependencies.as_ref()) }) .map(|constraints| { Constraints::from_requirements( constraints .iter() .map(|constraint| Requirement::from(constraint.clone())), ) }); let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); match update_environment( environment, spec, modifications, python_platform.as_ref(), build_constraints.unwrap_or_default(), script_extra_build_requires, &settings, &client_builder, &sync_state, if show_resolution { Box::new(DefaultResolveLogger) } else { Box::new(SummaryResolveLogger) }, if show_resolution { Box::new(DefaultInstallLogger) } else { Box::new(SummaryInstallLogger) }, installer_metadata, concurrency, &cache, workspace_cache.clone(), DryRun::Disabled, printer, preview, ) .await { Ok(update) => Some(update.into_environment().into_interpreter()), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .with_context("script") .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } } else { // Create a virtual environment. let interpreter = ScriptInterpreter::discover( (&script).into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, no_sync, no_config, active.map_or(Some(false), Some), &cache, printer, preview, ) .await? .into_interpreter(); temp_dir = cache.venv_dir()?; let environment = uv_virtualenv::create_venv( temp_dir.path(), interpreter, uv_virtualenv::Prompt::None, false, uv_virtualenv::OnExisting::Remove( uv_virtualenv::RemovalReason::TemporaryEnvironment, ), false, false, false, preview, )?; Some(environment.into_interpreter()) } } } else { None }; // Discover and sync the base environment. let temp_dir; let base_interpreter = if let Some(script_interpreter) = script_interpreter { // If we found a PEP 723 script and the user provided a project-only setting, warn. if no_project { debug!( "`--no-project` is a no-op for Python scripts with inline metadata; ignoring..." ); } if !extras.is_empty() { warn_user!("Extras are not supported for Python scripts with inline metadata"); } for flag in groups.history().as_flags_pretty() { warn_user!("`{flag}` is not supported for Python scripts with inline metadata"); } if all_packages { warn_user!( "`--all-packages` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if package.is_some() { warn_user!( "`--package` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if no_sync { warn_user!( "`--no-sync` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if isolated { warn_user!( "`--isolated` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } script_interpreter } else { let project = if let Some(package) = package.as_ref() { // We need a workspace, but we don't need to have a current package, we can be e.g. in // the root of a virtual workspace and then switch into the selected package. Some(VirtualProject::Project( Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await? .with_current_project(package.clone()) .with_context(|| format!("Package `{package}` not found in workspace"))?, )) } else { match VirtualProject::discover( project_dir, &DiscoveryOptions::default(), &workspace_cache, ) .await { Ok(project) => { if no_project { debug!("Ignoring discovered project due to `--no-project`"); None } else { Some(project) } } Err(WorkspaceError::MissingPyprojectToml | WorkspaceError::NonWorkspace(_)) => { // If the user runs with `--no-project` and we can't find a project, warn. if no_project { warn!("`--no-project` was provided, but no project was found"); } None } Err(err) => { // If the user runs with `--no-project`, ignore the error. if no_project { warn!("Ignoring project discovery error due to `--no-project`: {err}"); None } else { return Err(err.into()); } } } }; if no_project { // If the user ran with `--no-project` and provided a project-only setting, warn. for flag in extras.history().as_flags_pretty() { warn_user!("`{flag}` has no effect when used alongside `--no-project`"); } for flag in groups.history().as_flags_pretty() { warn_user!("`{flag}` has no effect when used alongside `--no-project`"); } if let LockCheck::Enabled(lock_check) = lock_check { warn_user!("`{lock_check}` has no effect when used alongside `--no-project`"); } if frozen { warn_user!("`--frozen` has no effect when used alongside `--no-project`"); } if no_sync { warn_user!("`--no-sync` has no effect when used alongside `--no-project`"); } } else if project.is_none() { // If we can't find a project and the user provided a project-only setting, warn. for flag in extras.history().as_flags_pretty() { warn_user!("`{flag}` has no effect when used outside of a project"); } for flag in groups.history().as_flags_pretty() { warn_user!("`{flag}` has no effect when used outside of a project"); } if let LockCheck::Enabled(lock_check) = lock_check { warn_user!("`{lock_check}` has no effect when used outside of a project",); } if no_sync { warn_user!("`--no-sync` has no effect when used outside of a project"); } } if let Some(project) = project { if let Some(project_name) = project.project_name() { debug!( "Discovered project `{project_name}` at: {}", project.workspace().install_path().display() ); } else { debug!( "Discovered virtual workspace at: {}", project.workspace().install_path().display() ); } // Determine the groups and extras to include. let default_groups = default_dependency_groups(project.pyproject_toml())?; let default_extras = DefaultExtras::default(); let groups = groups.with_defaults(default_groups); let extras = extras.with_defaults(default_extras); let venv = if isolated { debug!("Creating isolated virtual environment"); // If we're isolating the environment, use an ephemeral virtual environment as the // base environment for the project. // Resolve the Python request and requirement for the workspace. let WorkspacePython { source, python_request, requires_python, } = WorkspacePython::from_request( python.as_deref().map(PythonRequest::parse), Some(project.workspace()), &groups, project_dir, no_config, ) .await?; let interpreter = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::Any, python_preference, python_downloads, &client_builder, &cache, Some(&download_reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); if let Some(requires_python) = requires_python.as_ref() { validate_project_requires_python( &interpreter, Some(project.workspace()), &groups, requires_python, &source, )?; } // Create a virtual environment temp_dir = cache.venv_dir()?; uv_virtualenv::create_venv( temp_dir.path(), interpreter, uv_virtualenv::Prompt::None, false, uv_virtualenv::OnExisting::Remove( uv_virtualenv::RemovalReason::TemporaryEnvironment, ), false, false, false, preview, )? } else { // If we're not isolating the environment, reuse the base environment for the // project. ProjectEnvironment::get_or_init( project.workspace(), &groups, python.as_deref().map(PythonRequest::parse), &install_mirrors, &client_builder, python_preference, python_downloads, no_sync, no_config, active, &cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()? }; if no_sync { debug!("Skipping environment synchronization due to `--no-sync`"); // If we're not syncing, we should still attempt to respect the locked preferences // in any `--with` requirements. if !isolated && !requirements.is_empty() { base_lock = LockTarget::from(project.workspace()) .read() .await .ok() .flatten() .map(|lock| (lock, project.workspace().install_path().to_owned())); } } else { let _lock = venv .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); // Determine the lock mode. let mode = if frozen { LockMode::Frozen } else if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(venv.interpreter(), lock_check) } else if isolated { LockMode::DryRun(venv.interpreter()) } else { LockMode::Write(venv.interpreter()) }; let result = match Box::pin( project::lock::LockOperation::new( mode, &settings.resolver, &client_builder, &lock_state, if show_resolution { Box::new(DefaultResolveLogger) } else { Box::new(SummaryResolveLogger) }, concurrency, &cache, &workspace_cache, printer, preview, ) .execute(project.workspace().into()), ) .await { Ok(result) => result, Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // Identify the installation target. let target = match &project { VirtualProject::Project(project) => { if all_packages { InstallTarget::Workspace { workspace: project.workspace(), lock: result.lock(), } } else if let Some(package) = package.as_ref() { InstallTarget::Project { workspace: project.workspace(), name: package, lock: result.lock(), } } else { // By default, install the root package. InstallTarget::Project { workspace: project.workspace(), name: project.project_name(), lock: result.lock(), } } } VirtualProject::NonProject(workspace) => { if all_packages { InstallTarget::NonProjectWorkspace { workspace, lock: result.lock(), } } else if let Some(package) = package.as_ref() { InstallTarget::Project { workspace, name: package, lock: result.lock(), } } else { // By default, install the entire workspace. InstallTarget::NonProjectWorkspace { workspace, lock: result.lock(), } } } }; let install_options = InstallOptions::default(); // Validate that the set of requested extras and development groups are defined in the lockfile. target.validate_extras(&extras)?; target.validate_groups(&groups)?; match project::sync::do_sync( target,
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/src/commands/project/init.rs
crates/uv/src/commands/project/init.rs
use std::fmt::Write; use std::iter; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::str::FromStr; use anyhow::{Context, Result, anyhow}; use owo_colors::OwoColorize; use toml_edit::{InlineTable, Value}; use tracing::{debug, trace, warn}; use uv_cache::Cache; use uv_cli::AuthorFrom; use uv_client::BaseClientBuilder; use uv_configuration::{ DependencyGroupsWithDefaults, ProjectBuildBackend, VersionControlError, VersionControlSystem, }; use uv_distribution_types::RequiresPython; use uv_fs::{CWD, Simplified}; use uv_git::GIT; use uv_normalize::PackageName; use uv_pep440::Version; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVariant, PythonVersionFile, VersionFileDiscoveryOptions, VersionRequest, }; use uv_scripts::{Pep723Script, ScriptTag}; use uv_settings::PythonInstallMirrors; use uv_static::EnvVars; use uv_warnings::warn_user_once; use uv_workspace::pyproject_mut::{DependencyTarget, PyProjectTomlMut}; use uv_workspace::{DiscoveryOptions, MemberDiscovery, Workspace, WorkspaceCache, WorkspaceError}; use crate::commands::ExitStatus; use crate::commands::project::{find_requires_python, init_script_python_requirement}; use crate::commands::reporters::PythonDownloadReporter; use crate::printer::Printer; /// Add one or more packages to the project requirements. #[allow(clippy::single_match_else, clippy::fn_params_excessive_bools)] pub(crate) async fn init( project_dir: &Path, explicit_path: Option<PathBuf>, name: Option<PackageName>, package: bool, init_kind: InitKind, bare: bool, description: Option<String>, no_description: bool, vcs: Option<VersionControlSystem>, build_backend: Option<ProjectBuildBackend>, no_readme: bool, author_from: Option<AuthorFrom>, pin_python: bool, python: Option<String>, install_mirrors: PythonInstallMirrors, no_workspace: bool, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { match init_kind { InitKind::Script => { let Some(path) = explicit_path.as_deref() else { anyhow::bail!("Script initialization requires a file path") }; init_script( path, bare, python, install_mirrors, client_builder, python_preference, python_downloads, cache, printer, no_workspace, no_readme, author_from, pin_python, package, no_config, preview, ) .await?; writeln!( printer.stderr(), "Initialized script at `{}`", path.user_display().cyan() )?; } InitKind::Project(project_kind) => { // Default to the current directory if a path was not provided. let path = match explicit_path { None => project_dir.to_path_buf(), Some(ref path) => std::path::absolute(path)?, }; // Make sure a project does not already exist in the given directory. if path.join("pyproject.toml").exists() { let path = std::path::absolute(&path).unwrap_or_else(|_| path.simplified().to_path_buf()); anyhow::bail!( "Project is already initialized in `{}` (`pyproject.toml` file exists)", path.display().cyan() ); } // Default to the directory name if a name was not provided. let name = match name { Some(name) => name, None => { let directory_name = path .file_name() .and_then(|path| path.to_str()) .context("Missing directory name")?; // Pre-normalize the package name by removing any leading or trailing // whitespace, and replacing any internal whitespace with hyphens. let candidate = directory_name.trim().replace(' ', "-"); match PackageName::from_owned(candidate) { Ok(name) => name, Err(_) => { let directory_description = if explicit_path.is_some() { "target directory" } else { "current directory" }; anyhow::bail!( "The {directory_description} (`{directory_name}`) is not a valid package name. Please provide a package name with `--name`." ); } } } }; init_project( &path, &name, package, project_kind, bare, description, no_description, vcs, build_backend, no_readme, author_from, pin_python, python, install_mirrors, no_workspace, client_builder, python_preference, python_downloads, no_config, cache, printer, preview, ) .await?; // Create the `README.md` if it does not already exist. if !no_readme && !bare { let readme = path.join("README.md"); if !readme.exists() { fs_err::write(readme, String::new())?; } } match explicit_path { // Initialized a project in the current directory. None => { writeln!(printer.stderr(), "Initialized project `{}`", name.cyan())?; } // Initialized a project in the given directory. Some(path) => { let path = std::path::absolute(&path) .unwrap_or_else(|_| path.simplified().to_path_buf()); writeln!( printer.stderr(), "Initialized project `{}` at `{}`", name.cyan(), path.display().cyan() )?; } } } } Ok(ExitStatus::Success) } #[allow(clippy::fn_params_excessive_bools)] async fn init_script( script_path: &Path, bare: bool, python: Option<String>, install_mirrors: PythonInstallMirrors, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, cache: &Cache, printer: Printer, no_workspace: bool, no_readme: bool, author_from: Option<AuthorFrom>, pin_python: bool, package: bool, no_config: bool, preview: Preview, ) -> Result<()> { if no_workspace { warn_user_once!("`--no-workspace` is a no-op for Python scripts, which are standalone"); } if no_readme { warn_user_once!("`--no-readme` is a no-op for Python scripts, which are standalone"); } if author_from.is_some() { warn_user_once!("`--author-from` is a no-op for Python scripts, which are standalone"); } if package { warn_user_once!("`--package` is a no-op for Python scripts, which are standalone"); } let reporter = PythonDownloadReporter::single(printer); // If the file already exists, read its content. let content = match fs_err::tokio::read(script_path).await { Ok(metadata) => { // If the file is already a script, raise an error. if ScriptTag::parse(&metadata)?.is_some() { anyhow::bail!( "`{}` is already a PEP 723 script; use `{}` to execute it", script_path.simplified_display().cyan(), "uv run".green() ); } Some(metadata) } Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, Err(err) => { return Err(err).with_context(|| { format!( "Failed to read script at `{}`", script_path.simplified_display().cyan() ) }); } }; let requires_python = init_script_python_requirement( python.as_deref(), &install_mirrors, &CWD, pin_python, python_preference, python_downloads, no_config, client_builder, cache, &reporter, preview, ) .await?; if let Some(parent) = script_path.parent() { fs_err::tokio::create_dir_all(parent).await?; } Pep723Script::create(script_path, requires_python.specifiers(), content, bare).await?; Ok(()) } /// Initialize a project (and, implicitly, a workspace root) at the given path. #[allow(clippy::fn_params_excessive_bools)] async fn init_project( path: &Path, name: &PackageName, package: bool, project_kind: InitProjectKind, bare: bool, description: Option<String>, no_description: bool, vcs: Option<VersionControlSystem>, build_backend: Option<ProjectBuildBackend>, no_readme: bool, author_from: Option<AuthorFrom>, pin_python: bool, python: Option<String>, install_mirrors: PythonInstallMirrors, no_workspace: bool, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<()> { // Discover the current workspace, if it exists. let workspace_cache = WorkspaceCache::default(); let workspace = { let parent = path.parent().expect("Project path has no parent"); match Workspace::discover( parent, &DiscoveryOptions { members: MemberDiscovery::Ignore(std::iter::once(path.to_path_buf()).collect()), ..DiscoveryOptions::default() }, &workspace_cache, ) .await { Ok(workspace) => { // Ignore the current workspace, if `--no-workspace` was provided. if no_workspace { debug!("Ignoring discovered workspace due to `--no-workspace`"); None } else { Some(workspace) } } Err(WorkspaceError::MissingPyprojectToml | WorkspaceError::NonWorkspace(_)) => { // If the user runs with `--no-workspace` and we can't find a workspace, warn. if no_workspace { warn!("`--no-workspace` was provided, but no workspace was found"); } None } Err(err) => { // If the user runs with `--no-workspace`, ignore the error. if no_workspace { warn!("Ignoring workspace discovery error due to `--no-workspace`: {err}"); None } else { return Err(err).with_context(|| { format!( "Failed to discover parent workspace; use `{}` to ignore", "uv init --no-workspace".green() ) }); } } } }; let reporter = PythonDownloadReporter::single(printer); // First, determine if there is an request for Python let python_request = if let Some(request) = python { // (1) Explicit request from user Some(PythonRequest::parse(&request)) } else if let Some(file) = PythonVersionFile::discover( path, &VersionFileDiscoveryOptions::default() .with_stop_discovery_at( workspace .as_ref() .map(Workspace::install_path) .map(PathBuf::as_ref), ) .with_no_config(no_config), ) .await? { // (2) Request from `.python-version` file.into_version() } else { None }; let (requires_python, python_pin) = determine_requires_python( path, pin_python, install_mirrors, client_builder, python_preference, python_downloads, cache, preview, workspace.as_ref(), &reporter, python_request, ) .await?; project_kind.init( name, path, &requires_python, description.as_deref(), no_description, bare, vcs, build_backend, author_from, no_readme, package, )?; if let Some(workspace) = workspace { if workspace.excludes(path)? { // If the member is excluded by the workspace, ignore it. writeln!( printer.stderr(), "Project `{}` is excluded by workspace `{}`", name.cyan(), workspace.install_path().simplified_display().cyan() )?; } else if workspace.includes(path)? { // If the member is already included in the workspace, skip the `members` addition. writeln!( printer.stderr(), "Project `{}` is already a member of workspace `{}`", name.cyan(), workspace.install_path().simplified_display().cyan() )?; } else { // Add the package to the workspace. let mut pyproject = PyProjectTomlMut::from_toml( &workspace.pyproject_toml().raw, DependencyTarget::PyProjectToml, )?; pyproject.add_workspace(path.strip_prefix(workspace.install_path())?)?; // Save the modified `pyproject.toml`. fs_err::write( workspace.install_path().join("pyproject.toml"), pyproject.to_string(), )?; writeln!( printer.stderr(), "Adding `{}` as member of workspace `{}`", name.cyan(), workspace.install_path().simplified_display().cyan() )?; } // Write .python-version if it doesn't exist in the workspace or if the version differs if let Some(python_request) = python_pin { if PythonVersionFile::discover(path, &VersionFileDiscoveryOptions::default()) .await? .filter(|file| { file.version() .is_some_and(|version| *version == python_request) && file.path().parent().is_some_and(|parent| { parent == workspace.install_path() || parent == path }) }) .is_none() { PythonVersionFile::new(path.join(".python-version")) .with_versions(vec![python_request.clone()]) .write() .await?; } } } else { // Write .python-version if it doesn't exist in the project directory. if let Some(python_request) = python_pin { if PythonVersionFile::discover(path, &VersionFileDiscoveryOptions::default()) .await? .filter(|file| file.version().is_some()) .filter(|file| file.path().parent().is_some_and(|parent| parent == path)) .is_none() { PythonVersionFile::new(path.join(".python-version")) .with_versions(vec![python_request.clone()]) .write() .await?; } } } Ok(()) } async fn determine_requires_python( path: &Path, pin_python: bool, install_mirrors: PythonInstallMirrors, client_builder: &BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, cache: &Cache, preview: Preview, workspace: Option<&Workspace>, reporter: &PythonDownloadReporter, python_request: Option<PythonRequest>, ) -> Result<(RequiresPython, Option<PythonRequest>)> { // Add a `requires-python` field to the `pyproject.toml` and return the corresponding interpreter. if let Some(python_request) = python_request { // (1) A request from the user or `.python-version` file // This can be arbitrary, i.e., not a version — in which case we may need to resolve the // interpreter let (requires_python, python_pin) = match &python_request { PythonRequest::Version(VersionRequest::MajorMinor(major, minor, variant)) => { let requires_python = RequiresPython::greater_than_equal_version(&Version::new([ u64::from(*major), u64::from(*minor), ])); let python_pin = if pin_python { Some(PythonRequest::Version(VersionRequest::MajorMinor( *major, *minor, *variant, ))) } else { None }; (requires_python, python_pin) } PythonRequest::Version(VersionRequest::MajorMinorPatch( major, minor, patch, variant, )) => { let requires_python = RequiresPython::greater_than_equal_version(&Version::new([ u64::from(*major), u64::from(*minor), u64::from(*patch), ])); let python_pin = if pin_python { Some(PythonRequest::Version(VersionRequest::MajorMinorPatch( *major, *minor, *patch, *variant, ))) } else { None }; (requires_python, python_pin) } python_request @ PythonRequest::Version(VersionRequest::Range(specifiers, variant)) => { let requires_python = RequiresPython::from_specifiers(specifiers); let python_pin = if pin_python { let interpreter = PythonInstallation::find_or_download( Some(python_request), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); Some(PythonRequest::Version(VersionRequest::MajorMinor( interpreter.python_major(), interpreter.python_minor(), *variant, ))) } else { None }; (requires_python, python_pin) } python_request => { let interpreter = PythonInstallation::find_or_download( Some(python_request), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); let requires_python = RequiresPython::greater_than_equal_version(&interpreter.python_minor_version()); let python_pin = if pin_python { Some(PythonRequest::Version(VersionRequest::MajorMinor( interpreter.python_major(), interpreter.python_minor(), PythonVariant::Default, ))) } else { None }; (requires_python, python_pin) } }; debug!("Using Python version `{requires_python}` from request `{python_request}`"); Ok((requires_python, python_pin)) } else if let Ok(virtualenv) = PythonEnvironment::from_root(path.join(".venv"), cache) { // (2) An existing Python environment in the target directory let interpreter = virtualenv.into_interpreter(); let requires_python = RequiresPython::greater_than_equal_version(&interpreter.python_minor_version()); // Pin to the minor version. let python_pin = if pin_python { Some(PythonRequest::Version(VersionRequest::MajorMinor( interpreter.python_major(), interpreter.python_minor(), PythonVariant::Default, ))) } else { None }; debug!( "Using Python version `{requires_python}` from existing virtual environment in project" ); Ok((requires_python, python_pin)) } else if let Some(requires_python) = workspace .as_ref() .map(|workspace| find_requires_python(workspace, &DependencyGroupsWithDefaults::none())) .transpose()? .flatten() { // (3) `requires-python` from the workspace let python_request = PythonRequest::Version(VersionRequest::Range( requires_python.specifiers().clone(), PythonVariant::Default, )); // Pin to the minor version. let python_pin = if pin_python { let interpreter = PythonInstallation::find_or_download( Some(&python_request), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); Some(PythonRequest::Version(VersionRequest::MajorMinor( interpreter.python_major(), interpreter.python_minor(), PythonVariant::Default, ))) } else { None }; debug!("Using Python version `{requires_python}` from project workspace"); Ok((requires_python, python_pin)) } else { // (4) Default to the system Python let interpreter = PythonInstallation::find_or_download( None, EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); let requires_python = RequiresPython::greater_than_equal_version(&interpreter.python_minor_version()); // Pin to the minor version. let python_pin = if pin_python { Some(PythonRequest::Version(VersionRequest::MajorMinor( interpreter.python_major(), interpreter.python_minor(), PythonVariant::Default, ))) } else { None }; debug!("Using Python version `{requires_python}` from default interpreter"); Ok((requires_python, python_pin)) } } /// The kind of entity to initialize (either a PEP 723 script or a Python project). #[derive(Debug, Copy, Clone)] pub(crate) enum InitKind { /// Initialize a Python project. Project(InitProjectKind), /// Initialize a PEP 723 script. Script, } impl Default for InitKind { fn default() -> Self { Self::Project(InitProjectKind::default()) } } /// The kind of Python project to initialize (either an application or a library). #[derive(Debug, Copy, Clone, Default)] pub(crate) enum InitProjectKind { /// Initialize a Python application. #[default] Application, /// Initialize a Python library. Library, } impl InitKind { /// Returns `true` if the project should be packaged by default. pub(crate) fn packaged_by_default(self) -> bool { matches!(self, Self::Project(InitProjectKind::Library)) } } impl InitProjectKind { /// Initialize this project kind at the target path. #[allow(clippy::fn_params_excessive_bools)] fn init( self, name: &PackageName, path: &Path, requires_python: &RequiresPython, description: Option<&str>, no_description: bool, bare: bool, vcs: Option<VersionControlSystem>, build_backend: Option<ProjectBuildBackend>, author_from: Option<AuthorFrom>, no_readme: bool, package: bool, ) -> Result<()> { match self { Self::Application => Self::init_application( name, path, requires_python, description, no_description, bare, vcs, build_backend, author_from, no_readme, package, ), Self::Library => Self::init_library( name, path, requires_python, description, no_description, bare, vcs, build_backend, author_from, no_readme, package, ), } } /// Initialize a Python application at the target path. #[allow(clippy::fn_params_excessive_bools)] fn init_application( name: &PackageName, path: &Path, requires_python: &RequiresPython, description: Option<&str>, no_description: bool, bare: bool, vcs: Option<VersionControlSystem>, build_backend: Option<ProjectBuildBackend>, author_from: Option<AuthorFrom>, no_readme: bool, package: bool, ) -> Result<()> { fs_err::create_dir_all(path)?; // Initialize the version control system first so that Git configuration can properly // read conditional includes that depend on the repository path. init_vcs(path, vcs)?; // Do no fill in `authors` for non-packaged applications unless explicitly requested. let author_from = author_from.unwrap_or_else(|| { if package { AuthorFrom::default() } else { AuthorFrom::None } }); let author = get_author_info(path, author_from); // Create the `pyproject.toml` let mut pyproject = pyproject_project( name, requires_python, author.as_ref(), description, no_description, no_readme || bare, ); // Include additional project configuration for packaged applications if package { // Since it'll be packaged, we can add a `[project.scripts]` entry if !bare { pyproject.push('\n'); pyproject.push_str(&pyproject_project_scripts(name, name.as_str(), "main")); } // Add a build system let build_backend = build_backend.unwrap_or(ProjectBuildBackend::Uv); pyproject.push('\n'); pyproject.push_str(&pyproject_build_system(name, build_backend)); pyproject_build_backend_prerequisites(name, path, build_backend)?; if !bare { // Generate `src` files generate_package_scripts(name, path, build_backend, false)?; } } else { // Create `main.py` if it doesn't exist // (This isn't intended to be a particularly special or magical filename, just nice) // TODO(zanieb): Only create `main.py` if there are no other Python files? let main_py = path.join("main.py"); if !main_py.try_exists()? && !bare { fs_err::write( path.join("main.py"), indoc::formatdoc! {r#" def main(): print("Hello from {name}!") if __name__ == "__main__": main() "#}, )?; } } fs_err::write(path.join("pyproject.toml"), pyproject)?; Ok(()) } /// Initialize a library project at the target path. #[allow(clippy::fn_params_excessive_bools)] fn init_library( name: &PackageName, path: &Path, requires_python: &RequiresPython, description: Option<&str>, no_description: bool, bare: bool, vcs: Option<VersionControlSystem>, build_backend: Option<ProjectBuildBackend>, author_from: Option<AuthorFrom>, no_readme: bool, package: bool, ) -> Result<()> { if !package { return Err(anyhow!("Library projects must be packaged")); } fs_err::create_dir_all(path)?; // Initialize the version control system first so that Git configuration can properly // read conditional includes that depend on the repository path. init_vcs(path, vcs)?; let author = get_author_info(path, author_from.unwrap_or_default()); // Create the `pyproject.toml` let mut pyproject = pyproject_project( name, requires_python, author.as_ref(), description, no_description, no_readme || bare, ); // Always include a build system if the project is packaged. let build_backend = build_backend.unwrap_or(ProjectBuildBackend::Uv); pyproject.push('\n'); pyproject.push_str(&pyproject_build_system(name, build_backend)); pyproject_build_backend_prerequisites(name, path, build_backend)?; fs_err::write(path.join("pyproject.toml"), pyproject)?; // Generate `src` files if !bare { generate_package_scripts(name, path, build_backend, true)?; } Ok(()) } } #[derive(Debug)] enum Author { Name(String), Email(String), NameEmail { name: String, email: String }, } impl Author { fn to_toml_string(&self) -> String { let mut inline = InlineTable::new(); match self { Self::NameEmail { name, email } => { inline.insert("name", Value::from(name)); inline.insert("email", Value::from(email)); } Self::Name(name) => { inline.insert("name", Value::from(name)); } Self::Email(email) => { inline.insert("email", Value::from(email)); } } inline.to_string() } } /// Generate the `[project]` section of a `pyproject.toml`. fn pyproject_project( name: &PackageName, requires_python: &RequiresPython, author: Option<&Author>, description: Option<&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/src/commands/project/export.rs
crates/uv/src/commands/project/export.rs
use std::env; use std::ffi::OsStr; use std::io::Write; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, anyhow}; use clap::ValueEnum; use itertools::Itertools; use owo_colors::OwoColorize; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::{ Concurrency, DependencyGroups, EditableMode, ExportFormat, ExtrasSpecification, InstallOptions, }; use uv_normalize::{DefaultExtras, DefaultGroups, PackageName}; use uv_preview::Preview; use uv_python::{PythonDownloads, PythonPreference, PythonRequest}; use uv_requirements::is_pylock_toml; use uv_resolver::{PylockToml, RequirementsTxtExport, cyclonedx_json}; use uv_scripts::Pep723Script; use uv_settings::PythonInstallMirrors; use uv_workspace::{DiscoveryOptions, MemberDiscovery, VirtualProject, Workspace, WorkspaceCache}; use crate::commands::pip::loggers::DefaultResolveLogger; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::{LockMode, LockOperation}; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ ProjectError, ProjectInterpreter, ScriptInterpreter, UniversalState, default_dependency_groups, detect_conflicts, }; use crate::commands::{ExitStatus, OutputWriter, diagnostics}; use crate::printer::Printer; use crate::settings::{LockCheck, ResolverSettings}; #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] enum ExportTarget { /// A PEP 723 script, with inline metadata. Script(Pep723Script), /// A project with a `pyproject.toml`. Project(VirtualProject), } impl<'lock> From<&'lock ExportTarget> for LockTarget<'lock> { fn from(value: &'lock ExportTarget) -> Self { match value { ExportTarget::Script(script) => Self::Script(script), ExportTarget::Project(project) => Self::Workspace(project.workspace()), } } } /// Export the project's `uv.lock` in an alternate format. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn export( project_dir: &Path, format: Option<ExportFormat>, all_packages: bool, package: Vec<PackageName>, prune: Vec<PackageName>, hashes: bool, install_options: InstallOptions, output_file: Option<PathBuf>, extras: ExtrasSpecification, groups: DependencyGroups, editable: Option<EditableMode>, lock_check: LockCheck, frozen: bool, include_annotations: bool, include_header: bool, script: Option<Pep723Script>, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: ResolverSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, concurrency: Concurrency, no_config: bool, quiet: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Identify the target. let workspace_cache = WorkspaceCache::default(); let target = if let Some(script) = script { ExportTarget::Script(script) } else { let project = if frozen { VirtualProject::discover( project_dir, &DiscoveryOptions { members: MemberDiscovery::None, ..DiscoveryOptions::default() }, &workspace_cache, ) .await? } else if let [name] = package.as_slice() { VirtualProject::Project( Workspace::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache) .await? .with_current_project(name.clone()) .with_context(|| format!("Package `{name}` not found in workspace"))?, ) } else { let project = VirtualProject::discover( project_dir, &DiscoveryOptions::default(), &workspace_cache, ) .await?; for name in &package { if !project.workspace().packages().contains_key(name) { return Err(anyhow::anyhow!("Package `{name}` not found in workspace")); } } project }; ExportTarget::Project(project) }; // Determine the default groups to include. let default_groups = match &target { ExportTarget::Project(project) => default_dependency_groups(project.pyproject_toml())?, ExportTarget::Script(_) => DefaultGroups::default(), }; // Determine the default extras to include. let default_extras = match &target { ExportTarget::Project(_project) => DefaultExtras::default(), ExportTarget::Script(_) => DefaultExtras::default(), }; let groups = groups.with_defaults(default_groups); let extras = extras.with_defaults(default_extras); // Find an interpreter for the project, unless `--frozen` is set. let interpreter = if frozen { None } else { Some(match &target { ExportTarget::Script(script) => ScriptInterpreter::discover( script.into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, no_config, false, Some(false), cache, printer, preview, ) .await? .into_interpreter(), ExportTarget::Project(project) => ProjectInterpreter::discover( project.workspace(), project_dir, &groups, python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, Some(false), cache, printer, preview, ) .await? .into_interpreter(), }) }; // Determine the lock mode. let mode = if frozen { LockMode::Frozen } else if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(interpreter.as_ref().unwrap(), lock_check) } else if matches!(target, ExportTarget::Script(_)) && !LockTarget::from(&target).lock_path().is_file() { // If we're locking a script, avoid creating a lockfile if it doesn't already exist. LockMode::DryRun(interpreter.as_ref().unwrap()) } else { LockMode::Write(interpreter.as_ref().unwrap()) }; // Initialize any shared state. let state = UniversalState::default(); // Lock the project. let lock = match Box::pin( LockOperation::new( mode, &settings, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &workspace_cache, printer, preview, ) .execute((&target).into()), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // Identify the installation target. let target = match &target { ExportTarget::Project(VirtualProject::Project(project)) => { if all_packages { InstallTarget::Workspace { workspace: project.workspace(), lock: &lock, } } else { match package.as_slice() { // By default, install the root project. [] => InstallTarget::Project { workspace: project.workspace(), name: project.project_name(), lock: &lock, }, [name] => InstallTarget::Project { workspace: project.workspace(), name, lock: &lock, }, names => InstallTarget::Projects { workspace: project.workspace(), names, lock: &lock, }, } } } ExportTarget::Project(VirtualProject::NonProject(workspace)) => { if all_packages { InstallTarget::NonProjectWorkspace { workspace, lock: &lock, } } else { match package.as_slice() { // By default, install the entire workspace. [] => InstallTarget::NonProjectWorkspace { workspace, lock: &lock, }, [name] => InstallTarget::Project { workspace, name, lock: &lock, }, names => InstallTarget::Projects { workspace, names, lock: &lock, }, } } } ExportTarget::Script(script) => InstallTarget::Script { script, lock: &lock, }, }; // Validate that the set of requested extras and development groups are defined in the lockfile. target.validate_extras(&extras)?; target.validate_groups(&groups)?; if output_file .as_deref() .and_then(Path::file_name) .is_some_and(|name| name.eq_ignore_ascii_case("pyproject.toml")) { return Err(anyhow!( "`pyproject.toml` is not a supported output format for `{}` (supported formats: {})", "uv export".green(), ExportFormat::value_variants() .iter() .filter_map(clap::ValueEnum::to_possible_value) .map(|value| value.get_name().to_string()) .join(", ") )); } // Write the resolved dependencies to the output channel. let mut writer = OutputWriter::new(!quiet || output_file.is_none(), output_file.as_deref()); // Determine the output format. let format = format.unwrap_or_else(|| { if output_file .as_deref() .and_then(Path::extension) .is_some_and(|ext| ext.eq_ignore_ascii_case("txt")) { ExportFormat::RequirementsTxt } else if output_file .as_deref() .and_then(Path::file_name) .and_then(OsStr::to_str) .is_some_and(is_pylock_toml) { ExportFormat::PylockToml } else { ExportFormat::RequirementsTxt } }); // Skip conflict detection for CycloneDX exports, as SBOMs are meant to document all dependencies including conflicts. if !matches!(format, ExportFormat::CycloneDX1_5) { detect_conflicts(&target, &extras, &groups)?; } // If the user is exporting to PEP 751, ensure the filename matches the specification. if matches!(format, ExportFormat::PylockToml) { if let Some(file_name) = output_file .as_deref() .and_then(Path::file_name) .and_then(OsStr::to_str) { if !is_pylock_toml(file_name) { return Err(anyhow!( "Expected the output filename to start with `pylock.` and end with `.toml` (e.g., `pylock.toml`, `pylock.dev.toml`); `{file_name}` won't be recognized as a `pylock.toml` file in subsequent commands", )); } } } // Generate the export. match format { ExportFormat::RequirementsTxt => { let export = RequirementsTxtExport::from_lock( &target, &prune, &extras, &groups, include_annotations, editable, hashes, &install_options, )?; if include_header { writeln!( writer, "{}", "# This file was autogenerated by uv via the following command:".green() )?; writeln!(writer, "{}", format!("# {}", cmd()).green())?; } write!(writer, "{export}")?; } ExportFormat::PylockToml => { let export = PylockToml::from_lock( &target, &prune, &extras, &groups, include_annotations, editable, &install_options, )?; if include_header { writeln!( writer, "{}", "# This file was autogenerated by uv via the following command:".green() )?; writeln!(writer, "{}", format!("# {}", cmd()).green())?; } write!(writer, "{}", export.to_toml()?)?; } ExportFormat::CycloneDX1_5 => { let export = cyclonedx_json::from_lock( &target, &prune, &extras, &groups, include_annotations, &install_options, preview, all_packages, )?; export.output_as_json_v1_5(&mut writer)?; } } writer.commit().await?; Ok(ExitStatus::Success) } /// Format the uv command used to generate the output file. fn cmd() -> String { let args = env::args_os() .skip(1) .map(|arg| arg.to_string_lossy().to_string()) .scan(None, move |skip_next, arg| { if matches!(skip_next, Some(true)) { // Reset state; skip this iteration. *skip_next = None; return Some(None); } // Always skip the `--upgrade` flag. if arg == "--upgrade" || arg == "-U" { *skip_next = None; return Some(None); } // Always skip the `--upgrade-package` and mark the next item to be skipped if arg == "--upgrade-package" || arg == "-P" { *skip_next = Some(true); return Some(None); } // Skip only this argument if option and value are together if arg.starts_with("--upgrade-package=") || arg.starts_with("-P") { // Reset state; skip this iteration. *skip_next = None; return Some(None); } // Always skip the `--quiet` flag. if arg == "--quiet" || arg == "-q" { *skip_next = None; return Some(None); } // Always skip the `--verbose` flag. if arg == "--verbose" || arg == "-v" { *skip_next = None; return Some(None); } // Return the argument. Some(Some(arg)) }) .flatten() .join(" "); format!("uv {args}") }
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/src/commands/project/add.rs
crates/uv/src/commands/project/add.rs
use std::collections::BTreeMap; use std::collections::hash_map::Entry; use std::fmt::Write; use std::io; use std::path::Path; use std::str::FromStr; use std::sync::Arc; use anyhow::{Context, Result, bail}; use itertools::Itertools; use owo_colors::OwoColorize; use rustc_hash::{FxBuildHasher, FxHashMap}; use tracing::{debug, warn}; use uv_cache::Cache; use uv_cache_key::RepositoryUrl; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ Concurrency, Constraints, DependencyGroups, DependencyGroupsWithDefaults, DevMode, DryRun, ExtrasSpecification, ExtrasSpecificationWithDefaults, GitLfsSetting, InstallOptions, SourceStrategy, }; use uv_dispatch::BuildDispatch; use uv_distribution::{DistributionDatabase, LoweredExtraBuildDependencies}; use uv_distribution_types::{ Index, IndexName, IndexUrl, IndexUrls, NameRequirementSpecification, Requirement, RequirementSource, UnresolvedRequirement, VersionId, }; use uv_fs::{LockedFile, LockedFileError, Simplified}; use uv_git::GIT_STORE; use uv_normalize::{DEV_DEPENDENCIES, DefaultExtras, DefaultGroups, ExtraName, PackageName}; use uv_pep508::{MarkerTree, VersionOrUrl}; use uv_preview::{Preview, PreviewFeatures}; use uv_python::{Interpreter, PythonDownloads, PythonEnvironment, PythonPreference, PythonRequest}; use uv_redacted::DisplaySafeUrl; use uv_requirements::{NamedRequirementsResolver, RequirementsSource, RequirementsSpecification}; use uv_resolver::FlatIndex; use uv_scripts::{Pep723Metadata, Pep723Script}; use uv_settings::PythonInstallMirrors; use uv_types::{BuildIsolation, HashStrategy}; use uv_warnings::warn_user_once; use uv_workspace::pyproject::{DependencyType, Source, SourceError, Sources, ToolUvSources}; use uv_workspace::pyproject_mut::{AddBoundsKind, ArrayEdit, DependencyTarget, PyProjectTomlMut}; use uv_workspace::{DiscoveryOptions, VirtualProject, Workspace, WorkspaceCache}; use crate::commands::pip::loggers::{ DefaultInstallLogger, DefaultResolveLogger, SummaryResolveLogger, }; use crate::commands::pip::operations::Modifications; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::LockMode; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ PlatformState, ProjectEnvironment, ProjectError, ProjectInterpreter, ScriptInterpreter, UniversalState, default_dependency_groups, init_script_python_requirement, }; use crate::commands::reporters::{PythonDownloadReporter, ResolverReporter}; use crate::commands::{ExitStatus, ScriptPath, diagnostics, project}; use crate::printer::Printer; use crate::settings::{LockCheck, ResolverInstallerSettings}; /// Add one or more packages to the project requirements. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn add( project_dir: &Path, lock_check: LockCheck, frozen: bool, active: Option<bool>, no_sync: bool, no_install_project: bool, only_install_project: bool, no_install_workspace: bool, only_install_workspace: bool, no_install_local: bool, only_install_local: bool, no_install_package: Vec<PackageName>, only_install_package: Vec<PackageName>, requirements: Vec<RequirementsSource>, constraints: Vec<RequirementsSource>, marker: Option<MarkerTree>, editable: Option<bool>, dependency_type: DependencyType, raw: bool, bounds: Option<AddBoundsKind>, indexes: Vec<Index>, rev: Option<String>, tag: Option<String>, branch: Option<String>, lfs: GitLfsSetting, extras_of_dependency: Vec<ExtraName>, package: Option<PackageName>, python: Option<String>, workspace: Option<bool>, install_mirrors: PythonInstallMirrors, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, script: Option<ScriptPath>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if bounds.is_some() && !preview.is_enabled(PreviewFeatures::ADD_BOUNDS) { warn_user_once!( "The `bounds` option is in preview and may change in any future release. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::ADD_BOUNDS ); } if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !settings.resolver.extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } for source in &requirements { match source { RequirementsSource::PyprojectToml(_) => { bail!("Adding requirements from a `pyproject.toml` is not supported in `uv add`"); } RequirementsSource::SetupPy(_) => { bail!("Adding requirements from a `setup.py` is not supported in `uv add`"); } RequirementsSource::Pep723Script(_) => { bail!("Adding requirements from a PEP 723 script is not supported in `uv add`"); } RequirementsSource::SetupCfg(_) => { bail!("Adding requirements from a `setup.cfg` is not supported in `uv add`"); } RequirementsSource::PylockToml(_) => { bail!("Adding requirements from a `pylock.toml` is not supported in `uv add`"); } RequirementsSource::Package(_) | RequirementsSource::Editable(_) | RequirementsSource::RequirementsTxt(_) | RequirementsSource::Extensionless(_) | RequirementsSource::EnvironmentYml(_) => {} } } let reporter = PythonDownloadReporter::single(printer); // Determine what defaults/extras we're explicitly enabling let (extras, groups) = match &dependency_type { DependencyType::Production => { let extras = ExtrasSpecification::from_extra(vec![]); let groups = DependencyGroups::from_dev_mode(DevMode::Exclude); (extras, groups) } DependencyType::Dev => { let extras = ExtrasSpecification::from_extra(vec![]); let groups = DependencyGroups::from_dev_mode(DevMode::Include); (extras, groups) } DependencyType::Optional(extra_name) => { let extras = ExtrasSpecification::from_extra(vec![extra_name.clone()]); let groups = DependencyGroups::from_dev_mode(DevMode::Exclude); (extras, groups) } DependencyType::Group(group_name) => { let extras = ExtrasSpecification::from_extra(vec![]); let groups = DependencyGroups::from_group(group_name.clone()); (extras, groups) } }; // Default extras currently always disabled let defaulted_extras = extras.with_defaults(DefaultExtras::default()); // Default groups we need the actual project for, interpreter discovery will use this! let defaulted_groups; let mut target = if let Some(script) = script { // If we found a PEP 723 script and the user provided a project-only setting, warn. if package.is_some() { warn_user_once!( "`--package` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if let LockCheck::Enabled(lock_check) = lock_check { warn_user_once!( "`{lock_check}` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if frozen { warn_user_once!( "`--frozen` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if no_sync { warn_user_once!( "`--no-sync` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } // If we found a script, add to the existing metadata. Otherwise, create a new inline // metadata tag. let script = match script { ScriptPath::Script(script) => script, ScriptPath::Path(path) => { let requires_python = init_script_python_requirement( python.as_deref(), &install_mirrors, project_dir, false, python_preference, python_downloads, no_config, &client_builder, cache, &reporter, preview, ) .await?; Pep723Script::init(&path, requires_python.specifiers()).await? } }; // Scripts don't actually have groups defaulted_groups = groups.with_defaults(DefaultGroups::default()); // Discover the interpreter. let interpreter = ScriptInterpreter::discover( (&script).into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); AddTarget::Script(script, Box::new(interpreter)) } else { // Find the project in the workspace. // No workspace caching since `uv add` changes the workspace definition. let project = if let Some(package) = package { VirtualProject::Project( Workspace::discover( project_dir, &DiscoveryOptions::default(), &WorkspaceCache::default(), ) .await? .with_current_project(package.clone()) .with_context(|| format!("Package `{package}` not found in workspace"))?, ) } else { VirtualProject::discover( project_dir, &DiscoveryOptions::default(), &WorkspaceCache::default(), ) .await? }; // For non-project workspace roots, allow dev dependencies, but nothing else. // TODO(charlie): Automatically "upgrade" the project by adding a `[project]` table. if project.is_non_project() { match dependency_type { DependencyType::Production => { bail!( "Project is missing a `[project]` table; add a `[project]` table to use production dependencies, or run `{}` instead", "uv add --dev".green() ) } DependencyType::Optional(_) => { bail!( "Project is missing a `[project]` table; add a `[project]` table to use optional dependencies, or run `{}` instead", "uv add --dev".green() ) } DependencyType::Group(_) => {} DependencyType::Dev => (), } } // Enable the default groups of the project defaulted_groups = groups.with_defaults(default_dependency_groups(project.pyproject_toml())?); if frozen || no_sync { // Discover the interpreter. let interpreter = ProjectInterpreter::discover( project.workspace(), project_dir, &defaulted_groups, python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); AddTarget::Project(project, Box::new(PythonTarget::Interpreter(interpreter))) } else { // Discover or create the virtual environment. let environment = ProjectEnvironment::get_or_init( project.workspace(), &defaulted_groups, python.as_deref().map(PythonRequest::parse), &install_mirrors, &client_builder, python_preference, python_downloads, no_sync, no_config, active, cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()?; AddTarget::Project(project, Box::new(PythonTarget::Environment(environment))) } }; let _lock = target .acquire_lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); let client_builder = client_builder .clone() .keyring(settings.resolver.keyring_provider); // Read the requirements. let RequirementsSpecification { requirements, constraints, .. } = RequirementsSpecification::from_sources( &requirements, &constraints, &[], &[], None, &client_builder, ) .await?; // Initialize any shared state. let state = PlatformState::default(); // Resolve any unnamed requirements. let requirements = { // Partition the requirements into named and unnamed requirements. let (mut requirements, unnamed): (Vec<_>, Vec<_>) = requirements .into_iter() .map(|spec| { spec.requirement.augment_requirement( rev.as_deref(), tag.as_deref(), branch.as_deref(), lfs.into(), marker, ) }) .partition_map(|requirement| match requirement { UnresolvedRequirement::Named(requirement) => itertools::Either::Left(requirement), UnresolvedRequirement::Unnamed(requirement) => { itertools::Either::Right(requirement) } }); // Resolve any unnamed requirements. if !unnamed.is_empty() { // TODO(charlie): These are all default values. We should consider whether we want to // make them optional on the downstream APIs. let build_constraints = Constraints::default(); let build_hasher = HashStrategy::default(); let hasher = HashStrategy::default(); let sources = SourceStrategy::Enabled; // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(settings.resolver.index_locations.clone()) .index_strategy(settings.resolver.index_strategy) .markers(target.interpreter().markers()) .platform(target.interpreter().platform()) .build(); // Determine whether to enable build isolation. let environment; let build_isolation = match &settings.resolver.build_isolation { uv_configuration::BuildIsolation::Isolate => BuildIsolation::Isolated, uv_configuration::BuildIsolation::Shared => { environment = PythonEnvironment::from_interpreter(target.interpreter().clone()); BuildIsolation::Shared(&environment) } uv_configuration::BuildIsolation::SharedPackage(packages) => { environment = PythonEnvironment::from_interpreter(target.interpreter().clone()); BuildIsolation::SharedPackage(&environment, packages) } }; // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache); let entries = client .fetch_all( settings .resolver .index_locations .flat_indexes() .map(Index::url), ) .await?; FlatIndex::from_entries(entries, None, &hasher, &settings.resolver.build_options) }; // Lower the extra build dependencies, if any. let extra_build_requires = if let AddTarget::Project(project, _) = &target { LoweredExtraBuildDependencies::from_workspace( settings.resolver.extra_build_dependencies.clone(), project.workspace(), &settings.resolver.index_locations, settings.resolver.sources, client.credentials_cache(), )? } else { LoweredExtraBuildDependencies::from_non_lowered( settings.resolver.extra_build_dependencies.clone(), ) } .into_inner(); // Create a build dispatch. let extra_build_variables = settings.resolver.extra_build_variables.clone(); let build_dispatch = BuildDispatch::new( &client, cache, &build_constraints, target.interpreter(), &settings.resolver.index_locations, &flat_index, &settings.resolver.dependency_metadata, state.clone().into_inner(), settings.resolver.index_strategy, &settings.resolver.config_setting, &settings.resolver.config_settings_package, build_isolation, &extra_build_requires, &extra_build_variables, settings.resolver.link_mode, &settings.resolver.build_options, &build_hasher, settings.resolver.exclude_newer.clone(), sources, // No workspace caching since `uv add` changes the workspace definition. WorkspaceCache::default(), concurrency, preview, ); requirements.extend( NamedRequirementsResolver::new( &hasher, state.index(), DistributionDatabase::new(&client, &build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(unnamed.into_iter()) .await?, ); } requirements }; // If any of the requirements are self-dependencies, bail. if matches!(dependency_type, DependencyType::Production) { if let AddTarget::Project(project, _) = &target { if let Some(project_name) = project.project_name() { for requirement in &requirements { if requirement.name == *project_name { bail!( "Requirement name `{}` matches project name `{}`, but self-dependencies are not permitted without the `--dev` or `--optional` flags. If your project name (`{}`) is shadowing that of a third-party dependency, consider renaming the project.", requirement.name.cyan(), project_name.cyan(), project_name.cyan(), ); } } } } } // Store the content prior to any modifications. let snapshot = target.snapshot().await?; // If the user provides a single, named index, pin all requirements to that index. let index = indexes .first() .as_ref() .and_then(|index| index.name.as_ref()) .filter(|_| indexes.len() == 1) .inspect(|index| { debug!("Pinning all requirements to index: `{index}`"); }); // Track modification status, for reverts. let mut modified = false; // Determine whether to use workspace mode. let use_workspace = match workspace { Some(workspace) => workspace, None => { // Check if we're in a project (not a script), and if any requirements are path // dependencies within the workspace. if let AddTarget::Project(ref project, _) = target { let workspace_root = project.workspace().install_path(); requirements.iter().any(|req| { if let RequirementSource::Directory { install_path, .. } = &req.source { let absolute_path = if install_path.is_absolute() { install_path.to_path_buf() } else { project.root().join(install_path) }; absolute_path.starts_with(workspace_root) } else { false } }) } else { false } } }; // If workspace mode is enabled, add any members to the `workspace` section of the // `pyproject.toml` file. if use_workspace { let AddTarget::Project(project, python_target) = target else { unreachable!("`--workspace` and `--script` are conflicting options"); }; let mut toml = PyProjectTomlMut::from_toml( &project.workspace().pyproject_toml().raw, DependencyTarget::PyProjectToml, )?; // Check each requirement to see if it's a path dependency for requirement in &requirements { if let RequirementSource::Directory { install_path, .. } = &requirement.source { let absolute_path = if install_path.is_absolute() { install_path.to_path_buf() } else { project.root().join(install_path) }; // Either `--workspace` was provided explicitly, or it was omitted but the path is // within the workspace root. let use_workspace = workspace.unwrap_or_else(|| { absolute_path.starts_with(project.workspace().install_path()) }); if !use_workspace { continue; } // If the project is already a member of the workspace, skip it. if project.workspace().includes(&absolute_path)? { continue; } let relative_path = absolute_path .strip_prefix(project.workspace().install_path()) .unwrap_or(&absolute_path); toml.add_workspace(relative_path)?; modified |= true; writeln!( printer.stderr(), "Added `{}` to workspace members", relative_path.user_display().cyan() )?; } } // If we modified the workspace root, we need to reload it entirely, since this can impact // the discovered members, etc. target = if modified { let workspace_content = toml.to_string(); fs_err::write( project.workspace().install_path().join("pyproject.toml"), &workspace_content, )?; AddTarget::Project( VirtualProject::discover( project.root(), &DiscoveryOptions::default(), &WorkspaceCache::default(), ) .await?, python_target, ) } else { AddTarget::Project(project, python_target) } } let mut toml = match &target { AddTarget::Script(script, _) => { PyProjectTomlMut::from_toml(&script.metadata.raw, DependencyTarget::Script) } AddTarget::Project(project, _) => PyProjectTomlMut::from_toml( &project.pyproject_toml().raw, DependencyTarget::PyProjectToml, ), }?; let edits = edits( requirements, &target, editable, &dependency_type, raw, rev.as_deref(), tag.as_deref(), branch.as_deref(), lfs, &extras_of_dependency, index, &mut toml, )?; // If no requirements were added but a dependency group or optional dependency was specified, // ensure the group/extra exists. This handles the case where `uv add -r requirements.txt // --group <name>` or `uv add -r requirements.txt --optional <extra>` is called with an empty // requirements file. if edits.is_empty() { match &dependency_type { DependencyType::Group(group) => { toml.ensure_dependency_group(group)?; } DependencyType::Optional(extra) => { toml.ensure_optional_dependency(extra)?; } _ => {} } } // Validate any indexes that were provided on the command-line to ensure // they point to existing non-empty directories when using path URLs. let mut valid_indexes = Vec::with_capacity(indexes.len()); for index in indexes { if let IndexUrl::Path(url) = &index.url { let path = url .to_file_path() .map_err(|()| anyhow::anyhow!("Invalid file path in index URL: {url}"))?; if !path.is_dir() { bail!("Directory not found for index: {url}"); } if fs_err::read_dir(&path)?.next().is_none() { warn_user_once!("Index directory `{url}` is empty, skipping"); continue; } } valid_indexes.push(index); } let indexes = valid_indexes; // Add any indexes that were provided on the command-line, in priority order. if !raw { let urls = IndexUrls::from_indexes(indexes); let mut indexes = urls.defined_indexes().collect::<Vec<_>>(); indexes.reverse(); for index in indexes { toml.add_index(index)?; } } let content = toml.to_string(); // Save the modified `pyproject.toml` or script. modified |= target.write(&content)?; // If `--frozen`, exit early. There's no reason to lock and sync, since we don't need a `uv.lock` // to exist at all. if frozen { return Ok(ExitStatus::Success); } // If we're modifying a script, and lockfile doesn't exist, avoid creating it. We still need // to perform resolution, since we want to use the resolved versions to populate lower bounds // in the script. let dry_run = if let AddTarget::Script(ref script, _) = target { !LockTarget::from(script).lock_path().is_file() } else { false }; // Update the `pypackage.toml` in-memory. let target = target.update(&content)?; // Set the Ctrl-C handler to revert changes on exit. let _ = ctrlc::set_handler({ let snapshot = snapshot.clone(); move || { if modified { let _ = snapshot.revert(); } #[allow(clippy::exit, clippy::cast_possible_wrap)] std::process::exit(if cfg!(windows) { 0xC000_013A_u32 as i32 } else { 130 }); } }); // Use separate state for locking and syncing. let lock_state = state.fork(); let sync_state = state; match Box::pin(lock_and_sync( target, &mut toml, &edits, lock_state, sync_state, lock_check, no_install_project, only_install_project, no_install_workspace, only_install_workspace, no_install_local, only_install_local, no_install_package.clone(), only_install_package.clone(), &defaulted_extras, &defaulted_groups, raw, bounds, dry_run, constraints, &settings, &client_builder, installer_metadata, concurrency, cache, printer, preview, )) .await { Ok(()) => Ok(ExitStatus::Success), Err(err) => { if modified { let _ = snapshot.revert(); } match err { ProjectError::Operation(err) => diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()).with_hint(format!("If you want to add the package regardless of the failed resolution, provide the `{}` flag to skip locking and syncing.", "--frozen".green())) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())), err => Err(err.into()), } } } } fn edits( requirements: Vec<Requirement>, target: &AddTarget, editable: Option<bool>, dependency_type: &DependencyType, raw: bool, rev: Option<&str>, tag: Option<&str>, branch: Option<&str>, lfs: GitLfsSetting, extras: &[ExtraName], index: Option<&IndexName>, toml: &mut PyProjectTomlMut, ) -> Result<Vec<DependencyEdit>> { let mut edits = Vec::<DependencyEdit>::with_capacity(requirements.len()); for mut requirement in requirements { // Add the specified extras. let mut ex = requirement.extras.to_vec(); ex.extend(extras.iter().cloned()); ex.sort_unstable(); ex.dedup(); requirement.extras = ex.into_boxed_slice(); let (requirement, source) = match target { AddTarget::Script(_, _) | AddTarget::Project(_, _) if raw => { (uv_pep508::Requirement::from(requirement), None) } AddTarget::Script(script, _) => { let script_path = std::path::absolute(&script.path)?; let script_dir = script_path.parent().expect("script path has no parent"); let existing_sources = Some(script.sources()); resolve_requirement( requirement, false, editable, index.cloned(), rev.map(ToString::to_string), tag.map(ToString::to_string), branch.map(ToString::to_string), lfs, script_dir, existing_sources, )? } AddTarget::Project(project, _) => { let existing_sources = project .pyproject_toml() .tool .as_ref() .and_then(|tool| tool.uv.as_ref()) .and_then(|uv| uv.sources.as_ref()) .map(ToolUvSources::inner); let is_workspace_member = project .workspace() .packages() .contains_key(&requirement.name); resolve_requirement( requirement, is_workspace_member, editable, index.cloned(), rev.map(ToString::to_string), tag.map(ToString::to_string), branch.map(ToString::to_string), lfs, project.root(), existing_sources, )? } }; // Remove any credentials. By default, we avoid writing sensitive credentials to files that // will be checked into version control (e.g., `pyproject.toml` and `uv.lock`). Instead, // we store the credentials in a global store, and reuse them during resolution. The // expectation is that subsequent resolutions steps will succeed by reading from (e.g.) the
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/src/commands/project/remove.rs
crates/uv/src/commands/project/remove.rs
use std::fmt::Write; use std::io; use std::path::Path; use std::str::FromStr; use anyhow::{Context, Result}; use owo_colors::OwoColorize; use tracing::{debug, warn}; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::{ Concurrency, DependencyGroups, DryRun, ExtrasSpecification, InstallOptions, }; use uv_fs::Simplified; use uv_normalize::PackageName; use uv_normalize::{DEV_DEPENDENCIES, DefaultExtras, DefaultGroups}; use uv_preview::Preview; use uv_python::{PythonDownloads, PythonPreference, PythonRequest}; use uv_scripts::{Pep723Metadata, Pep723Script}; use uv_settings::PythonInstallMirrors; use uv_warnings::warn_user_once; use uv_workspace::pyproject::DependencyType; use uv_workspace::pyproject_mut::{DependencyTarget, PyProjectTomlMut}; use uv_workspace::{DiscoveryOptions, VirtualProject, Workspace, WorkspaceCache}; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger}; use crate::commands::pip::operations::Modifications; use crate::commands::project::add::{AddTarget, PythonTarget}; use crate::commands::project::install_target::InstallTarget; use crate::commands::project::lock::LockMode; use crate::commands::project::lock_target::LockTarget; use crate::commands::project::{ ProjectEnvironment, ProjectError, ProjectInterpreter, ScriptInterpreter, UniversalState, default_dependency_groups, }; use crate::commands::{ExitStatus, diagnostics, project}; use crate::printer::Printer; use crate::settings::{LockCheck, ResolverInstallerSettings}; /// Remove one or more packages from the project requirements. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn remove( project_dir: &Path, lock_check: LockCheck, frozen: bool, active: Option<bool>, no_sync: bool, packages: Vec<PackageName>, dependency_type: DependencyType, package: Option<PackageName>, python: Option<String>, install_mirrors: PythonInstallMirrors, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, script: Option<Pep723Script>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, no_config: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let target = if let Some(script) = script { // If we found a PEP 723 script and the user provided a project-only setting, warn. if package.is_some() { warn_user_once!( "`--package` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if let LockCheck::Enabled(lock_check) = lock_check { warn_user_once!( "`{lock_check}` is a no-op for Python scripts with inline metadata, which always run in isolation", ); } if frozen { warn_user_once!( "`--frozen` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } if no_sync { warn_user_once!( "`--no-sync` is a no-op for Python scripts with inline metadata, which always run in isolation" ); } RemoveTarget::Script(script) } else { // Find the project in the workspace. // No workspace caching since `uv remove` changes the workspace definition. let project = if let Some(package) = package { VirtualProject::Project( Workspace::discover( project_dir, &DiscoveryOptions::default(), &WorkspaceCache::default(), ) .await? .with_current_project(package.clone()) .with_context(|| format!("Package `{package}` not found in workspace"))?, ) } else { VirtualProject::discover( project_dir, &DiscoveryOptions::default(), &WorkspaceCache::default(), ) .await? }; RemoveTarget::Project(project) }; let mut toml = match &target { RemoveTarget::Script(script) => { PyProjectTomlMut::from_toml(&script.metadata.raw, DependencyTarget::Script) } RemoveTarget::Project(project) => PyProjectTomlMut::from_toml( project.pyproject_toml().raw.as_ref(), DependencyTarget::PyProjectToml, ), }?; for package in packages { match dependency_type { DependencyType::Production => { let deps = toml.remove_dependency(&package)?; if deps.is_empty() { show_other_dependency_type_hint(printer, &package, &toml)?; anyhow::bail!( "The dependency `{package}` could not be found in `project.dependencies`" ) } } DependencyType::Dev => { let dev_deps = toml.remove_dev_dependency(&package)?; let group_deps = toml.remove_dependency_group_requirement(&package, &DEV_DEPENDENCIES)?; if dev_deps.is_empty() && group_deps.is_empty() { show_other_dependency_type_hint(printer, &package, &toml)?; anyhow::bail!( "The dependency `{package}` could not be found in `tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`" ); } } DependencyType::Optional(ref extra) => { let deps = toml.remove_optional_dependency(&package, extra)?; if deps.is_empty() { show_other_dependency_type_hint(printer, &package, &toml)?; anyhow::bail!( "The dependency `{package}` could not be found in `project.optional-dependencies.{extra}`" ); } } DependencyType::Group(ref group) => { if group == &*DEV_DEPENDENCIES { let dev_deps = toml.remove_dev_dependency(&package)?; let group_deps = toml.remove_dependency_group_requirement(&package, &DEV_DEPENDENCIES)?; if dev_deps.is_empty() && group_deps.is_empty() { show_other_dependency_type_hint(printer, &package, &toml)?; anyhow::bail!( "The dependency `{package}` could not be found in `tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`" ); } } else { let deps = toml.remove_dependency_group_requirement(&package, group)?; if deps.is_empty() { show_other_dependency_type_hint(printer, &package, &toml)?; anyhow::bail!( "The dependency `{package}` could not be found in `dependency-groups.{group}`" ); } } } } } let content = toml.to_string(); // Save the modified `pyproject.toml` or script. target.write(&content)?; // If `--frozen`, exit early. There's no reason to lock and sync, since we don't need a `uv.lock` // to exist at all. if frozen { return Ok(ExitStatus::Success); } // If we're modifying a script, and lockfile doesn't exist, don't create it. if let RemoveTarget::Script(ref script) = target { if !LockTarget::from(script).lock_path().is_file() { writeln!( printer.stderr(), "Updated `{}`", script.path.user_display().cyan() )?; return Ok(ExitStatus::Success); } } // Update the `pypackage.toml` in-memory. let target = target.update(&content)?; // Determine enabled groups and extras let default_groups = match &target { RemoveTarget::Project(project) => default_dependency_groups(project.pyproject_toml())?, RemoveTarget::Script(_) => DefaultGroups::default(), }; let groups = DependencyGroups::default().with_defaults(default_groups); let extras = ExtrasSpecification::default().with_defaults(DefaultExtras::default()); // Convert to an `AddTarget` by attaching the appropriate interpreter or environment. let target = match target { RemoveTarget::Project(project) => { if no_sync { // Discover the interpreter. let interpreter = ProjectInterpreter::discover( project.workspace(), project_dir, &groups, python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, false, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); AddTarget::Project(project, Box::new(PythonTarget::Interpreter(interpreter))) } else { // Discover or create the virtual environment. let environment = ProjectEnvironment::get_or_init( project.workspace(), &groups, python.as_deref().map(PythonRequest::parse), &install_mirrors, &client_builder, python_preference, python_downloads, no_sync, no_config, active, cache, DryRun::Disabled, printer, preview, ) .await? .into_environment()?; AddTarget::Project(project, Box::new(PythonTarget::Environment(environment))) } } RemoveTarget::Script(script) => { let interpreter = ScriptInterpreter::discover( (&script).into(), python.as_deref().map(PythonRequest::parse), &client_builder, python_preference, python_downloads, &install_mirrors, no_sync, no_config, active, cache, printer, preview, ) .await? .into_interpreter(); AddTarget::Script(script, Box::new(interpreter)) } }; let _lock = target .acquire_lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); // Determine the lock mode. let mode = if let LockCheck::Enabled(lock_check) = lock_check { LockMode::Locked(target.interpreter(), lock_check) } else { LockMode::Write(target.interpreter()) }; // Initialize any shared state. let state = UniversalState::default(); // Lock and sync the environment, if necessary. let lock = match Box::pin( project::lock::LockOperation::new( mode, &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, cache, &WorkspaceCache::default(), printer, preview, ) .execute((&target).into()), ) .await { Ok(result) => result.into_lock(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; let AddTarget::Project(project, environment) = target else { // If we're not adding to a project, exit early. return Ok(ExitStatus::Success); }; let PythonTarget::Environment(venv) = &*environment else { // If we're not syncing, exit early. return Ok(ExitStatus::Success); }; // Identify the installation target. let target = match &project { VirtualProject::Project(project) => InstallTarget::Project { workspace: project.workspace(), name: project.project_name(), lock: &lock, }, VirtualProject::NonProject(workspace) => InstallTarget::NonProjectWorkspace { workspace, lock: &lock, }, }; let state = state.fork(); match project::sync::do_sync( target, venv, &extras, &groups, None, InstallOptions::default(), Modifications::Exact, None, (&settings).into(), &client_builder, &state, Box::new(DefaultInstallLogger), installer_metadata, concurrency, cache, WorkspaceCache::default(), DryRun::Disabled, printer, preview, ) .await { Ok(_) => {} Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } Ok(ExitStatus::Success) } /// Represents the destination where dependencies are added, either to a project or a script. #[derive(Debug)] #[allow(clippy::large_enum_variant)] enum RemoveTarget { /// A PEP 723 script, with inline metadata. Project(VirtualProject), /// A project with a `pyproject.toml`. Script(Pep723Script), } impl RemoveTarget { /// Write the updated content to the target. /// /// Returns `true` if the content was modified. fn write(&self, content: &str) -> Result<bool, io::Error> { match self { Self::Script(script) => { if content == script.metadata.raw { debug!("No changes to dependencies; skipping update"); Ok(false) } else { script.write(content)?; Ok(true) } } Self::Project(project) => { if content == project.pyproject_toml().raw { debug!("No changes to dependencies; skipping update"); Ok(false) } else { let pyproject_path = project.root().join("pyproject.toml"); fs_err::write(pyproject_path, content)?; Ok(true) } } } } /// Update the target in-memory to incorporate the new content. #[allow(clippy::result_large_err)] fn update(self, content: &str) -> Result<Self, ProjectError> { match self { Self::Script(mut script) => { script.metadata = Pep723Metadata::from_str(content) .map_err(ProjectError::Pep723ScriptTomlParse)?; Ok(Self::Script(script)) } Self::Project(project) => { let project = project .with_pyproject_toml( toml::from_str(content).map_err(ProjectError::PyprojectTomlParse)?, )? .ok_or(ProjectError::PyprojectTomlUpdate)?; Ok(Self::Project(project)) } } } } /// Show a hint if a dependency with the given name is present as any dependency type. /// /// This is useful when a dependency of the user-specified type was not found, but it may be present /// elsewhere. fn show_other_dependency_type_hint( printer: Printer, name: &PackageName, pyproject: &PyProjectTomlMut, ) -> Result<()> { // TODO(zanieb): Attach these hints to the error so they render _after_ in accordance our // typical styling for dep_ty in pyproject.find_dependency(name, None) { match dep_ty { DependencyType::Production => writeln!( printer.stderr(), "{}{} `{name}` is a production dependency", "hint".bold().cyan(), ":".bold(), )?, DependencyType::Dev => writeln!( printer.stderr(), "{}{} `{name}` is a development dependency (try: `{}`)", "hint".bold().cyan(), ":".bold(), format!("uv remove {name} --dev`").bold() )?, DependencyType::Optional(group) => writeln!( printer.stderr(), "{}{} `{name}` is an optional dependency (try: `{}`)", "hint".bold().cyan(), ":".bold(), format!("uv remove {name} --optional {group}").bold() )?, DependencyType::Group(group) => writeln!( printer.stderr(), "{}{} `{name}` is in the `{group}` group (try: `{}`)", "hint".bold().cyan(), ":".bold(), format!("uv remove {name} --group {group}").bold() )?, } } 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/src/commands/pip/uninstall.rs
crates/uv/src/commands/pip/uninstall.rs
use std::fmt::Write; use anyhow::Result; use itertools::{Either, Itertools}; use owo_colors::OwoColorize; use tracing::{debug, warn}; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::{DryRun, KeyringProviderType}; use uv_distribution_types::Requirement; use uv_distribution_types::{InstalledMetadata, Name, UnresolvedRequirement}; use uv_fs::Simplified; use uv_pep508::UnnamedRequirement; use uv_preview::Preview; use uv_pypi_types::VerbatimParsedUrl; use uv_python::PythonRequest; use uv_python::{EnvironmentPreference, PythonPreference}; use uv_python::{Prefix, PythonEnvironment, Target}; use uv_requirements::{RequirementsSource, RequirementsSpecification}; use crate::commands::pip::operations::report_target_environment; use crate::commands::{ExitStatus, elapsed}; use crate::printer::Printer; /// Uninstall packages from the current environment. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_uninstall( sources: &[RequirementsSource], python: Option<String>, system: bool, break_system_packages: bool, target: Option<Target>, prefix: Option<Prefix>, cache: Cache, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, dry_run: DryRun, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let start = std::time::Instant::now(); let client_builder = client_builder.clone().keyring(keyring_provider); // Read all requirements from the provided sources. let spec = RequirementsSpecification::from_simple_sources(sources, &client_builder).await?; // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python .as_deref() .map(PythonRequest::parse) .unwrap_or_default(), EnvironmentPreference::from_system_flag(system, true), PythonPreference::default().with_system_flag(system), &cache, preview, )?; report_target_environment(&environment, &cache, printer)?; // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; // If the environment is externally managed, abort. if let Some(externally_managed) = environment.interpreter().is_externally_managed() { if break_system_packages { debug!("Ignoring externally managed environment due to `--break-system-packages`"); } else { return if let Some(error) = externally_managed.into_error() { Err(anyhow::anyhow!( "The interpreter at {} is externally managed, and indicates the following:\n\n{}\n\nConsider creating a virtual environment with `uv venv`.", environment.root().user_display().cyan(), textwrap::indent(&error, " ").green(), )) } else { Err(anyhow::anyhow!( "The interpreter at {} is externally managed. Instead, create a virtual environment with `uv venv`.", environment.root().user_display().cyan() )) }; } } let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); // Index the current `site-packages` directory. let site_packages = uv_installer::SitePackages::from_environment(&environment)?; // Partition the requirements into named and unnamed requirements. let (named, unnamed): (Vec<Requirement>, Vec<UnnamedRequirement<VerbatimParsedUrl>>) = spec .requirements .into_iter() .partition_map(|entry| match entry.requirement { UnresolvedRequirement::Named(requirement) => Either::Left(requirement), UnresolvedRequirement::Unnamed(requirement) => Either::Right(requirement), }); // Sort and deduplicate the packages, which are keyed by name. Like `pip`, we ignore the // dependency specifier (even if it's a URL). let names = { let mut packages = named .into_iter() .map(|requirement| requirement.name) .collect::<Vec<_>>(); packages.sort_unstable(); packages.dedup(); packages }; // Sort and deduplicate the unnamed requirements, which are keyed by URL rather than package name. let urls = { let mut urls = unnamed .into_iter() .map(|requirement| requirement.url.verbatim.to_url()) .collect::<Vec<_>>(); urls.sort_unstable(); urls.dedup(); urls }; // Map to the local distributions. let distributions = { let mut distributions = Vec::with_capacity(names.len() + urls.len()); // Identify all packages that are installed. for package in &names { let installed = site_packages.get_packages(package); if installed.is_empty() { if !dry_run.enabled() { writeln!( printer.stderr(), "{}{} Skipping {} as it is not installed", "warning".yellow().bold(), ":".bold(), package.as_ref().bold() )?; } } else { distributions.extend(installed); } } // Identify all unnamed distributions that are installed. for url in &urls { let installed = site_packages.get_urls(url); if installed.is_empty() { if !dry_run.enabled() { writeln!( printer.stderr(), "{}{} Skipping {} as it is not installed", "warning".yellow().bold(), ":".bold(), url.as_ref().bold() )?; } } else { distributions.extend(installed); } } // Deduplicate, since a package could be listed both by name and editable URL. distributions.sort_unstable_by_key(|dist| dist.install_path()); distributions.dedup_by_key(|dist| dist.install_path()); distributions }; if distributions.is_empty() { if dry_run.enabled() { writeln!(printer.stderr(), "Would make no changes")?; } else { writeln!( printer.stderr(), "{}{} No packages to uninstall", "warning".yellow().bold(), ":".bold(), )?; } return Ok(ExitStatus::Success); } // Uninstall each package. if !dry_run.enabled() { for distribution in &distributions { let summary = uv_installer::uninstall(distribution).await?; debug!( "Uninstalled {} ({} file{}, {} director{})", distribution.name(), summary.file_count, if summary.file_count == 1 { "" } else { "s" }, summary.dir_count, if summary.dir_count == 1 { "y" } else { "ies" }, ); } } let uninstalls = distributions.len(); let s = if uninstalls == 1 { "" } else { "s" }; if dry_run.enabled() { writeln!( printer.stderr(), "{}", format!( "Would uninstall {}", format!("{uninstalls} package{s}").bold(), ) .dimmed() )?; } else { writeln!( printer.stderr(), "{}", format!( "Uninstalled {} {}", format!("{uninstalls} package{s}").bold(), format!("in {}", elapsed(start.elapsed())).dimmed(), ) .dimmed() )?; } for distribution in distributions { writeln!( printer.stderr(), " {} {}{}", "-".red(), distribution.name().as_ref().bold(), distribution.installed_version().to_string().dimmed() )?; } Ok(ExitStatus::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/src/commands/pip/compile.rs
crates/uv/src/commands/pip/compile.rs
use std::collections::BTreeSet; use std::env; use std::ffi::OsStr; use std::io::Write; use std::path::Path; use std::str::FromStr; use anyhow::{Result, anyhow}; use itertools::Itertools; use owo_colors::OwoColorize; use rustc_hash::FxHashSet; use tracing::debug; use uv_python::downloads::ManagedPythonDownloadList; use uv_cache::Cache; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ BuildIsolation, BuildOptions, Concurrency, Constraints, ExtrasSpecification, IndexStrategy, NoBinary, NoBuild, PipCompileFormat, Reinstall, SourceStrategy, Upgrade, }; use uv_configuration::{KeyringProviderType, TargetTriple}; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildVariables, HashGeneration, Index, IndexLocations, NameRequirementSpecification, Origin, PackageConfigSettings, Requirement, RequiresPython, UnresolvedRequirementSpecification, Verbatim, }; use uv_fs::{CWD, Simplified}; use uv_git::ResolvedRepositoryReference; use uv_install_wheel::LinkMode; use uv_normalize::PackageName; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::{Conflicts, SupportedEnvironments}; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVersion, VersionRequest, }; use uv_requirements::upgrade::{LockedRequirements, read_pylock_toml_requirements}; use uv_requirements::{ GroupsSpecification, RequirementsSource, RequirementsSpecification, is_pylock_toml, upgrade::read_requirements_txt, }; use uv_resolver::{ AnnotationStyle, DependencyMode, DisplayResolutionGraph, ExcludeNewer, FlatIndex, ForkStrategy, InMemoryIndex, OptionsBuilder, PrereleaseMode, PylockToml, PythonRequirement, ResolutionMode, ResolverEnvironment, }; use uv_settings::PythonInstallMirrors; use uv_static::EnvVars; use uv_torch::{TorchMode, TorchSource, TorchStrategy}; use uv_types::{EmptyInstalledPackages, HashStrategy}; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::WorkspaceCache; use uv_workspace::pyproject::ExtraBuildDependencies; use crate::commands::pip::loggers::DefaultResolveLogger; use crate::commands::pip::{operations, resolution_markers, resolution_tags}; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::{ExitStatus, OutputWriter, diagnostics}; use crate::printer::Printer; /// Resolve a set of requirements into a set of pinned versions. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_compile( requirements: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], excludes: &[RequirementsSource], build_constraints: &[RequirementsSource], constraints_from_workspace: Vec<Requirement>, overrides_from_workspace: Vec<Requirement>, excludes_from_workspace: Vec<uv_normalize::PackageName>, build_constraints_from_workspace: Vec<Requirement>, environments: SupportedEnvironments, extras: ExtrasSpecification, groups: GroupsSpecification, output_file: Option<&Path>, format: Option<PipCompileFormat>, resolution_mode: ResolutionMode, prerelease_mode: PrereleaseMode, fork_strategy: ForkStrategy, dependency_mode: DependencyMode, upgrade: Upgrade, generate_hashes: bool, no_emit_packages: Vec<PackageName>, include_extras: bool, include_markers: bool, include_annotations: bool, include_header: bool, custom_compile_command: Option<String>, include_index_url: bool, include_find_links: bool, include_build_options: bool, include_marker_expression: bool, include_index_annotation: bool, index_locations: IndexLocations, index_strategy: IndexStrategy, torch_backend: Option<TorchMode>, dependency_metadata: DependencyMetadata, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, config_settings: ConfigSettings, config_settings_package: PackageConfigSettings, build_isolation: BuildIsolation, extra_build_dependencies: &ExtraBuildDependencies, extra_build_variables: &ExtraBuildVariables, build_options: BuildOptions, install_mirrors: PythonInstallMirrors, mut python_version: Option<PythonVersion>, python_platform: Option<TargetTriple>, python_downloads: PythonDownloads, universal: bool, exclude_newer: ExcludeNewer, sources: SourceStrategy, annotation_style: AnnotationStyle, link_mode: LinkMode, mut python: Option<String>, system: bool, python_preference: PythonPreference, concurrency: Concurrency, quiet: bool, cache: Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } // If the user provides a `pyproject.toml` or other TOML file as the output file, raise an // error. if output_file .and_then(Path::file_name) .is_some_and(|name| name.eq_ignore_ascii_case("pyproject.toml")) { return Err(anyhow!( "`pyproject.toml` is not a supported output format for `{}` (only `requirements.txt`-style output is supported)", "uv pip compile".green() )); } // Determine the output format. let format = format.unwrap_or_else(|| { let extension = output_file.and_then(Path::extension); if extension.is_some_and(|ext| ext.eq_ignore_ascii_case("txt")) { PipCompileFormat::RequirementsTxt } else if extension.is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) { PipCompileFormat::PylockToml } else { PipCompileFormat::RequirementsTxt } }); // If the user is exporting to PEP 751, ensure the filename matches the specification. if matches!(format, PipCompileFormat::PylockToml) { if let Some(file_name) = output_file .and_then(Path::file_name) .and_then(OsStr::to_str) { if !is_pylock_toml(file_name) { return Err(anyhow!( "Expected the output filename to start with `pylock.` and end with `.toml` (e.g., `pylock.toml`, `pylock.dev.toml`); `{file_name}` won't be recognized as a `pylock.toml` file in subsequent commands", )); } } } // Respect `UV_PYTHON` if python.is_none() && python_version.is_none() { if let Ok(request) = std::env::var(EnvVars::UV_PYTHON) { if !request.is_empty() { python = Some(request); } } } // If `--python` / `-p` is a simple Python version request, we treat it as `--python-version` // for backwards compatibility. `-p` was previously aliased to `--python-version` but changed to // `--python` for consistency with the rest of the CLI in v0.6.0. Since we assume metadata is // consistent across wheels, it's okay for us to build wheels (to determine metadata) with an // alternative Python interpreter as long as we solve with the proper Python version tags. if python_version.is_none() { if let Some(request) = python.as_ref() { if let Ok(version) = PythonVersion::from_str(request) { python_version = Some(version); python = None; } } } // If the user requests `extras` but does not provide a valid source (e.g., a `pyproject.toml`), // return an error. if !extras.is_empty() && !requirements.iter().any(RequirementsSource::allows_extras) { return Err(anyhow!( "Requesting extras requires a `pyproject.toml`, `setup.cfg`, or `setup.py` file." )); } let client_builder = client_builder.clone().keyring(keyring_provider); // Read all requirements from the provided sources. let RequirementsSpecification { project, requirements, constraints, overrides, excludes, pylock, source_trees, groups, extras: used_extras, index_url, extra_index_urls, no_index, find_links, no_binary, no_build, } = RequirementsSpecification::from_sources( requirements, constraints, overrides, excludes, Some(&groups), &client_builder, ) .await?; // Reject `pylock.toml` files, which are valid outputs but not inputs. if pylock.is_some() { return Err(anyhow!( "`pylock.toml` is not a supported input format for `uv pip compile`" )); } let constraints = constraints .iter() .cloned() .chain( constraints_from_workspace .into_iter() .map(NameRequirementSpecification::from), ) .collect(); let overrides: Vec<UnresolvedRequirementSpecification> = overrides .iter() .cloned() .chain( overrides_from_workspace .into_iter() .map(UnresolvedRequirementSpecification::from), ) .collect(); let excludes: Vec<PackageName> = excludes .into_iter() .chain(excludes_from_workspace) .collect(); // Read build constraints. let build_constraints: Vec<NameRequirementSpecification> = operations::read_constraints(build_constraints, &client_builder) .await? .into_iter() .chain( build_constraints_from_workspace .into_iter() .map(NameRequirementSpecification::from), ) .collect(); // If all the metadata could be statically resolved, validate that every extra was used. If we // need to resolve metadata via PEP 517, we don't know which extras are used until much later. if source_trees.is_empty() { let mut unused_extras = extras .explicit_names() .filter(|extra| !used_extras.contains(extra)) .collect::<Vec<_>>(); if !unused_extras.is_empty() { unused_extras.sort_unstable(); unused_extras.dedup(); let s = if unused_extras.len() == 1 { "" } else { "s" }; return Err(anyhow!( "Requested extra{s} not found: {}", unused_extras.iter().join(", ") )); } } // Find an interpreter to use for building distributions let environment_preference = EnvironmentPreference::from_system_flag(system, false); let python_preference = python_preference.with_system_flag(system); let client = client_builder.clone().retries(0).build(); let download_list = ManagedPythonDownloadList::new( &client, install_mirrors.python_downloads_json_url.as_deref(), ) .await?; let interpreter = if let Some(python) = python.as_ref() { let request = PythonRequest::parse(python); let reporter = PythonDownloadReporter::single(printer); PythonInstallation::find_or_download( Some(&request), environment_preference, python_preference, python_downloads, &client_builder, &cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await } else { // TODO(zanieb): The split here hints at a problem with the request abstraction; we should // be able to use `PythonInstallation::find(...)` here. let request = if let Some(version) = python_version.as_ref() { // TODO(zanieb): We should consolidate `VersionRequest` and `PythonVersion` PythonRequest::Version(VersionRequest::from(version)) } else { PythonRequest::default() }; PythonInstallation::find_best( &request, environment_preference, python_preference, &download_list, &cache, preview, ) }? .into_interpreter(); debug!( "Using Python {} interpreter at {} for builds", interpreter.python_version(), interpreter.sys_executable().user_display().cyan() ); if let Some(python_version) = python_version.as_ref() { // If the requested version does not match the version we're using warn the user // _unless_ they have not specified a patch version and that is the only difference // _or_ if builds are disabled let matches_without_patch = { python_version.major() == interpreter.python_major() && python_version.minor() == interpreter.python_minor() }; if no_build.is_none() && python.is_none() && python_version.version() != interpreter.python_version() && (python_version.patch().is_some() || !matches_without_patch) { warn_user!( "The requested Python version {} is not available; {} will be used to build dependencies instead.", python_version.version(), interpreter.python_version(), ); } } // Create the shared state. let state = SharedState::default(); // If we're resolving against a different Python version, use a separate index. Source // distributions will be built against the installed version, and so the index may contain // different package priorities than in the top-level resolution. let top_level_index = if python_version.is_some() { InMemoryIndex::default() } else { state.index().clone() }; // Determine the Python requirement, if the user requested a specific version. let python_requirement = if universal { let requires_python = if let Some(python_version) = python_version.as_ref() { RequiresPython::greater_than_equal_version(&python_version.version) } else { let version = interpreter.python_minor_version(); RequiresPython::greater_than_equal_version(&version) }; PythonRequirement::from_requires_python(&interpreter, requires_python) } else if let Some(python_version) = python_version.as_ref() { PythonRequirement::from_python_version(&interpreter, python_version) } else { PythonRequirement::from_interpreter(&interpreter) }; // Determine the environment for the resolution. let (tags, resolver_env) = if universal { ( None, ResolverEnvironment::universal(environments.into_markers()), ) } else { let tags = resolution_tags( python_version.as_ref(), python_platform.as_ref(), &interpreter, )?; let marker_env = resolution_markers( python_version.as_ref(), python_platform.as_ref(), &interpreter, ); (Some(tags), ResolverEnvironment::specific(marker_env)) }; // Generate, but don't enforce hashes for the requirements. PEP 751 _requires_ a hash to be // present, but otherwise, we omit them by default. let hasher = if generate_hashes || matches!(format, PipCompileFormat::PylockToml) { HashStrategy::Generate(HashGeneration::All) } else { HashStrategy::None }; // Incorporate any index locations from the provided sources. let index_locations = index_locations.combine( extra_index_urls .into_iter() .map(Index::from_extra_index_url) .chain(index_url.map(Index::from_index_url)) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), find_links .into_iter() .map(Index::from_find_links) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), no_index, ); // Determine the PyTorch backend. let torch_backend = torch_backend .map(|mode| { let source = if uv_auth::PyxTokenStore::from_settings() .is_ok_and(|store| store.has_credentials()) { TorchSource::Pyx } else { TorchSource::default() }; TorchStrategy::from_mode( mode, source, python_platform .map(TargetTriple::platform) .as_ref() .unwrap_or(interpreter.platform()) .os(), ) }) .transpose()?; // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend.clone()) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Read the lockfile, if present. let LockedRequirements { preferences, git } = if let Some(output_file) = output_file.filter(|output_file| output_file.exists()) { match format { PipCompileFormat::RequirementsTxt => LockedRequirements::from_preferences( read_requirements_txt(output_file, &upgrade).await?, ), PipCompileFormat::PylockToml => { read_pylock_toml_requirements(output_file, &upgrade).await? } } } else { LockedRequirements::default() }; // Populate the Git resolver. for ResolvedRepositoryReference { reference, sha } in git { debug!("Inserting Git reference into resolver: `{reference:?}` at `{sha}`"); state.git().insert(reference, sha); } // Combine the `--no-binary` and `--no-build` flags from the requirements files. let build_options = build_options.combine(no_binary, no_build); // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), &cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, tags.as_deref(), &hasher, &build_options) }; // Determine whether to enable build isolation. let environment; let types_build_isolation = match build_isolation { BuildIsolation::Isolate => uv_types::BuildIsolation::Isolated, BuildIsolation::Shared => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); uv_types::BuildIsolation::Shared(&environment) } BuildIsolation::SharedPackage(ref packages) => { environment = PythonEnvironment::from_interpreter(interpreter.clone()); uv_types::BuildIsolation::SharedPackage(&environment, packages) } }; // Don't enforce hashes in `pip compile`. let build_hashes = HashStrategy::None; let build_constraints = Constraints::from_requirements( build_constraints .iter() .map(|constraint| constraint.requirement.clone()), ); // Lower the extra build dependencies, if any. let extra_build_requires = LoweredExtraBuildDependencies::from_non_lowered(extra_build_dependencies.clone()) .into_inner(); // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, &cache, &build_constraints, &interpreter, &index_locations, &flat_index, &dependency_metadata, state, index_strategy, &config_settings, &config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, &build_options, &build_hashes, exclude_newer.clone(), sources, WorkspaceCache::default(), concurrency, preview, ); let options = OptionsBuilder::new() .resolution_mode(resolution_mode) .prerelease_mode(prerelease_mode) .fork_strategy(fork_strategy) .dependency_mode(dependency_mode) .exclude_newer(exclude_newer.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend) .build_options(build_options.clone()) .build(); // Resolve the requirements. let resolution = match operations::resolve( requirements, constraints, overrides, excludes, source_trees, project, BTreeSet::default(), &extras, &groups, preferences, EmptyInstalledPackages, &hasher, &Reinstall::None, &upgrade, tags.as_deref(), resolver_env.clone(), python_requirement, interpreter.markers(), Conflicts::empty(), &client, &flat_index, &top_level_index, &build_dispatch, concurrency, options, Box::new(DefaultResolveLogger), printer, ) .await { Ok(resolution) => resolution, Err(err) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } }; // Write the resolved dependencies to the output channel. let mut writer = OutputWriter::new(!quiet || output_file.is_none(), output_file); if include_header { writeln!( writer, "{}", "# This file was autogenerated by uv via the following command:".green() )?; writeln!( writer, "{}", format!( "# {}", cmd( include_index_url, include_find_links, custom_compile_command ) ) .green() )?; } match format { PipCompileFormat::RequirementsTxt => { if include_marker_expression { if let Some(marker_env) = resolver_env.marker_environment() { let relevant_markers = resolution.marker_tree(&top_level_index, marker_env)?; if let Some(relevant_markers) = relevant_markers.contents() { writeln!( writer, "{}", "# Pinned dependencies known to be valid for:".green() )?; writeln!(writer, "{}", format!("# {relevant_markers}").green())?; } } } let mut wrote_preamble = false; // If necessary, include the `--index-url` and `--extra-index-url` locations. if include_index_url { if let Some(index) = index_locations.default_index() { writeln!(writer, "--index-url {}", index.url().verbatim())?; wrote_preamble = true; } let mut seen = FxHashSet::default(); for extra_index in index_locations.implicit_indexes() { if seen.insert(extra_index.url()) { writeln!(writer, "--extra-index-url {}", extra_index.url().verbatim())?; wrote_preamble = true; } } } // If necessary, include the `--find-links` locations. if include_find_links { for flat_index in index_locations.flat_indexes() { writeln!(writer, "--find-links {}", flat_index.url().verbatim())?; wrote_preamble = true; } } // If necessary, include the `--no-binary` and `--only-binary` options. if include_build_options { match build_options.no_binary() { NoBinary::None => {} NoBinary::All => { writeln!(writer, "--no-binary :all:")?; wrote_preamble = true; } NoBinary::Packages(packages) => { for package in packages { writeln!(writer, "--no-binary {package}")?; wrote_preamble = true; } } } match build_options.no_build() { NoBuild::None => {} NoBuild::All => { writeln!(writer, "--only-binary :all:")?; wrote_preamble = true; } NoBuild::Packages(packages) => { for package in packages { writeln!(writer, "--only-binary {package}")?; wrote_preamble = true; } } } } // If we wrote an index, add a newline to separate it from the requirements if wrote_preamble { writeln!(writer)?; } write!( writer, "{}", DisplayResolutionGraph::new( &resolution, &resolver_env, &no_emit_packages, generate_hashes, include_extras, include_markers || universal, include_annotations, include_index_annotation, annotation_style, ) )?; } PipCompileFormat::PylockToml => { if include_marker_expression { warn_user!( "The `--emit-marker-expression` option is not supported for `pylock.toml` output" ); } if include_index_url { warn_user!( "The `--emit-index-url` option is not supported for `pylock.toml` output" ); } if include_find_links { warn_user!( "The `--emit-find-links` option is not supported for `pylock.toml` output" ); } if include_build_options { warn_user!( "The `--emit-build-options` option is not supported for `pylock.toml` output" ); } if include_index_annotation { warn_user!( "The `--emit-index-annotation` option is not supported for `pylock.toml` output" ); } // Determine the directory relative to which the output file should be written. let output_file = output_file.map(std::path::absolute).transpose()?; let install_path = if let Some(output_file) = output_file.as_deref() { output_file.parent().unwrap() } else { &*CWD }; // Convert the resolution to a `pylock.toml` file. let export = PylockToml::from_resolution( &resolution, &no_emit_packages, install_path, tags.as_deref(), &build_options, )?; write!(writer, "{}", export.to_toml()?)?; } } // If any "unsafe" packages were excluded, notify the user. let excluded = no_emit_packages .into_iter() .filter(|name| resolution.contains(name)) .collect::<Vec<_>>(); if !excluded.is_empty() { writeln!(writer)?; writeln!( writer, "{}", "# The following packages were excluded from the output:".green() )?; for package in excluded { writeln!(writer, "# {package}")?; } } // Commit the output to disk. writer.commit().await?; // Notify the user of any resolution diagnostics. operations::diagnose_resolution(resolution.diagnostics(), printer)?; Ok(ExitStatus::Success) } /// Format the uv command used to generate the output file. #[allow(clippy::fn_params_excessive_bools)] fn cmd( include_index_url: bool, include_find_links: bool, custom_compile_command: Option<String>, ) -> String { if let Some(cmd_str) = custom_compile_command { return cmd_str; } let args = env::args_os() .skip(1) .map(|arg| arg.to_string_lossy().to_string()) .scan(None, move |skip_next, arg| { if matches!(skip_next, Some(true)) { // Reset state; skip this iteration. *skip_next = None; return Some(None); } // Skip any index URLs, unless requested. if !include_index_url { if arg.starts_with("--extra-index-url=") || arg.starts_with("--index-url=") || arg.starts_with("-i=") || arg.starts_with("--index=") || arg.starts_with("--default-index=") { // Reset state; skip this iteration. *skip_next = None; return Some(None); } // Mark the next item as (to be) skipped. if arg == "--index-url" || arg == "--extra-index-url" || arg == "-i" || arg == "--index" || arg == "--default-index" { *skip_next = Some(true); return Some(None); } } // Skip any `--find-links` URLs, unless requested. if !include_find_links { // Always skip the `--find-links` and mark the next item to be skipped if arg == "--find-links" || arg == "-f" { *skip_next = Some(true); return Some(None); } // Skip only this argument if option and value are together if arg.starts_with("--find-links=") || arg.starts_with("-f") { // Reset state; skip this iteration. *skip_next = None; return Some(None); } } // Always skip the `--upgrade` flag. if arg == "--upgrade" || arg == "-U" { *skip_next = None; return Some(None); } // Always skip the `--upgrade-package` and mark the next item to be skipped if arg == "--upgrade-package" || arg == "-P" { *skip_next = Some(true); return Some(None); } // Skip only this argument if option and value are together if arg.starts_with("--upgrade-package=") || arg.starts_with("-P") { // Reset state; skip this iteration. *skip_next = None; return Some(None); } // Always skip the `--quiet` flag. if arg == "--quiet" || arg == "-q" { *skip_next = None; return Some(None); } // Always skip the `--verbose` flag. if arg == "--verbose" || arg == "-v" { *skip_next = None; return Some(None); } // Always skip the `--no-progress` flag. if arg == "--no-progress" { *skip_next = None; return Some(None); } // Always skip the `--native-tls` flag. if arg == "--native-tls" { *skip_next = None; return Some(None); } // Return the argument. Some(Some(arg)) }) .flatten() .join(" "); format!("uv {args}") }
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/src/commands/pip/sync.rs
crates/uv/src/commands/pip/sync.rs
use std::collections::BTreeSet; use std::fmt::Write; use anyhow::{Context, Result}; use owo_colors::OwoColorize; use tracing::{debug, warn}; use uv_cache::Cache; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ BuildIsolation, BuildOptions, Concurrency, Constraints, DryRun, ExtrasSpecification, HashCheckingMode, IndexStrategy, Reinstall, SourceStrategy, Upgrade, }; use uv_configuration::{KeyringProviderType, TargetTriple}; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildVariables, Index, IndexLocations, Origin, PackageConfigSettings, Resolution, }; use uv_fs::Simplified; use uv_install_wheel::LinkMode; use uv_installer::{InstallationStrategy, SitePackages}; use uv_normalize::{DefaultExtras, DefaultGroups}; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::Conflicts; use uv_python::{ EnvironmentPreference, Prefix, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVersion, Target, }; use uv_requirements::{GroupsSpecification, RequirementsSource, RequirementsSpecification}; use uv_resolver::{ DependencyMode, ExcludeNewer, FlatIndex, OptionsBuilder, PrereleaseMode, PylockToml, PythonRequirement, ResolutionMode, ResolverEnvironment, }; use uv_settings::PythonInstallMirrors; use uv_torch::{TorchMode, TorchSource, TorchStrategy}; use uv_types::HashStrategy; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::WorkspaceCache; use uv_workspace::pyproject::ExtraBuildDependencies; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger}; use crate::commands::pip::operations::Modifications; use crate::commands::pip::operations::{report_interpreter, report_target_environment}; use crate::commands::pip::{operations, resolution_markers, resolution_tags}; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::{ExitStatus, diagnostics}; use crate::printer::Printer; /// Install a set of locked requirements into the current Python environment. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_sync( requirements: &[RequirementsSource], constraints: &[RequirementsSource], build_constraints: &[RequirementsSource], extras: &ExtrasSpecification, groups: &GroupsSpecification, reinstall: Reinstall, link_mode: LinkMode, compile: bool, hash_checking: Option<HashCheckingMode>, index_locations: IndexLocations, index_strategy: IndexStrategy, torch_backend: Option<TorchMode>, dependency_metadata: DependencyMetadata, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, allow_empty_requirements: bool, installer_metadata: bool, config_settings: &ConfigSettings, config_settings_package: &PackageConfigSettings, build_isolation: BuildIsolation, extra_build_dependencies: &ExtraBuildDependencies, extra_build_variables: &ExtraBuildVariables, build_options: BuildOptions, python_version: Option<PythonVersion>, python_platform: Option<TargetTriple>, python_downloads: PythonDownloads, install_mirrors: PythonInstallMirrors, strict: bool, exclude_newer: ExcludeNewer, python: Option<String>, system: bool, break_system_packages: bool, target: Option<Target>, prefix: Option<Prefix>, sources: SourceStrategy, python_preference: PythonPreference, concurrency: Concurrency, cache: Cache, dry_run: DryRun, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } let client_builder = client_builder.clone().keyring(keyring_provider); // Initialize a few defaults. let overrides = &[]; let excludes = &[]; let upgrade = Upgrade::default(); let resolution_mode = ResolutionMode::default(); let prerelease_mode = PrereleaseMode::default(); let dependency_mode = DependencyMode::Direct; // Read all requirements from the provided sources. let RequirementsSpecification { project, requirements, constraints, overrides, excludes, pylock, source_trees, groups, index_url, extra_index_urls, no_index, find_links, no_binary, no_build, extras: _, } = operations::read_requirements( requirements, constraints, overrides, excludes, extras, Some(groups), &client_builder, ) .await?; if pylock.is_some() { if !preview.is_enabled(PreviewFeatures::PYLOCK) { warn_user!( "The `--pylock` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::PYLOCK ); } } // Read build constraints. let build_constraints = operations::read_constraints(build_constraints, &client_builder).await?; // Validate that the requirements are non-empty. if !allow_empty_requirements { let num_requirements = requirements.len() + source_trees.len() + usize::from(pylock.is_some()); if num_requirements == 0 { writeln!( printer.stderr(), "No requirements found (hint: use `--allow-empty-requirements` to clear the environment)" )?; return Ok(ExitStatus::Success); } } // Detect the current Python interpreter. let environment = if target.is_some() || prefix.is_some() { let python_request = python.as_deref().map(PythonRequest::parse); let reporter = PythonDownloadReporter::single(printer); let installation = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::from_system_flag(system, false), python_preference.with_system_flag(system), python_downloads, &client_builder, &cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await?; report_interpreter(&installation, true, printer)?; PythonEnvironment::from_installation(installation) } else { let environment = PythonEnvironment::find( &python .as_deref() .map(PythonRequest::parse) .unwrap_or_default(), EnvironmentPreference::from_system_flag(system, true), PythonPreference::default().with_system_flag(system), &cache, preview, )?; report_target_environment(&environment, &cache, printer)?; environment }; // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; // If the environment is externally managed, abort. if let Some(externally_managed) = environment.interpreter().is_externally_managed() { if break_system_packages { debug!("Ignoring externally managed environment due to `--break-system-packages`"); } else { return if let Some(error) = externally_managed.into_error() { Err(anyhow::anyhow!( "The interpreter at {} is externally managed, and indicates the following:\n\n{}\n\nConsider creating a virtual environment with `uv venv`.", environment.root().user_display().cyan(), textwrap::indent(&error, " ").green(), )) } else { Err(anyhow::anyhow!( "The interpreter at {} is externally managed. Instead, create a virtual environment with `uv venv`.", environment.root().user_display().cyan() )) }; } } let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); let interpreter = environment.interpreter(); // Determine the Python requirement, if the user requested a specific version. let python_requirement = if let Some(python_version) = python_version.as_ref() { PythonRequirement::from_python_version(interpreter, python_version) } else { PythonRequirement::from_interpreter(interpreter) }; // Determine the markers and tags to use for resolution. let marker_env = resolution_markers( python_version.as_ref(), python_platform.as_ref(), interpreter, ); let tags = resolution_tags( python_version.as_ref(), python_platform.as_ref(), interpreter, )?; // Collect the set of required hashes. let hasher = if let Some(hash_checking) = hash_checking { HashStrategy::from_requirements( requirements .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), constraints .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), Some(&marker_env), hash_checking, )? } else { HashStrategy::None }; // Incorporate any index locations from the provided sources. let index_locations = index_locations.combine( extra_index_urls .into_iter() .map(Index::from_extra_index_url) .chain(index_url.map(Index::from_index_url)) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), find_links .into_iter() .map(Index::from_find_links) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), no_index, ); // Determine the PyTorch backend. let torch_backend = torch_backend .map(|mode| { let source = if uv_auth::PyxTokenStore::from_settings() .is_ok_and(|store| store.has_credentials()) { TorchSource::Pyx } else { TorchSource::default() }; TorchStrategy::from_mode( mode, source, python_platform .map(TargetTriple::platform) .as_ref() .unwrap_or(interpreter.platform()) .os(), ) }) .transpose()?; // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend.clone()) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Combine the `--no-binary` and `--no-build` flags from the requirements files. let build_options = build_options.combine(no_binary, no_build); // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), &cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, Some(&tags), &hasher, &build_options) }; // Determine whether to enable build isolation. let types_build_isolation = match build_isolation { BuildIsolation::Isolate => uv_types::BuildIsolation::Isolated, BuildIsolation::Shared => uv_types::BuildIsolation::Shared(&environment), BuildIsolation::SharedPackage(ref packages) => { uv_types::BuildIsolation::SharedPackage(&environment, packages) } }; // Enforce (but never require) the build constraints, if `--require-hashes` or `--verify-hashes` // is provided. _Requiring_ hashes would be too strict, and would break with pip. let build_hasher = if hash_checking.is_some() { HashStrategy::from_requirements( std::iter::empty(), build_constraints .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), Some(&marker_env), HashCheckingMode::Verify, )? } else { HashStrategy::None }; let build_constraints = Constraints::from_requirements( build_constraints .iter() .map(|constraint| constraint.requirement.clone()), ); // Initialize any shared state. let state = SharedState::default(); // Lower the extra build dependencies, if any. let extra_build_requires = LoweredExtraBuildDependencies::from_non_lowered(extra_build_dependencies.clone()) .into_inner(); // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, &cache, &build_constraints, interpreter, &index_locations, &flat_index, &dependency_metadata, state.clone(), index_strategy, config_settings, config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, &build_options, &build_hasher, exclude_newer.clone(), sources, WorkspaceCache::default(), concurrency, preview, ); // Determine the set of installed packages. let site_packages = SitePackages::from_environment(&environment)?; let (resolution, hasher) = if let Some(pylock) = pylock { // Read the `pylock.toml` from disk, and deserialize it from TOML. let install_path = std::path::absolute(&pylock)?; let install_path = install_path.parent().unwrap(); let content = fs_err::tokio::read_to_string(&pylock).await?; let lock = toml::from_str::<PylockToml>(&content).with_context(|| { format!("Not a valid `pylock.toml` file: {}", pylock.user_display()) })?; // Verify that the Python version is compatible with the lock file. if let Some(requires_python) = lock.requires_python.as_ref() { if !requires_python.contains(interpreter.python_version()) { return Err(anyhow::anyhow!( "The requested interpreter resolved to Python {}, which is incompatible with the `pylock.toml`'s Python requirement: `{}`", interpreter.python_version(), requires_python, )); } } // Convert the extras and groups specifications into a concrete form. let extras = extras.with_defaults(DefaultExtras::default()); let extras = extras .extra_names(lock.extras.iter()) .cloned() .collect::<Vec<_>>(); let groups = groups .get(&pylock) .cloned() .unwrap_or_default() .with_defaults(DefaultGroups::List(lock.default_groups.clone())); let groups = groups .group_names(lock.dependency_groups.iter()) .cloned() .collect::<Vec<_>>(); let resolution = lock.to_resolution( install_path, marker_env.markers(), &extras, &groups, &tags, &build_options, )?; let hasher = HashStrategy::from_resolution(&resolution, HashCheckingMode::Verify)?; (resolution, hasher) } else { // When resolving, don't take any external preferences into account. let preferences = Vec::default(); let options = OptionsBuilder::new() .resolution_mode(resolution_mode) .prerelease_mode(prerelease_mode) .dependency_mode(dependency_mode) .exclude_newer(exclude_newer.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend) .build_options(build_options.clone()) .build(); let resolution = match operations::resolve( requirements, constraints, overrides, excludes, source_trees, project, BTreeSet::default(), extras, &groups, preferences, site_packages.clone(), &hasher, &reinstall, &upgrade, Some(&tags), ResolverEnvironment::specific(marker_env.clone()), python_requirement, interpreter.markers(), Conflicts::empty(), &client, &flat_index, state.index(), &build_dispatch, concurrency, options, Box::new(DefaultResolveLogger), printer, ) .await { Ok(resolution) => Resolution::from(resolution), Err(err) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } }; (resolution, hasher) }; // Constrain any build requirements marked as `match-runtime = true`. let extra_build_requires = extra_build_requires.match_runtime(&resolution)?; // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, &cache, &build_constraints, interpreter, &index_locations, &flat_index, &dependency_metadata, state.clone(), index_strategy, config_settings, config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, &build_options, &build_hasher, exclude_newer.clone(), sources, WorkspaceCache::default(), concurrency, preview, ); // Sync the environment. match operations::install( &resolution, site_packages, InstallationStrategy::Permissive, Modifications::Exact, &reinstall, &build_options, link_mode, compile, &hasher, &tags, &client, state.in_flight(), concurrency, &build_dispatch, &cache, &environment, Box::new(DefaultInstallLogger), installer_metadata, dry_run, printer, preview, ) .await { Ok(_) => {} Err(err) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } } // Notify the user of any resolution diagnostics. operations::diagnose_resolution(resolution.diagnostics(), printer)?; // Notify the user of any environment diagnostics. if strict && !dry_run.enabled() { operations::diagnose_environment(&resolution, &environment, &marker_env, &tags, printer)?; } Ok(ExitStatus::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/src/commands/pip/list.rs
crates/uv/src/commands/pip/list.rs
use std::cmp::max; use std::fmt::Write; use anyhow::Result; use futures::StreamExt; use itertools::Itertools; use owo_colors::OwoColorize; use rustc_hash::FxHashMap; use serde::Serialize; use tokio::sync::Semaphore; use tracing::debug; use unicode_width::UnicodeWidthStr; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; use uv_cli::ListFormat; use uv_client::{BaseClientBuilder, RegistryClientBuilder}; use uv_configuration::{Concurrency, IndexStrategy, KeyringProviderType}; use uv_distribution_filename::DistFilename; use uv_distribution_types::{ Diagnostic, IndexCapabilities, IndexLocations, InstalledDist, Name, RequiresPython, }; use uv_fs::Simplified; use uv_installer::SitePackages; use uv_normalize::PackageName; use uv_pep440::Version; use uv_preview::Preview; use uv_python::PythonRequest; use uv_python::{EnvironmentPreference, Prefix, PythonEnvironment, PythonPreference, Target}; use uv_resolver::{ExcludeNewer, PrereleaseMode}; use crate::commands::ExitStatus; use crate::commands::pip::latest::LatestClient; use crate::commands::pip::operations::report_target_environment; use crate::commands::reporters::LatestVersionReporter; use crate::printer::Printer; /// Enumerate the installed packages in the current environment. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_list( editable: Option<bool>, exclude: &[PackageName], format: &ListFormat, outdated: bool, prerelease: PrereleaseMode, index_locations: IndexLocations, index_strategy: IndexStrategy, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, concurrency: Concurrency, strict: bool, exclude_newer: ExcludeNewer, python: Option<&str>, system: bool, target: Option<Target>, prefix: Option<Prefix>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Disallow `--outdated` with `--format freeze`. if outdated && matches!(format, ListFormat::Freeze) { anyhow::bail!("`--outdated` cannot be used with `--format freeze`"); } // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python.map(PythonRequest::parse).unwrap_or_default(), EnvironmentPreference::from_system_flag(system, false), PythonPreference::default().with_system_flag(system), cache, preview, )?; // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; report_target_environment(&environment, cache, printer)?; // Build the installed index. let site_packages = SitePackages::from_environment(&environment)?; // Filter if `--editable` is specified; always sort by name. let results = site_packages .iter() .filter(|dist| editable.is_none() || editable == Some(dist.is_editable())) .filter(|dist| !exclude.contains(dist.name())) .sorted_unstable_by(|a, b| a.name().cmp(b.name()).then(a.version().cmp(b.version()))) .collect_vec(); // Determine the latest version for each package. let latest = if outdated && !results.is_empty() { let capabilities = IndexCapabilities::default(); let client_builder = client_builder.clone().keyring(keyring_provider); // Initialize the registry client. let client = RegistryClientBuilder::new( client_builder, cache.clone().with_refresh(Refresh::All(Timestamp::now())), ) .index_locations(index_locations) .index_strategy(index_strategy) .markers(environment.interpreter().markers()) .platform(environment.interpreter().platform()) .build(); let download_concurrency = Semaphore::new(concurrency.downloads); // Determine the platform tags. let interpreter = environment.interpreter(); let tags = interpreter.tags()?; let requires_python = RequiresPython::greater_than_equal_version(interpreter.python_full_version()); // Initialize the client to fetch the latest version of each package. let client = LatestClient { client: &client, capabilities: &capabilities, prerelease, exclude_newer: &exclude_newer, tags: Some(tags), requires_python: Some(&requires_python), }; let reporter = LatestVersionReporter::from(printer).with_length(results.len() as u64); // Fetch the latest version for each package. let mut fetches = futures::stream::iter(&results) .map(async |dist| { let latest = client .find_latest(dist.name(), None, &download_concurrency) .await?; Ok::<(&PackageName, Option<DistFilename>), uv_client::Error>((dist.name(), latest)) }) .buffer_unordered(concurrency.downloads); let mut map = FxHashMap::default(); while let Some((package, version)) = fetches.next().await.transpose()? { if let Some(version) = version.as_ref() { reporter.on_fetch_version(package, version.version()); } else { reporter.on_fetch_progress(); } map.insert(package, version); } reporter.on_fetch_complete(); map } else { FxHashMap::default() }; // Remove any up-to-date packages from the results. let results = if outdated { results .into_iter() .filter(|dist| { latest[dist.name()] .as_ref() .is_some_and(|filename| filename.version() > dist.version()) }) .collect_vec() } else { results }; match format { ListFormat::Json => { let rows = results .iter() .copied() .map(|dist| Entry { name: dist.name().clone(), version: dist.version().clone(), latest_version: latest .get(dist.name()) .and_then(|filename| filename.as_ref()) .map(DistFilename::version) .cloned(), latest_filetype: latest .get(dist.name()) .and_then(|filename| filename.as_ref()) .map(FileType::from), editable_project_location: dist .as_editable() .map(|url| url.to_file_path().unwrap().simplified_display().to_string()), }) .collect_vec(); let output = serde_json::to_string(&rows)?; writeln!(printer.stdout_important(), "{output}")?; } ListFormat::Columns if results.is_empty() => {} ListFormat::Columns => { // The package name and version are always present. let mut columns = vec![ Column { header: String::from("Package"), rows: results .iter() .copied() .map(|dist| dist.name().to_string()) .collect_vec(), }, Column { header: String::from("Version"), rows: results .iter() .map(|dist| dist.version().to_string()) .collect_vec(), }, ]; // The latest version and type are only displayed if outdated. if outdated { columns.push(Column { header: String::from("Latest"), rows: results .iter() .map(|dist| { latest .get(dist.name()) .and_then(|filename| filename.as_ref()) .map(DistFilename::version) .map(ToString::to_string) .unwrap_or_default() }) .collect_vec(), }); columns.push(Column { header: String::from("Type"), rows: results .iter() .map(|dist| { latest .get(dist.name()) .and_then(|filename| filename.as_ref()) .map(FileType::from) .as_ref() .map(ToString::to_string) .unwrap_or_default() }) .collect_vec(), }); } // Editable column is only displayed if at least one editable package is found. if results.iter().copied().any(InstalledDist::is_editable) { columns.push(Column { header: String::from("Editable project location"), rows: results .iter() .map(|dist| dist.as_editable()) .map(|url| { url.map(|url| { url.to_file_path().unwrap().simplified_display().to_string() }) .unwrap_or_default() }) .collect_vec(), }); } for elems in MultiZip(columns.iter().map(Column::fmt).collect_vec()) { writeln!(printer.stdout_important(), "{}", elems.join(" ").trim_end())?; } } ListFormat::Freeze if results.is_empty() => {} ListFormat::Freeze => { for dist in &results { writeln!( printer.stdout_important(), "{}=={}", dist.name().bold(), dist.version() )?; } } } // Validate that the environment is consistent. if strict { // Determine the markers and tags to use for resolution. let markers = environment.interpreter().resolver_marker_environment(); let tags = environment.interpreter().tags()?; for diagnostic in site_packages.diagnostics(&markers, tags)? { writeln!( printer.stderr(), "{}{} {}", "warning".yellow().bold(), ":".bold(), diagnostic.message().bold() )?; } } Ok(ExitStatus::Success) } #[derive(Debug)] enum FileType { /// A wheel distribution (i.e., a `.whl` file). Wheel, /// A source distribution (e.g., a `.tar.gz` file). SourceDistribution, } impl std::fmt::Display for FileType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Wheel => write!(f, "wheel"), Self::SourceDistribution => write!(f, "sdist"), } } } impl Serialize for FileType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { Self::Wheel => serializer.serialize_str("wheel"), Self::SourceDistribution => serializer.serialize_str("sdist"), } } } impl From<&DistFilename> for FileType { fn from(filename: &DistFilename) -> Self { match filename { DistFilename::WheelFilename(_) => Self::Wheel, DistFilename::SourceDistFilename(_) => Self::SourceDistribution, } } } /// An entry in a JSON list of installed packages. #[derive(Debug, Serialize)] struct Entry { name: PackageName, version: Version, #[serde(skip_serializing_if = "Option::is_none")] latest_version: Option<Version>, #[serde(skip_serializing_if = "Option::is_none")] latest_filetype: Option<FileType>, #[serde(skip_serializing_if = "Option::is_none")] editable_project_location: Option<String>, } /// A column in a table. #[derive(Debug)] struct Column { /// The header of the column. header: String, /// The rows of the column. rows: Vec<String>, } impl<'a> Column { /// Return the width of the column. fn max_width(&self) -> usize { max( self.header.width(), self.rows.iter().map(|f| f.width()).max().unwrap_or(0), ) } /// Return an iterator of the column, with the header and rows formatted to the maximum width. fn fmt(&'a self) -> impl Iterator<Item = String> + 'a { let max_width = self.max_width(); let header = vec![ format!("{0:width$}", self.header, width = max_width), format!("{:-^width$}", "", width = max_width), ]; header .into_iter() .chain(self.rows.iter().map(move |f| format!("{f:max_width$}"))) } } /// Zip an unknown number of iterators. /// /// A combination of [`itertools::multizip`] and [`itertools::izip`]. #[derive(Debug)] struct MultiZip<T>(Vec<T>); impl<T> Iterator for MultiZip<T> where T: Iterator, { type Item = Vec<T::Item>; fn next(&mut self) -> Option<Self::Item> { self.0.iter_mut().map(Iterator::next).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/src/commands/pip/check.rs
crates/uv/src/commands/pip/check.rs
use std::fmt::Write; use std::time::Instant; use anyhow::Result; use owo_colors::OwoColorize; use uv_cache::Cache; use uv_configuration::TargetTriple; use uv_distribution_types::{Diagnostic, InstalledDist}; use uv_installer::{SitePackages, SitePackagesDiagnostic}; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PythonEnvironment, PythonPreference, PythonRequest, PythonVersion, }; use crate::commands::pip::operations::report_target_environment; use crate::commands::pip::{resolution_markers, resolution_tags}; use crate::commands::{ExitStatus, elapsed}; use crate::printer::Printer; /// Check for incompatibilities in installed packages. pub(crate) fn pip_check( python: Option<&str>, system: bool, python_version: Option<&PythonVersion>, python_platform: Option<&TargetTriple>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let start = Instant::now(); // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python.map(PythonRequest::parse).unwrap_or_default(), EnvironmentPreference::from_system_flag(system, false), PythonPreference::default().with_system_flag(system), cache, preview, )?; report_target_environment(&environment, cache, printer)?; // Build the installed index. let site_packages = SitePackages::from_environment(&environment)?; let packages: Vec<&InstalledDist> = site_packages.iter().collect(); let s = if packages.len() == 1 { "" } else { "s" }; writeln!( printer.stderr(), "{}", format!( "Checked {} {}", format!("{} package{}", packages.len(), s).bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; // Determine the markers and tags to use for resolution. let markers = resolution_markers(python_version, python_platform, environment.interpreter()); let tags = resolution_tags(python_version, python_platform, environment.interpreter())?; // Run the diagnostics. let diagnostics: Vec<SitePackagesDiagnostic> = site_packages .diagnostics(&markers, &tags)? .into_iter() .collect(); if diagnostics.is_empty() { writeln!( printer.stderr(), "{}", "All installed packages are compatible".to_string().dimmed() )?; Ok(ExitStatus::Success) } else { let incompats = if diagnostics.len() == 1 { "incompatibility" } else { "incompatibilities" }; writeln!( printer.stderr(), "{}", format!( "Found {}", format!("{} {}", diagnostics.len(), incompats).bold() ) .dimmed() )?; for diagnostic in &diagnostics { writeln!(printer.stderr(), "{}", diagnostic.message().bold())?; } Ok(ExitStatus::Failure) } }
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/src/commands/pip/tree.rs
crates/uv/src/commands/pip/tree.rs
use std::cmp::Ordering; use std::collections::VecDeque; use std::fmt::Write; use anyhow::Result; use futures::StreamExt; use owo_colors::OwoColorize; use petgraph::Direction; use petgraph::graph::{EdgeIndex, NodeIndex}; use petgraph::prelude::EdgeRef; use rustc_hash::{FxHashMap, FxHashSet}; use tokio::sync::Semaphore; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; use uv_client::{BaseClientBuilder, RegistryClientBuilder}; use uv_configuration::{Concurrency, IndexStrategy, KeyringProviderType}; use uv_distribution_types::{Diagnostic, IndexCapabilities, IndexLocations, Name, RequiresPython}; use uv_installer::SitePackages; use uv_normalize::PackageName; use uv_pep440::{Operator, Version, VersionSpecifier, VersionSpecifiers}; use uv_pep508::{Requirement, VersionOrUrl}; use uv_preview::Preview; use uv_pypi_types::{ResolutionMetadata, ResolverMarkerEnvironment, VerbatimParsedUrl}; use uv_python::{EnvironmentPreference, PythonEnvironment, PythonPreference, PythonRequest}; use uv_resolver::{ExcludeNewer, PrereleaseMode}; use crate::commands::ExitStatus; use crate::commands::pip::latest::LatestClient; use crate::commands::pip::operations::report_target_environment; use crate::commands::reporters::LatestVersionReporter; use crate::printer::Printer; /// Display the installed packages in the current environment as a dependency tree. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_tree( show_version_specifiers: bool, depth: u8, prune: &[PackageName], package: &[PackageName], no_dedupe: bool, invert: bool, outdated: bool, prerelease: PrereleaseMode, index_locations: IndexLocations, index_strategy: IndexStrategy, keyring_provider: KeyringProviderType, client_builder: BaseClientBuilder<'_>, concurrency: Concurrency, strict: bool, exclude_newer: ExcludeNewer, python: Option<&str>, system: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python.map(PythonRequest::parse).unwrap_or_default(), EnvironmentPreference::from_system_flag(system, false), PythonPreference::default().with_system_flag(system), cache, preview, )?; report_target_environment(&environment, cache, printer)?; // Read packages from the virtual environment. let site_packages = SitePackages::from_environment(&environment)?; let packages = { let mut packages: FxHashMap<_, Vec<_>> = FxHashMap::default(); for package in site_packages.iter() { packages .entry(package.name()) .or_default() .push(package.read_metadata()?); } packages }; // Determine the markers and tags to use for the resolution. let markers = environment.interpreter().resolver_marker_environment(); let tags = environment.interpreter().tags()?; // Determine the latest version for each package. let latest = if outdated && !packages.is_empty() { let capabilities = IndexCapabilities::default(); let client_builder = client_builder.keyring(keyring_provider); // Initialize the registry client. let client = RegistryClientBuilder::new( client_builder, cache.clone().with_refresh(Refresh::All(Timestamp::now())), ) .index_locations(index_locations) .index_strategy(index_strategy) .markers(environment.interpreter().markers()) .platform(environment.interpreter().platform()) .build(); let download_concurrency = Semaphore::new(concurrency.downloads); // Determine the platform tags. let interpreter = environment.interpreter(); let tags = interpreter.tags()?; let requires_python = RequiresPython::greater_than_equal_version(interpreter.python_full_version()); // Initialize the client to fetch the latest version of each package. let client = LatestClient { client: &client, capabilities: &capabilities, prerelease, exclude_newer: &exclude_newer, tags: Some(tags), requires_python: Some(&requires_python), }; let reporter = LatestVersionReporter::from(printer).with_length(packages.len() as u64); // Fetch the latest version for each package. let mut fetches = futures::stream::iter(&packages) .map(async |(name, ..)| { let Some(filename) = client .find_latest(name, None, &download_concurrency) .await? else { return Ok(None); }; Ok::<Option<_>, uv_client::Error>(Some((*name, filename.into_version()))) }) .buffer_unordered(concurrency.downloads); let mut map = FxHashMap::default(); while let Some(entry) = fetches.next().await.transpose()? { let Some((name, version)) = entry else { reporter.on_fetch_progress(); continue; }; reporter.on_fetch_version(name, &version); map.insert(name, version); } reporter.on_fetch_complete(); map } else { FxHashMap::default() }; // Render the tree. let rendered_tree = DisplayDependencyGraph::new( depth.into(), prune, package, no_dedupe, invert, show_version_specifiers, &markers, &packages, &latest, ) .render() .join("\n"); writeln!(printer.stdout(), "{rendered_tree}")?; if rendered_tree.contains("(*)") { let message = if no_dedupe { "(*) Package tree is a cycle and cannot be shown".italic() } else { "(*) Package tree already displayed".italic() }; writeln!(printer.stdout(), "{message}")?; } // Validate that the environment is consistent. if strict { for diagnostic in site_packages.diagnostics(&markers, tags)? { writeln!( printer.stderr(), "{}{} {}", "warning".yellow().bold(), ":".bold(), diagnostic.message().bold() )?; } } Ok(ExitStatus::Success) } #[derive(Debug)] pub(crate) struct DisplayDependencyGraph<'env> { /// The constructed dependency graph. graph: petgraph::graph::Graph< &'env ResolutionMetadata, &'env Requirement<VerbatimParsedUrl>, petgraph::Directed, >, /// The packages considered as roots of the dependency tree. roots: Vec<NodeIndex>, /// The latest known version of each package. latest: &'env FxHashMap<&'env PackageName, Version>, /// Maximum display depth of the dependency tree depth: usize, /// Whether to de-duplicate the displayed dependencies. no_dedupe: bool, /// Whether to invert the dependency tree. invert: bool, /// Whether to include the version specifiers in the tree. show_version_specifiers: bool, } impl<'env> DisplayDependencyGraph<'env> { /// Create a new [`DisplayDependencyGraph`] for the set of installed distributions. pub(crate) fn new( depth: usize, prune: &[PackageName], package: &[PackageName], no_dedupe: bool, invert: bool, show_version_specifiers: bool, markers: &ResolverMarkerEnvironment, packages: &'env FxHashMap<&PackageName, Vec<&ResolutionMetadata>>, latest: &'env FxHashMap<&PackageName, Version>, ) -> Self { // Create a graph. let mut graph = petgraph::graph::Graph::< &ResolutionMetadata, &Requirement<VerbatimParsedUrl>, petgraph::Directed, >::new(); // Step 1: Add each installed package. let mut inverse: FxHashMap<PackageName, Vec<NodeIndex>> = FxHashMap::default(); for metadata in packages.values().flatten() { if prune.contains(&metadata.name) { continue; } let index = graph.add_node(metadata); inverse .entry(metadata.name.clone()) .or_default() .push(index); } // Step 2: Add all dependencies. for index in graph.node_indices() { let metadata = &graph[index]; for requirement in &metadata.requires_dist { if prune.contains(&requirement.name) { continue; } if !requirement.marker.evaluate(markers, &[]) { continue; } for dep_index in inverse .get(&requirement.name) .into_iter() .flatten() .copied() { let dep = &graph[dep_index]; // Avoid adding an edge if the dependency is not required by the current package. if let Some(VersionOrUrl::VersionSpecifier(specifier)) = requirement.version_or_url.as_ref() { if !specifier.contains(&dep.version) { continue; } } graph.add_edge(index, dep_index, requirement); } } } // Step 2: Reverse the graph. if invert { graph.reverse(); } // Step 3: Filter the graph to those nodes reachable from the target packages. if !package.is_empty() { // Perform a DFS from the root nodes to find the reachable nodes. let mut reachable = graph .node_indices() .filter(|index| package.contains(&graph[*index].name)) .collect::<FxHashSet<_>>(); let mut stack = reachable.iter().copied().collect::<VecDeque<_>>(); while let Some(node) = stack.pop_front() { for edge in graph.edges_directed(node, Direction::Outgoing) { if reachable.insert(edge.target()) { stack.push_back(edge.target()); } } } // Remove the unreachable nodes from the graph. graph.retain_nodes(|_, index| reachable.contains(&index)); } // Compute the list of roots. let roots = { let mut edges = vec![]; // Remove any cycles. let feedback_set: Vec<EdgeIndex> = petgraph::algo::greedy_feedback_arc_set(&graph) .map(|e| e.id()) .collect(); for edge_id in feedback_set { if let Some((source, target)) = graph.edge_endpoints(edge_id) { if let Some(weight) = graph.remove_edge(edge_id) { edges.push((source, target, weight)); } } } // Find the root nodes. let mut roots = graph .node_indices() .filter(|index| { graph .edges_directed(*index, Direction::Incoming) .next() .is_none() }) .collect::<Vec<_>>(); // Sort the roots. roots.sort_by_key(|index| { let metadata = &graph[*index]; (&metadata.name, &metadata.version) }); // Re-add the removed edges. for (source, target, weight) in edges { graph.add_edge(source, target, weight); } roots }; Self { graph, roots, latest, depth, no_dedupe, invert, show_version_specifiers, } } /// Perform a depth-first traversal of the given distribution and its dependencies. fn visit( &self, cursor: &Cursor, visited: &mut FxHashMap<&'env PackageName, Vec<PackageName>>, path: &mut Vec<&'env PackageName>, ) -> Vec<String> { // Short-circuit if the current path is longer than the provided depth. if path.len() > self.depth { return Vec::new(); } let metadata = &self.graph[cursor.node()]; let package_name = &metadata.name; let mut line = format!("{} v{}", package_name, metadata.version); // If the current package is not top-level (i.e., it has a parent), include the specifiers. if self.show_version_specifiers && !cursor.is_root() { line.push(' '); let requirement = self.aggregate_requirement(cursor); if self.invert { let parent = self.graph.edge_endpoints(cursor.edge().unwrap()).unwrap().0; let parent = &self.graph[parent].name; match requirement { None => { let _ = write!(line, "[requires: {parent} *]"); } Some(value) => { let _ = write!(line, "[requires: {parent} {value}]"); } } } else { match requirement { None => { let _ = write!(line, "[required: *]"); } Some(value) => { let _ = write!(line, "[required: {value}]"); } } } } // Skip the traversal if: // 1. The package is in the current traversal path (i.e., a dependency cycle). // 2. The package has been visited and de-duplication is enabled (default). if let Some(requirements) = visited.get(package_name) { if !self.no_dedupe || path.contains(&package_name) { return if requirements.is_empty() { vec![line] } else { vec![format!("{} (*)", line)] }; } } // Incorporate the latest version of the package, if known. let line = if let Some(version) = self .latest .get(package_name) .filter(|&version| *version > metadata.version) { format!("{line} {}", format!("(latest: v{version})").bold().cyan()) } else { line }; let mut dependencies = self .graph .edges_directed(cursor.node(), Direction::Outgoing) .fold(FxHashMap::default(), |mut acc, edge| { acc.entry(edge.target()) .or_insert_with(Vec::new) .push(edge.id()); acc }) .into_iter() .map(|(node, edges)| Cursor::with_edges(node, edges)) .collect::<Vec<_>>(); dependencies.sort_by_key(|node| { let metadata = &self.graph[node.node()]; (&metadata.name, &metadata.version) }); let mut lines = vec![line]; // Keep track of the dependency path to avoid cycles. visited.insert( package_name, dependencies .iter() .map(|node| { let metadata = &self.graph[node.node()]; metadata.name.clone() }) .collect(), ); path.push(package_name); for (index, dep) in dependencies.iter().enumerate() { // For sub-visited packages, add the prefix to make the tree display user-friendly. // The key observation here is you can group the tree as follows when you're at the // root of the tree: // root_package // ├── level_1_0 // Group 1 // │ ├── level_2_0 ... // │ │ ├── level_3_0 ... // │ │ └── level_3_1 ... // │ └── level_2_1 ... // ├── level_1_1 // Group 2 // │ ├── level_2_2 ... // │ └── level_2_3 ... // └── level_1_2 // Group 3 // └── level_2_4 ... // // The lines in Group 1 and 2 have `├── ` at the top and `| ` at the rest while // those in Group 3 have `└── ` at the top and ` ` at the rest. // This observation is true recursively even when looking at the subtree rooted // at `level_1_0`. let (prefix_top, prefix_rest) = if dependencies.len() - 1 == index { ("└── ", " ") } else { ("├── ", "│ ") }; for (visited_index, visited_line) in self.visit(dep, visited, path).iter().enumerate() { let prefix = if visited_index == 0 { prefix_top } else { prefix_rest }; lines.push(format!("{prefix}{visited_line}")); } } path.pop(); lines } /// Aggregate the requirements associated with the incoming edges for a node. fn aggregate_requirement(&self, cursor: &Cursor) -> Option<String> { let mut specifiers = Vec::new(); for edge_id in cursor.edge_ids() { let requirement = &self.graph[*edge_id]; let Some(version_or_url) = requirement.version_or_url.as_ref() else { continue; }; match version_or_url { VersionOrUrl::VersionSpecifier(values) => { specifiers.extend(values.iter().cloned()); } VersionOrUrl::Url(value) => return Some(value.to_string()), } } if specifiers.is_empty() { return None; } let display = Self::simplify_specifiers(specifiers).to_string(); if display.is_empty() { None } else { Some(display) } } /// Simplify a collection of specifiers into a canonical representation for display. fn simplify_specifiers(specifiers: Vec<VersionSpecifier>) -> VersionSpecifiers { let (lower, upper, others) = specifiers.into_iter().fold( (None, None, Vec::new()), |(lower, upper, mut rest), spec| match *spec.operator() { Operator::GreaterThan | Operator::GreaterThanEqual => { (Some(Self::prefer_lower(lower, spec)), upper, rest) } Operator::LessThan | Operator::LessThanEqual => { (lower, Some(Self::prefer_upper(upper, spec)), rest) } _ => { rest.push(spec); (lower, upper, rest) } }, ); let mut merged = lower .into_iter() .chain(upper) .chain(others) .collect::<Vec<_>>(); let mut seen = FxHashSet::default(); merged.retain(|spec| seen.insert(spec.to_string())); VersionSpecifiers::from_iter(merged) } fn prefer_lower( current: Option<VersionSpecifier>, candidate: VersionSpecifier, ) -> VersionSpecifier { match current { None => candidate, Some(existing) => match candidate.version().cmp(existing.version()) { Ordering::Greater => candidate, Ordering::Less => existing, Ordering::Equal => { let candidate_inclusive = matches!(candidate.operator(), Operator::GreaterThanEqual); let existing_inclusive = matches!(existing.operator(), Operator::GreaterThanEqual); if !candidate_inclusive && existing_inclusive { candidate } else { existing } } }, } } fn prefer_upper( current: Option<VersionSpecifier>, candidate: VersionSpecifier, ) -> VersionSpecifier { match current { None => candidate, Some(existing) => match candidate.version().cmp(existing.version()) { Ordering::Less => candidate, Ordering::Greater => existing, Ordering::Equal => { let candidate_inclusive = matches!(candidate.operator(), Operator::LessThanEqual); let existing_inclusive = matches!(existing.operator(), Operator::LessThanEqual); if !candidate_inclusive && existing_inclusive { candidate } else { existing } } }, } } /// Depth-first traverse the nodes to render the tree. pub(crate) fn render(&self) -> Vec<String> { let mut path = Vec::new(); let mut lines = Vec::with_capacity(self.graph.node_count()); let mut visited = FxHashMap::with_capacity_and_hasher(self.graph.node_count(), rustc_hash::FxBuildHasher); for node in &self.roots { path.clear(); let cursor = Cursor::root(*node); lines.extend(self.visit(&cursor, &mut visited, &mut path)); } lines } } /// A node in the dependency graph along with the edge that led to it, or `None` for root nodes. #[derive(Debug, Clone)] struct Cursor { node: NodeIndex, edges: Vec<EdgeIndex>, } impl Cursor { /// Create a [`Cursor`] representing a root node in the dependency tree. fn root(node: NodeIndex) -> Self { Self { node, edges: Vec::new(), } } /// Create a [`Cursor`] with the provided set of edges. fn with_edges(node: NodeIndex, edges: Vec<EdgeIndex>) -> Self { Self { node, edges } } /// Return the [`NodeIndex`] of the node. fn node(&self) -> NodeIndex { self.node } /// Return the [`EdgeIndex`] values that led to the node. fn edge_ids(&self) -> &[EdgeIndex] { &self.edges } /// Return the first [`EdgeIndex`] if the node is not a root. fn edge(&self) -> Option<EdgeIndex> { self.edges.first().copied() } /// Whether this cursor represents a root node. fn is_root(&self) -> bool { self.edges.is_empty() } } #[cfg(test)] mod tests { use super::DisplayDependencyGraph; use std::str::FromStr; use uv_pep440::{VersionSpecifier, VersionSpecifiers}; fn simplify_specs(specs: &[&str]) -> VersionSpecifiers { DisplayDependencyGraph::simplify_specifiers( specs .iter() .map(|s| VersionSpecifier::from_str(s).expect("valid specifier")) .collect(), ) } #[test] fn prefers_highest_lower_bound() { assert_eq!( simplify_specs(&[">=0.3.6", ">=0.3.7"]).to_string(), ">=0.3.7" ); } #[test] fn prefers_strict_bound_on_tie() { assert_eq!(simplify_specs(&[">=1", ">1"]).to_string(), ">1"); } #[test] fn retains_other_specifiers_and_dedupes() { assert_eq!( simplify_specs(&[">=0.3.7", "<0.4", "!=0.3.9", ">=0.3.7"]).to_string(), ">=0.3.7, !=0.3.9, <0.4" ); } #[test] fn prefers_lowest_upper_bound() { assert_eq!(simplify_specs(&["<=1", "<1"]).to_string(), "<1"); } #[test] fn keeps_both_bounds_when_present() { assert_eq!( simplify_specs(&[">=0.3.7", "<0.4", ">=0.3.6"]).to_string(), ">=0.3.7, <0.4" ); } }
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/src/commands/pip/loggers.rs
crates/uv/src/commands/pip/loggers.rs
use std::collections::BTreeSet; use std::fmt; use std::fmt::Write; use itertools::Itertools; use owo_colors::OwoColorize; use rustc_hash::{FxBuildHasher, FxHashMap}; use uv_configuration::DryRun; use uv_distribution_types::Name; use uv_normalize::PackageName; use crate::commands::pip::operations::{Changelog, ShortSpecifier}; use crate::commands::{ChangeEvent, ChangeEventKind, elapsed}; use crate::printer::Printer; /// A trait to handle logging during install operations. pub(crate) trait InstallLogger { /// Log the completion of the audit phase. fn on_audit( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result; /// Log the completion of the preparation phase. fn on_prepare( &self, count: usize, suffix: Option<&str>, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result; /// Log the completion of the uninstallation phase. fn on_uninstall( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result; /// Log the completion of the installation phase. fn on_install( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result; /// Log the completion of the operation. fn on_complete(&self, changelog: &Changelog, printer: Printer, dry_run: DryRun) -> fmt::Result; } /// The default logger for install operations. #[derive(Debug, Default, Clone, Copy)] pub(crate) struct DefaultInstallLogger; impl InstallLogger for DefaultInstallLogger { fn on_audit( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { if count == 0 { writeln!( printer.stderr(), "{}", format!("Audited in {}", elapsed(start.elapsed())).dimmed() )?; } else { let s = if count == 1 { "" } else { "s" }; writeln!( printer.stderr(), "{}", format!( "Audited {} {}", format!("{count} package{s}").bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() )?; } if dry_run.enabled() { writeln!(printer.stderr(), "Would make no changes")?; } Ok(()) } fn on_prepare( &self, count: usize, suffix: Option<&str>, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { let s = if count == 1 { "" } else { "s" }; let what = if let Some(suffix) = suffix { format!("{count} package{s} {suffix}") } else { format!("{count} package{s}") }; let what = what.bold(); writeln!( printer.stderr(), "{}", if dry_run.enabled() { format!("Would download {what}") } else { format!( "Prepared {what} {}", format!("in {}", elapsed(start.elapsed())).dimmed() ) } .dimmed() ) } fn on_uninstall( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { let s = if count == 1 { "" } else { "s" }; let what = format!("{count} package{s}"); let what = what.bold(); writeln!( printer.stderr(), "{}", if dry_run.enabled() { format!("Would uninstall {what}") } else { format!( "Uninstalled {what} {}", format!("in {}", elapsed(start.elapsed())).dimmed() ) } .dimmed() ) } fn on_install( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { let s = if count == 1 { "" } else { "s" }; let what = format!("{count} package{s}"); let what = what.bold(); writeln!( printer.stderr(), "{}", if dry_run.enabled() { format!("Would install {what}") } else { format!( "Installed {what} {}", format!("in {}", elapsed(start.elapsed())).dimmed() ) } .dimmed() ) } fn on_complete( &self, changelog: &Changelog, printer: Printer, _dry_run: DryRun, ) -> fmt::Result { for event in changelog .uninstalled .iter() .map(|distribution| ChangeEvent { dist: distribution, kind: ChangeEventKind::Removed, }) .chain(changelog.installed.iter().map(|distribution| ChangeEvent { dist: distribution, kind: ChangeEventKind::Added, })) .chain( changelog .reinstalled .iter() .map(|distribution| ChangeEvent { dist: distribution, kind: ChangeEventKind::Reinstalled, }), ) .sorted_unstable_by(|a, b| { a.dist .name() .cmp(b.dist.name()) .then_with(|| a.kind.cmp(&b.kind)) .then_with(|| a.dist.long_specifier().cmp(&b.dist.long_specifier())) }) { match event.kind { ChangeEventKind::Added => { writeln!( printer.stderr(), " {} {}{}", "+".green(), event.dist.name().bold(), event.dist.long_specifier().dimmed() )?; } ChangeEventKind::Removed => { writeln!( printer.stderr(), " {} {}{}", "-".red(), event.dist.name().bold(), event.dist.long_specifier().dimmed() )?; } ChangeEventKind::Reinstalled => { writeln!( printer.stderr(), " {} {}{}", "~".yellow(), event.dist.name().bold(), event.dist.long_specifier().dimmed() )?; } } } Ok(()) } } /// A logger that only shows installs and uninstalls, the minimal logging necessary to understand /// environment changes. #[derive(Debug, Default, Clone, Copy)] pub(crate) struct SummaryInstallLogger; impl InstallLogger for SummaryInstallLogger { fn on_audit( &self, _count: usize, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_prepare( &self, _count: usize, _suffix: Option<&str>, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_uninstall( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { DefaultInstallLogger.on_uninstall(count, start, printer, dry_run) } fn on_install( &self, count: usize, start: std::time::Instant, printer: Printer, dry_run: DryRun, ) -> fmt::Result { DefaultInstallLogger.on_install(count, start, printer, dry_run) } fn on_complete( &self, _changelog: &Changelog, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } } /// A logger that shows special output for the modification of the given target. #[derive(Debug, Clone)] pub(crate) struct UpgradeInstallLogger { target: PackageName, } impl UpgradeInstallLogger { /// Create a new logger for the given target. pub(crate) fn new(target: PackageName) -> Self { Self { target } } } impl InstallLogger for UpgradeInstallLogger { fn on_audit( &self, _count: usize, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_prepare( &self, _count: usize, _suffix: Option<&str>, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_uninstall( &self, _count: usize, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_install( &self, _count: usize, _start: std::time::Instant, _printer: Printer, _dry_run: DryRun, ) -> fmt::Result { Ok(()) } fn on_complete( &self, changelog: &Changelog, printer: Printer, // TODO(tk): Adjust format for dry_run _dry_run: DryRun, ) -> fmt::Result { // Index the removals by package name. let removals: FxHashMap<&PackageName, BTreeSet<ShortSpecifier>> = changelog.uninstalled.iter().fold( FxHashMap::with_capacity_and_hasher(changelog.uninstalled.len(), FxBuildHasher), |mut acc, distribution| { acc.entry(distribution.name()) .or_default() .insert(distribution.short_specifier()); acc }, ); // Index the additions by package name. let additions: FxHashMap<&PackageName, BTreeSet<ShortSpecifier>> = changelog.installed.iter().fold( FxHashMap::with_capacity_and_hasher(changelog.installed.len(), FxBuildHasher), |mut acc, distribution| { acc.entry(distribution.name()) .or_default() .insert(distribution.short_specifier()); acc }, ); // Summarize the change for the target. match (removals.get(&self.target), additions.get(&self.target)) { (Some(removals), Some(additions)) => { if removals == additions { let reinstalls = additions .iter() .map(|version| format!("v{version}")) .collect::<Vec<_>>() .join(", "); writeln!( printer.stderr(), "{} {} {}", "Reinstalled".yellow().bold(), &self.target, reinstalls )?; } else { let removals = removals .iter() .map(|version| format!("v{version}")) .collect::<Vec<_>>() .join(", "); let additions = additions .iter() .map(|version| format!("v{version}")) .collect::<Vec<_>>() .join(", "); writeln!( printer.stderr(), "{} {} {} -> {}", "Updated".green().bold(), &self.target, removals, additions )?; } } (Some(removals), None) => { let removals = removals .iter() .map(|version| format!("v{version}")) .collect::<Vec<_>>() .join(", "); writeln!( printer.stderr(), "{} {} {}", "Removed".red().bold(), &self.target, removals )?; } (None, Some(additions)) => { let additions = additions .iter() .map(|version| format!("v{version}")) .collect::<Vec<_>>() .join(", "); writeln!( printer.stderr(), "{} {} {}", "Added".green().bold(), &self.target, additions )?; } (None, None) => { writeln!( printer.stderr(), "{} {} {}", "Modified".dimmed(), &self.target.dimmed().bold(), "environment".dimmed() )?; } } // Follow-up with a detailed summary of all changes. DefaultInstallLogger.on_complete(changelog, printer, _dry_run)?; Ok(()) } } /// A trait to handle logging during resolve operations. pub(crate) trait ResolveLogger { /// Log the completion of the operation. fn on_complete(&self, count: usize, start: std::time::Instant, printer: Printer) -> fmt::Result; } /// The default logger for resolve operations. #[derive(Debug, Default, Clone, Copy)] pub(crate) struct DefaultResolveLogger; impl ResolveLogger for DefaultResolveLogger { fn on_complete( &self, count: usize, start: std::time::Instant, printer: Printer, ) -> fmt::Result { if count == 0 { writeln!( printer.stderr(), "{}", format!("Resolved in {}", elapsed(start.elapsed())).dimmed() ) } else { let s = if count == 1 { "" } else { "s" }; writeln!( printer.stderr(), "{}", format!( "Resolved {} {}", format!("{count} package{s}").bold(), format!("in {}", elapsed(start.elapsed())).dimmed() ) .dimmed() ) } } } /// A logger that doesn't show any output. #[derive(Debug, Default, Clone, Copy)] pub(crate) struct SummaryResolveLogger; impl ResolveLogger for SummaryResolveLogger { fn on_complete( &self, _count: usize, _start: std::time::Instant, _printer: Printer, ) -> fmt::Result { 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/src/commands/pip/install.rs
crates/uv/src/commands/pip/install.rs
use std::collections::BTreeSet; use anyhow::Context; use itertools::Itertools; use owo_colors::OwoColorize; use tracing::{Level, debug, enabled, warn}; use uv_cache::Cache; use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder}; use uv_configuration::{ BuildIsolation, BuildOptions, Concurrency, Constraints, DryRun, ExtrasSpecification, HashCheckingMode, IndexStrategy, Reinstall, SourceStrategy, Upgrade, }; use uv_configuration::{KeyringProviderType, TargetTriple}; use uv_dispatch::{BuildDispatch, SharedState}; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::{ ConfigSettings, DependencyMetadata, ExtraBuildVariables, Index, IndexLocations, NameRequirementSpecification, Origin, PackageConfigSettings, Requirement, Resolution, UnresolvedRequirementSpecification, }; use uv_fs::Simplified; use uv_install_wheel::LinkMode; use uv_installer::{InstallationStrategy, SatisfiesResult, SitePackages}; use uv_normalize::{DefaultExtras, DefaultGroups, PackageName}; use uv_preview::{Preview, PreviewFeatures}; use uv_pypi_types::Conflicts; use uv_python::{ EnvironmentPreference, Prefix, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVersion, Target, }; use uv_requirements::{GroupsSpecification, RequirementsSource, RequirementsSpecification}; use uv_resolver::{ DependencyMode, ExcludeNewer, FlatIndex, OptionsBuilder, PrereleaseMode, PylockToml, PythonRequirement, ResolutionMode, ResolverEnvironment, }; use uv_settings::PythonInstallMirrors; use uv_torch::{TorchMode, TorchSource, TorchStrategy}; use uv_types::HashStrategy; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::WorkspaceCache; use uv_workspace::pyproject::ExtraBuildDependencies; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger, InstallLogger}; use crate::commands::pip::operations::Modifications; use crate::commands::pip::operations::{report_interpreter, report_target_environment}; use crate::commands::pip::{operations, resolution_markers, resolution_tags}; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::{ExitStatus, diagnostics}; use crate::printer::Printer; /// Install packages into the current environment. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn pip_install( requirements: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], excludes: &[RequirementsSource], build_constraints: &[RequirementsSource], constraints_from_workspace: Vec<Requirement>, overrides_from_workspace: Vec<Requirement>, excludes_from_workspace: Vec<uv_normalize::PackageName>, build_constraints_from_workspace: Vec<Requirement>, extras: &ExtrasSpecification, groups: &GroupsSpecification, resolution_mode: ResolutionMode, prerelease_mode: PrereleaseMode, dependency_mode: DependencyMode, upgrade: Upgrade, index_locations: IndexLocations, index_strategy: IndexStrategy, torch_backend: Option<TorchMode>, dependency_metadata: DependencyMetadata, keyring_provider: KeyringProviderType, client_builder: &BaseClientBuilder<'_>, reinstall: Reinstall, link_mode: LinkMode, compile: bool, hash_checking: Option<HashCheckingMode>, installer_metadata: bool, config_settings: &ConfigSettings, config_settings_package: &PackageConfigSettings, build_isolation: BuildIsolation, extra_build_dependencies: &ExtraBuildDependencies, extra_build_variables: &ExtraBuildVariables, build_options: BuildOptions, modifications: Modifications, python_version: Option<PythonVersion>, python_platform: Option<TargetTriple>, python_downloads: PythonDownloads, install_mirrors: PythonInstallMirrors, strict: bool, exclude_newer: ExcludeNewer, sources: SourceStrategy, python: Option<String>, system: bool, break_system_packages: bool, target: Option<Target>, prefix: Option<Prefix>, python_preference: PythonPreference, concurrency: Concurrency, cache: Cache, dry_run: DryRun, printer: Printer, preview: Preview, ) -> anyhow::Result<ExitStatus> { let start = std::time::Instant::now(); if !preview.is_enabled(PreviewFeatures::EXTRA_BUILD_DEPENDENCIES) && !extra_build_dependencies.is_empty() { warn_user_once!( "The `extra-build-dependencies` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::EXTRA_BUILD_DEPENDENCIES ); } let client_builder = client_builder.clone().keyring(keyring_provider); // Read all requirements from the provided sources. let RequirementsSpecification { project, requirements, constraints, overrides, excludes, pylock, source_trees, groups, index_url, extra_index_urls, no_index, find_links, no_binary, no_build, extras: _, } = operations::read_requirements( requirements, constraints, overrides, excludes, extras, Some(groups), &client_builder, ) .await?; if pylock.is_some() { if !preview.is_enabled(PreviewFeatures::PYLOCK) { warn_user!( "The `--pylock` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.", PreviewFeatures::PYLOCK ); } } let constraints: Vec<NameRequirementSpecification> = constraints .iter() .cloned() .chain( constraints_from_workspace .into_iter() .map(NameRequirementSpecification::from), ) .collect(); let overrides: Vec<UnresolvedRequirementSpecification> = overrides .iter() .cloned() .chain( overrides_from_workspace .into_iter() .map(UnresolvedRequirementSpecification::from), ) .collect(); let excludes: Vec<PackageName> = excludes .into_iter() .chain(excludes_from_workspace) .collect(); // Read build constraints. let build_constraints: Vec<NameRequirementSpecification> = operations::read_constraints(build_constraints, &client_builder) .await? .into_iter() .chain( build_constraints_from_workspace .iter() .cloned() .map(NameRequirementSpecification::from), ) .collect(); // Detect the current Python interpreter. let environment = if target.is_some() || prefix.is_some() { let python_request = python.as_deref().map(PythonRequest::parse); let reporter = PythonDownloadReporter::single(printer); let installation = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::from_system_flag(system, false), python_preference.with_system_flag(system), python_downloads, &client_builder, &cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await?; report_interpreter(&installation, true, printer)?; PythonEnvironment::from_installation(installation) } else { let environment = PythonEnvironment::find( &python .as_deref() .map(PythonRequest::parse) .unwrap_or_default(), EnvironmentPreference::from_system_flag(system, true), PythonPreference::default().with_system_flag(system), &cache, preview, )?; report_target_environment(&environment, &cache, printer)?; environment }; // Lower the extra build dependencies, if any. let extra_build_requires = LoweredExtraBuildDependencies::from_non_lowered(extra_build_dependencies.clone()) .into_inner(); // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; // If the environment is externally managed, abort. if let Some(externally_managed) = environment.interpreter().is_externally_managed() { if break_system_packages { debug!("Ignoring externally managed environment due to `--break-system-packages`"); } else { let managed_message = match externally_managed.into_error() { Some(error) => format!( "The interpreter at {} is externally managed, and indicates the following:\n\n{}\n", environment.root().user_display().cyan(), textwrap::indent(&error, " ").green(), ), None => format!( "The interpreter at {} is externally managed and cannot be modified.", environment.root().user_display().cyan() ), }; let error_message = if system { // Add a hint about the `--system` flag format!( "{}\n{}{} Virtual environments were not considered due to the `--system` flag", managed_message, "hint".bold().cyan(), ":".bold() ) } else { // Add a hint to create a virtual environment format!( "{}\n{}{} Consider creating a virtual environment, e.g., with `uv venv`", managed_message, "hint".bold().cyan(), ":".bold() ) }; return Err(anyhow::Error::msg(error_message)); } } let _lock = environment .lock() .await .inspect_err(|err| { warn!("Failed to acquire environment lock: {err}"); }) .ok(); // Determine the markers and tags to use for the resolution. let interpreter = environment.interpreter(); let marker_env = resolution_markers( python_version.as_ref(), python_platform.as_ref(), interpreter, ); let tags = resolution_tags( python_version.as_ref(), python_platform.as_ref(), interpreter, )?; // Determine the set of installed packages. let site_packages = SitePackages::from_environment(&environment)?; // Check if the current environment satisfies the requirements. // Ideally, the resolver would be fast enough to let us remove this check. But right now, for large environments, // it's an order of magnitude faster to validate the environment than to resolve the requirements. if reinstall.is_none() && upgrade.is_none() && source_trees.is_empty() && groups.is_empty() && pylock.is_none() && matches!(modifications, Modifications::Sufficient) { match site_packages.satisfies_spec( &requirements, &constraints, &overrides, InstallationStrategy::Permissive, &marker_env, &tags, config_settings, config_settings_package, &extra_build_requires, extra_build_variables, )? { // If the requirements are already satisfied, we're done. SatisfiesResult::Fresh { recursive_requirements, } => { if enabled!(Level::DEBUG) { for requirement in recursive_requirements .iter() .map(ToString::to_string) .sorted() { debug!("Requirement satisfied: {requirement}"); } } DefaultInstallLogger.on_audit(requirements.len(), start, printer, dry_run)?; return Ok(ExitStatus::Success); } SatisfiesResult::Unsatisfied(requirement) => { debug!("At least one requirement is not satisfied: {requirement}"); } } } // Determine the Python requirement, if the user requested a specific version. let python_requirement = if let Some(python_version) = python_version.as_ref() { PythonRequirement::from_python_version(interpreter, python_version) } else { PythonRequirement::from_interpreter(interpreter) }; // Collect the set of required hashes. let hasher = if let Some(hash_checking) = hash_checking { HashStrategy::from_requirements( requirements .iter() .chain(overrides.iter()) .map(|entry| (&entry.requirement, entry.hashes.as_slice())), constraints .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), Some(&marker_env), hash_checking, )? } else { HashStrategy::None }; // Incorporate any index locations from the provided sources. let index_locations = index_locations.combine( extra_index_urls .into_iter() .map(Index::from_extra_index_url) .chain(index_url.map(Index::from_index_url)) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), find_links .into_iter() .map(Index::from_find_links) .map(|index| index.with_origin(Origin::RequirementsTxt)) .collect(), no_index, ); // Determine the PyTorch backend. let torch_backend = torch_backend .map(|mode| { let source = if uv_auth::PyxTokenStore::from_settings() .is_ok_and(|store| store.has_credentials()) { TorchSource::Pyx } else { TorchSource::default() }; TorchStrategy::from_mode( mode, source, python_platform .map(TargetTriple::platform) .as_ref() .unwrap_or(interpreter.platform()) .os(), ) }) .transpose()?; // Initialize the registry client. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(index_locations.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend.clone()) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Combine the `--no-binary` and `--no-build` flags from the requirements files. let build_options = build_options.combine(no_binary, no_build); // Resolve the flat indexes from `--find-links`. let flat_index = { let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), &cache); let entries = client .fetch_all(index_locations.flat_indexes().map(Index::url)) .await?; FlatIndex::from_entries(entries, Some(&tags), &hasher, &build_options) }; // Determine whether to enable build isolation. let types_build_isolation = match build_isolation { BuildIsolation::Isolate => uv_types::BuildIsolation::Isolated, BuildIsolation::Shared => uv_types::BuildIsolation::Shared(&environment), BuildIsolation::SharedPackage(ref packages) => { uv_types::BuildIsolation::SharedPackage(&environment, packages) } }; // Enforce (but never require) the build constraints, if `--require-hashes` or `--verify-hashes` // is provided. _Requiring_ hashes would be too strict, and would break with pip. let build_hasher = if hash_checking.is_some() { HashStrategy::from_requirements( std::iter::empty(), build_constraints .iter() .map(|entry| (&entry.requirement, entry.hashes.as_slice())), Some(&marker_env), HashCheckingMode::Verify, )? } else { HashStrategy::None }; let build_constraints = Constraints::from_requirements( build_constraints .iter() .map(|constraint| constraint.requirement.clone()), ); // Initialize any shared state. let state = SharedState::default(); // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, &cache, &build_constraints, interpreter, &index_locations, &flat_index, &dependency_metadata, state.clone(), index_strategy, config_settings, config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, &build_options, &build_hasher, exclude_newer.clone(), sources, WorkspaceCache::default(), concurrency, preview, ); let (resolution, hasher) = if let Some(pylock) = pylock { // Read the `pylock.toml` from disk or URL, and deserialize it from TOML. let (install_path, content) = if pylock.starts_with("http://") || pylock.starts_with("https://") { // Fetch the `pylock.toml` over HTTP(S). let url = uv_redacted::DisplaySafeUrl::parse(&pylock.to_string_lossy())?; let client = client_builder.build(); let response = client .for_host(&url) .get(url::Url::from(url.clone())) .send() .await?; response.error_for_status_ref()?; let content = response.text().await?; // Use the current working directory as the install path for remote lock files. let install_path = std::env::current_dir()?; (install_path, content) } else { let install_path = std::path::absolute(&pylock)?; let install_path = install_path.parent().unwrap().to_path_buf(); let content = fs_err::tokio::read_to_string(&pylock).await?; (install_path, content) }; let lock = toml::from_str::<PylockToml>(&content).with_context(|| { format!("Not a valid `pylock.toml` file: {}", pylock.user_display()) })?; // Verify that the Python version is compatible with the lock file. if let Some(requires_python) = lock.requires_python.as_ref() { if !requires_python.contains(interpreter.python_version()) { return Err(anyhow::anyhow!( "The requested interpreter resolved to Python {}, which is incompatible with the `pylock.toml`'s Python requirement: `{}`", interpreter.python_version(), requires_python, )); } } // Convert the extras and groups specifications into a concrete form. let extras = extras.with_defaults(DefaultExtras::default()); let extras = extras .extra_names(lock.extras.iter()) .cloned() .collect::<Vec<_>>(); let groups = groups .get(&pylock) .cloned() .unwrap_or_default() .with_defaults(DefaultGroups::List(lock.default_groups.clone())); let groups = groups .group_names(lock.dependency_groups.iter()) .cloned() .collect::<Vec<_>>(); let resolution = lock.to_resolution( &install_path, marker_env.markers(), &extras, &groups, &tags, &build_options, )?; let hasher = HashStrategy::from_resolution(&resolution, HashCheckingMode::Verify)?; (resolution, hasher) } else { // When resolving, don't take any external preferences into account. let preferences = Vec::default(); let options = OptionsBuilder::new() .resolution_mode(resolution_mode) .prerelease_mode(prerelease_mode) .dependency_mode(dependency_mode) .exclude_newer(exclude_newer.clone()) .index_strategy(index_strategy) .torch_backend(torch_backend) .build_options(build_options.clone()) .build(); // Resolve the requirements. let resolution = match operations::resolve( requirements, constraints, overrides, excludes, source_trees, project, BTreeSet::default(), extras, &groups, preferences, site_packages.clone(), &hasher, &reinstall, &upgrade, Some(&tags), ResolverEnvironment::specific(marker_env.clone()), python_requirement, interpreter.markers(), Conflicts::empty(), &client, &flat_index, state.index(), &build_dispatch, concurrency, options, Box::new(DefaultResolveLogger), printer, ) .await { Ok(graph) => Resolution::from(graph), Err(err) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } }; (resolution, hasher) }; // Constrain any build requirements marked as `match-runtime = true`. let extra_build_requires = extra_build_requires.match_runtime(&resolution)?; // Create a build dispatch. let build_dispatch = BuildDispatch::new( &client, &cache, &build_constraints, interpreter, &index_locations, &flat_index, &dependency_metadata, state.clone(), index_strategy, config_settings, config_settings_package, types_build_isolation, &extra_build_requires, extra_build_variables, link_mode, &build_options, &build_hasher, exclude_newer.clone(), sources, WorkspaceCache::default(), concurrency, preview, ); // Sync the environment. match operations::install( &resolution, site_packages, InstallationStrategy::Permissive, modifications, &reinstall, &build_options, link_mode, compile, &hasher, &tags, &client, state.in_flight(), concurrency, &build_dispatch, &cache, &environment, Box::new(DefaultInstallLogger), installer_metadata, dry_run, printer, preview, ) .await { Ok(..) => {} Err(err) => { return diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } } // Notify the user of any resolution diagnostics. operations::diagnose_resolution(resolution.diagnostics(), printer)?; // Notify the user of any environment diagnostics. if strict && !dry_run.enabled() { operations::diagnose_environment(&resolution, &environment, &marker_env, &tags, printer)?; } Ok(ExitStatus::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/src/commands/pip/operations.rs
crates/uv/src/commands/pip/operations.rs
//! Common operations shared across the `pip` API and subcommands. use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fmt::Write; use std::path::PathBuf; use std::sync::Arc; use anyhow::{Context, anyhow}; use itertools::Itertools; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::Cache; use uv_client::{BaseClientBuilder, RegistryClient}; use uv_configuration::{ BuildOptions, Concurrency, Constraints, DependencyGroups, DryRun, Excludes, ExtrasSpecification, Overrides, Reinstall, Upgrade, }; use uv_dispatch::BuildDispatch; use uv_distribution::{DistributionDatabase, SourcedDependencyGroups}; use uv_distribution_types::{ CachedDist, Diagnostic, Dist, InstalledDist, InstalledVersion, LocalDist, NameRequirementSpecification, Requirement, ResolutionDiagnostic, UnresolvedRequirement, UnresolvedRequirementSpecification, VersionOrUrlRef, }; use uv_distribution_types::{DistributionMetadata, InstalledMetadata, Name, Resolution}; use uv_fs::Simplified; use uv_install_wheel::LinkMode; use uv_installer::{InstallationStrategy, Plan, Planner, Preparer, SitePackages}; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pep508::{MarkerEnvironment, RequirementOrigin, VerbatimUrl}; use uv_platform_tags::Tags; use uv_preview::Preview; use uv_pypi_types::{Conflicts, ResolverMarkerEnvironment}; use uv_python::{PythonEnvironment, PythonInstallation}; use uv_requirements::{ GroupsSpecification, LookaheadResolver, NamedRequirementsResolver, RequirementsSource, RequirementsSpecification, SourceTree, SourceTreeResolver, }; use uv_resolver::{ DependencyMode, Exclusions, FlatIndex, InMemoryIndex, Manifest, Options, Preference, Preferences, PythonRequirement, Resolver, ResolverEnvironment, ResolverOutput, }; use uv_tool::InstalledTools; use uv_types::{BuildContext, HashStrategy, InFlight, InstalledPackagesProvider}; use uv_warnings::warn_user; use crate::commands::compile_bytecode; use crate::commands::pip::loggers::{InstallLogger, ResolveLogger}; use crate::commands::reporters::{InstallReporter, PrepareReporter, ResolverReporter}; use crate::printer::Printer; /// Consolidate the requirements for an installation. pub(crate) async fn read_requirements( requirements: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], excludes: &[RequirementsSource], extras: &ExtrasSpecification, groups: Option<&GroupsSpecification>, client_builder: &BaseClientBuilder<'_>, ) -> Result<RequirementsSpecification, Error> { // If the user requests `extras` but does not provide a valid source (e.g., a `pyproject.toml`), // return an error. if !extras.is_empty() && !requirements.iter().any(RequirementsSource::allows_extras) { let hint = if requirements .iter() .any(|source| matches!(source, RequirementsSource::Editable(_))) { "Use `<dir>[extra]` syntax or `-r <file>` instead." } else { "Use `package[extra]` syntax instead." }; return Err(anyhow!( "Requesting extras requires a `pylock.toml`, `pyproject.toml`, `setup.cfg`, or `setup.py` file. {hint}" ) .into()); } // Read all requirements from the provided sources. Ok(RequirementsSpecification::from_sources( requirements, constraints, overrides, excludes, groups, client_builder, ) .await?) } /// Resolve a set of constraints. pub(crate) async fn read_constraints( constraints: &[RequirementsSource], client_builder: &BaseClientBuilder<'_>, ) -> Result<Vec<NameRequirementSpecification>, Error> { Ok( RequirementsSpecification::from_sources(&[], constraints, &[], &[], None, client_builder) .await? .constraints, ) } /// Resolve a set of requirements, similar to running `pip compile`. pub(crate) async fn resolve<InstalledPackages: InstalledPackagesProvider>( requirements: Vec<UnresolvedRequirementSpecification>, constraints: Vec<NameRequirementSpecification>, overrides: Vec<UnresolvedRequirementSpecification>, excludes: Vec<PackageName>, source_trees: Vec<SourceTree>, mut project: Option<PackageName>, workspace_members: BTreeSet<PackageName>, extras: &ExtrasSpecification, groups: &BTreeMap<PathBuf, DependencyGroups>, preferences: Vec<Preference>, installed_packages: InstalledPackages, hasher: &HashStrategy, reinstall: &Reinstall, upgrade: &Upgrade, tags: Option<&Tags>, resolver_env: ResolverEnvironment, python_requirement: PythonRequirement, current_environment: &MarkerEnvironment, conflicts: Conflicts, client: &RegistryClient, flat_index: &FlatIndex, index: &InMemoryIndex, build_dispatch: &BuildDispatch<'_>, concurrency: Concurrency, options: Options, logger: Box<dyn ResolveLogger>, printer: Printer, ) -> Result<ResolverOutput, Error> { let start = std::time::Instant::now(); // Resolve the requirements from the provided sources. let requirements = { // Partition the requirements into named and unnamed requirements. let (mut requirements, unnamed): (Vec<_>, Vec<_>) = requirements .into_iter() .partition_map(|spec| match spec.requirement { UnresolvedRequirement::Named(requirement) => { itertools::Either::Left(requirement) } UnresolvedRequirement::Unnamed(requirement) => { itertools::Either::Right(requirement) } }); // Resolve any unnamed requirements. if !unnamed.is_empty() { requirements.extend( NamedRequirementsResolver::new( hasher, index, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(unnamed.into_iter()) .await?, ); } // Resolve any source trees into requirements. if !source_trees.is_empty() { let resolutions = SourceTreeResolver::new( extras, hasher, index, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(source_trees.iter()) .await?; // If we resolved a single project, use it for the project name. project = project.or_else(|| { if let [resolution] = &resolutions[..] { Some(resolution.project.clone()) } else { None } }); // If any of the extras were unused, surface a warning. let mut unused_extras = extras .explicit_names() .filter(|extra| { !resolutions .iter() .any(|resolution| resolution.extras.contains(extra)) }) .collect::<Vec<_>>(); if !unused_extras.is_empty() { unused_extras.sort_unstable(); unused_extras.dedup(); let s = if unused_extras.len() == 1 { "" } else { "s" }; return Err(anyhow!( "Requested extra{s} not found: {}", unused_extras.iter().join(", ") ) .into()); } // Extend the requirements with the resolved source trees. requirements.extend( resolutions .into_iter() .flat_map(|resolution| resolution.requirements), ); } for (pyproject_path, groups) in groups { let metadata = SourcedDependencyGroups::from_virtual_project( pyproject_path, None, build_dispatch.locations(), build_dispatch.sources(), build_dispatch.workspace_cache(), client.credentials_cache(), ) .await .with_context(|| { format!( "Failed to read dependency groups from: {}", pyproject_path.display() ) })?; // Complain if dependency groups are named that don't appear. for name in groups.explicit_names() { if !metadata.dependency_groups.contains_key(name) { return Err(anyhow!( "The dependency group '{name}' was not found in the project: {}", pyproject_path.user_display() ))?; } } // Apply dependency-groups for (group_name, group) in &metadata.dependency_groups { if groups.contains(group_name) { requirements.extend(group.iter().cloned().map(|group| Requirement { origin: Some(RequirementOrigin::Group( pyproject_path.clone(), metadata.name.clone(), group_name.clone(), )), ..group })); } } } requirements }; // Resolve the overrides from the provided sources. let overrides = { // Partition the overrides into named and unnamed requirements. let (mut overrides, unnamed): (Vec<_>, Vec<_>) = overrides .into_iter() .partition_map(|spec| match spec.requirement { UnresolvedRequirement::Named(requirement) => { itertools::Either::Left(requirement) } UnresolvedRequirement::Unnamed(requirement) => { itertools::Either::Right(requirement) } }); // Resolve any unnamed overrides. if !unnamed.is_empty() { overrides.extend( NamedRequirementsResolver::new( hasher, index, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(unnamed.into_iter()) .await?, ); } overrides }; // Collect constraints, overrides, and excludes. let constraints = Constraints::from_requirements( constraints .into_iter() .map(|constraint| constraint.requirement) .chain(upgrade.constraints().cloned()), ); let overrides = Overrides::from_requirements(overrides); let excludes = excludes.into_iter().collect::<Excludes>(); let preferences = Preferences::from_iter(preferences, &resolver_env); // Determine any lookahead requirements. let lookaheads = match options.dependency_mode { DependencyMode::Transitive => { LookaheadResolver::new( &requirements, &constraints, &overrides, hasher, index, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new(ResolverReporter::from(printer))) .resolve(&resolver_env) .await? } DependencyMode::Direct => Vec::new(), }; // TODO(zanieb): Consider consuming these instead of cloning let exclusions = Exclusions::new(reinstall.clone(), upgrade.clone()); // Create a manifest of the requirements. let manifest = Manifest::new( requirements, constraints, overrides, excludes, preferences, project, workspace_members, exclusions, lookaheads, ); // Resolve the dependencies. let resolution = { // If possible, create a bound on the progress bar. let reporter = match options.dependency_mode { DependencyMode::Transitive => ResolverReporter::from(printer), DependencyMode::Direct => { ResolverReporter::from(printer).with_length(manifest.num_requirements() as u64) } }; let resolver = Resolver::new( manifest, options, &python_requirement, resolver_env, current_environment, conflicts, tags, flat_index, index, hasher, build_dispatch, installed_packages, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), )? .with_reporter(Arc::new(reporter)); resolver.resolve().await? }; logger.on_complete(resolution.len(), start, printer)?; Ok(resolution) } #[derive(Debug, Clone, Copy)] pub(crate) enum Modifications { /// Use `pip install` semantics, whereby existing installations are left as-is, unless they are /// marked for re-installation or upgrade. /// /// Ensures that the resulting environment is sufficient to meet the requirements, but without /// any unnecessary changes. Sufficient, /// Use `pip sync` semantics, whereby any existing, extraneous installations are removed. /// /// Ensures that the resulting environment is an exact match for the requirements, but may /// result in more changes than necessary. Exact, } /// A distribution which was or would be modified #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[allow(clippy::large_enum_variant)] pub(crate) enum ChangedDist { Local(LocalDist), Remote(Arc<Dist>), } impl Name for ChangedDist { fn name(&self) -> &PackageName { match self { Self::Local(dist) => dist.name(), Self::Remote(dist) => dist.name(), } } } /// The [`Version`] or [`VerbatimUrl`] for a changed dist. #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub(crate) enum ShortSpecifier<'a> { Version(&'a Version), Url(&'a VerbatimUrl), } impl std::fmt::Display for ShortSpecifier<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Version(version) => version.fmt(f), Self::Url(url) => write!(f, " @ {url}"), } } } /// The [`InstalledVersion`] or [`VerbatimUrl`] for a changed dist. #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub(crate) enum LongSpecifier<'a> { InstalledVersion(InstalledVersion<'a>), Url(&'a VerbatimUrl), } impl std::fmt::Display for LongSpecifier<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::InstalledVersion(version) => version.fmt(f), Self::Url(url) => write!(f, " @ {url}"), } } } impl ChangedDist { pub(crate) fn short_specifier(&self) -> ShortSpecifier<'_> { match self { Self::Local(dist) => ShortSpecifier::Version(dist.installed_version().version()), Self::Remote(dist) => match dist.version_or_url() { VersionOrUrlRef::Version(version) => ShortSpecifier::Version(version), VersionOrUrlRef::Url(url) => ShortSpecifier::Url(url), }, } } pub(crate) fn long_specifier(&self) -> LongSpecifier<'_> { match self { Self::Local(dist) => LongSpecifier::InstalledVersion(dist.installed_version()), Self::Remote(dist) => match dist.version_or_url() { VersionOrUrlRef::Version(version) => { LongSpecifier::InstalledVersion(InstalledVersion::Version(version)) } VersionOrUrlRef::Url(url) => LongSpecifier::Url(url), }, } } pub(crate) fn version(&self) -> Option<&Version> { match self { Self::Local(dist) => Some(dist.installed_version().version()), Self::Remote(dist) => dist.version(), } } } /// A summary of the changes made to the environment during an installation. #[derive(Debug, Clone, Default)] pub(crate) struct Changelog { /// The distributions that were installed. pub(crate) installed: HashSet<ChangedDist>, /// The distributions that were uninstalled. pub(crate) uninstalled: HashSet<ChangedDist>, /// The distributions that were reinstalled. pub(crate) reinstalled: HashSet<ChangedDist>, } impl Changelog { /// Create a [`Changelog`] from two iterators of [`ChangedDist`]s. pub(crate) fn new<I, U>(installed: I, uninstalled: U) -> Self where I: IntoIterator<Item = ChangedDist>, U: IntoIterator<Item = ChangedDist>, { // SAFETY: This is allowed because `LocalDist` implements `Hash` and `Eq` based solely on // the inner `kind`, and omits the types that rely on internal mutability. #[allow(clippy::mutable_key_type)] let mut uninstalled: HashSet<_> = uninstalled.into_iter().collect(); let (reinstalled, installed): (HashSet<_>, HashSet<_>) = installed .into_iter() .partition(|dist| uninstalled.contains(dist)); uninstalled.retain(|dist| !reinstalled.contains(dist)); Self { installed, uninstalled, reinstalled, } } /// Create a [`Changelog`] from a list of local distributions. pub(crate) fn from_local(installed: Vec<CachedDist>, uninstalled: Vec<InstalledDist>) -> Self { Self::new( installed .into_iter() .map(|dist| ChangedDist::Local(dist.into())), uninstalled .into_iter() .map(|dist| ChangedDist::Local(dist.into())), ) } /// Create a [`Changelog`] from a list of installed distributions. pub(crate) fn from_installed(installed: Vec<CachedDist>) -> Self { Self::from_local(installed, Vec::new()) } /// Returns `true` if the changelog includes a distribution with the given name, either via /// an installation or uninstallation. pub(crate) fn includes(&self, name: &PackageName) -> bool { self.installed.iter().any(|dist| dist.name() == name) || self.uninstalled.iter().any(|dist| dist.name() == name) } /// Returns `true` if the changelog is empty. pub(crate) fn is_empty(&self) -> bool { self.installed.is_empty() && self.uninstalled.is_empty() } } /// Install a set of requirements into the current environment. /// /// Returns a [`Changelog`] summarizing the changes made to the environment. pub(crate) async fn install( resolution: &Resolution, site_packages: SitePackages, installation: InstallationStrategy, modifications: Modifications, reinstall: &Reinstall, build_options: &BuildOptions, link_mode: LinkMode, compile: bool, hasher: &HashStrategy, tags: &Tags, client: &RegistryClient, in_flight: &InFlight, concurrency: Concurrency, build_dispatch: &BuildDispatch<'_>, cache: &Cache, venv: &PythonEnvironment, logger: Box<dyn InstallLogger>, installer_metadata: bool, dry_run: DryRun, printer: Printer, preview: Preview, ) -> Result<Changelog, Error> { let start = std::time::Instant::now(); // Partition into those that should be linked from the cache (`local`), those that need to be // downloaded (`remote`), and those that should be removed (`extraneous`). let plan = Planner::new(resolution) .build( site_packages, installation, reinstall, build_options, hasher, build_dispatch.locations(), build_dispatch.config_settings(), build_dispatch.config_settings_package(), build_dispatch.extra_build_requires(), build_dispatch.extra_build_variables(), cache, venv, tags, ) .context("Failed to determine installation plan")?; if dry_run.enabled() { return report_dry_run( dry_run, resolution, plan, modifications, start, logger.as_ref(), printer, ); } let Plan { cached, remote, reinstalls, extraneous, } = plan; // If we're in `install` mode, ignore any extraneous distributions. let extraneous = match modifications { Modifications::Sufficient => vec![], Modifications::Exact => extraneous, }; // Nothing to do. if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() && extraneous.is_empty() && !compile { logger.on_audit(resolution.len(), start, printer, dry_run)?; return Ok(Changelog::default()); } // Partition into two sets: those that require build isolation, and those that disable it. This // is effectively a heuristic to make `--no-build-isolation` work "more often" by way of giving // `--no-build-isolation` packages "access" to the rest of the environment. let (isolated_phase, shared_phase) = Plan { cached, remote, reinstalls, extraneous, } .partition(|name| build_dispatch.build_isolation().is_isolated(Some(name))); let has_isolated_phase = !isolated_phase.is_empty(); let has_shared_phase = !shared_phase.is_empty(); let mut installs = vec![]; let mut uninstalls = vec![]; // Execute the isolated-build phase. if has_isolated_phase { let (isolated_installs, isolated_uninstalls) = execute_plan( isolated_phase, None, resolution, build_options, link_mode, hasher, tags, client, in_flight, concurrency, build_dispatch, cache, venv, logger.as_ref(), installer_metadata, printer, preview, ) .await?; installs.extend(isolated_installs); uninstalls.extend(isolated_uninstalls); } if has_shared_phase { let (shared_installs, shared_uninstalls) = execute_plan( shared_phase, if has_isolated_phase { Some(InstallPhase::Shared) } else { None }, resolution, build_options, link_mode, hasher, tags, client, in_flight, concurrency, build_dispatch, cache, venv, logger.as_ref(), installer_metadata, printer, preview, ) .await?; installs.extend(shared_installs); uninstalls.extend(shared_uninstalls); } if compile { compile_bytecode(venv, &concurrency, cache, printer).await?; } // Construct a summary of the changes made to the environment. let changelog = Changelog::from_local(installs, uninstalls); // Notify the user of any environment modifications. logger.on_complete(&changelog, printer, dry_run)?; Ok(changelog) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum InstallPhase { /// A dedicated phase for building and installing packages with build-isolation disabled. Shared, } impl InstallPhase { fn label(self) -> &'static str { match self { Self::Shared => "without build isolation", } } } /// Execute a [`Plan`] to install distributions into a Python environment. async fn execute_plan( plan: Plan, phase: Option<InstallPhase>, resolution: &Resolution, build_options: &BuildOptions, link_mode: LinkMode, hasher: &HashStrategy, tags: &Tags, client: &RegistryClient, in_flight: &InFlight, concurrency: Concurrency, build_dispatch: &BuildDispatch<'_>, cache: &Cache, venv: &PythonEnvironment, logger: &dyn InstallLogger, installer_metadata: bool, printer: Printer, preview: Preview, ) -> Result<(Vec<CachedDist>, Vec<InstalledDist>), Error> { let Plan { cached, remote, reinstalls, extraneous, } = plan; // Download, build, and unzip any missing distributions. let wheels = if remote.is_empty() { vec![] } else { let start = std::time::Instant::now(); let preparer = Preparer::new( cache, tags, hasher, build_options, DistributionDatabase::new(client, build_dispatch, concurrency.downloads), ) .with_reporter(Arc::new( PrepareReporter::from(printer).with_length(remote.len() as u64), )); let wheels = preparer .prepare(remote.clone(), in_flight, resolution) .await?; logger.on_prepare( wheels.len(), phase.map(InstallPhase::label), start, printer, DryRun::Disabled, )?; wheels }; // Remove any upgraded or extraneous installations. let uninstalls = extraneous.into_iter().chain(reinstalls).collect::<Vec<_>>(); if !uninstalls.is_empty() { let start = std::time::Instant::now(); for dist_info in &uninstalls { match uv_installer::uninstall(dist_info).await { Ok(summary) => { debug!( "Uninstalled {} ({} file{}, {} director{})", dist_info.name(), summary.file_count, if summary.file_count == 1 { "" } else { "s" }, summary.dir_count, if summary.dir_count == 1 { "y" } else { "ies" }, ); } Err(uv_installer::UninstallError::Uninstall( uv_install_wheel::Error::MissingRecord(_), )) => { warn_user!( "Failed to uninstall package at {} due to missing `RECORD` file. Installation may result in an incomplete environment.", dist_info.install_path().user_display().cyan(), ); } Err(uv_installer::UninstallError::Uninstall( uv_install_wheel::Error::MissingTopLevel(_), )) => { warn_user!( "Failed to uninstall package at {} due to missing `top_level.txt` file. Installation may result in an incomplete environment.", dist_info.install_path().user_display().cyan(), ); } Err(err) => return Err(err.into()), } } logger.on_uninstall(uninstalls.len(), start, printer, DryRun::Disabled)?; } // Install the resolved distributions. let mut installs = wheels.into_iter().chain(cached).collect::<Vec<_>>(); if !installs.is_empty() { let start = std::time::Instant::now(); installs = uv_installer::Installer::new(venv, preview) .with_link_mode(link_mode) .with_cache(cache) .with_installer_metadata(installer_metadata) .with_reporter(Arc::new( InstallReporter::from(printer).with_length(installs.len() as u64), )) // This technically can block the runtime, but we are on the main thread and // have no other running tasks at this point, so this lets us avoid spawning a blocking // task. .install_blocking(installs)?; logger.on_install(installs.len(), start, printer, DryRun::Disabled)?; } Ok((installs, uninstalls)) } /// Display a message about the interpreter that was selected for the operation. #[allow(clippy::result_large_err)] pub(crate) fn report_interpreter( python: &PythonInstallation, dimmed: bool, printer: Printer, ) -> Result<(), Error> { let managed = python.source().is_managed(); let implementation = python.implementation(); let interpreter = python.interpreter(); if dimmed { if managed { writeln!( printer.stderr(), "{}", format!( "Using {} {}{}", implementation.pretty(), interpreter.python_version(), interpreter.variant().display_suffix(), ) .dimmed() )?; } else { writeln!( printer.stderr(), "{}", format!( "Using {} {}{} interpreter at: {}", implementation.pretty(), interpreter.python_version(), interpreter.variant().display_suffix(), interpreter.sys_executable().user_display() ) .dimmed() )?; } } else { if managed { writeln!( printer.stderr(), "Using {} {}{}", implementation.pretty(), interpreter.python_version().cyan(), interpreter.variant().display_suffix().cyan() )?; } else { writeln!( printer.stderr(), "Using {} {}{} interpreter at: {}", implementation.pretty(), interpreter.python_version(), interpreter.variant().display_suffix(), interpreter.sys_executable().user_display().cyan() )?; } } Ok(()) } /// Display a message about the target environment for the operation. #[allow(clippy::result_large_err)] pub(crate) fn report_target_environment( env: &PythonEnvironment, cache: &Cache, printer: Printer, ) -> Result<(), Error> { let message = format!( "Using Python {} environment at: {}", env.interpreter().python_version(), env.root().user_display() ); let Ok(target) = std::path::absolute(env.root()) else { debug!("{}", message); return Ok(()); }; // Do not report environments in the cache if target.starts_with(cache.root()) { debug!("{}", message); return Ok(()); } // Do not report tool environments if let Ok(tools) = InstalledTools::from_settings() { if target.starts_with(tools.root()) { debug!("{}", message); return Ok(()); } } // Do not report a default environment path if let Ok(default) = std::path::absolute(PathBuf::from(".venv")) { if target == default { debug!("{}", message); return Ok(()); } } Ok(writeln!(printer.stderr(), "{}", message.dimmed())?) } /// Report on the results of a dry-run installation. #[allow(clippy::result_large_err)] fn report_dry_run( dry_run: DryRun, resolution: &Resolution, plan: Plan, modifications: Modifications, start: std::time::Instant, logger: &dyn InstallLogger, printer: Printer, ) -> Result<Changelog, Error> { let Plan { cached, remote, reinstalls, extraneous, } = plan; // If we're in `install` mode, ignore any extraneous distributions. let extraneous = match modifications { Modifications::Sufficient => vec![], Modifications::Exact => extraneous, }; // Nothing to do. if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() && extraneous.is_empty() { logger.on_audit(resolution.len(), start, printer, dry_run)?; return Ok(Changelog::default()); } // Download, build, and unzip any missing distributions. let wheels = if remote.is_empty() { vec![] } else { logger.on_prepare(remote.len(), None, start, printer, dry_run)?; remote.clone() }; // Remove any upgraded or extraneous installations. let uninstalls = extraneous.len() + reinstalls.len(); if uninstalls > 0 {
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/src/commands/pip/mod.rs
crates/uv/src/commands/pip/mod.rs
use std::borrow::Cow; use uv_configuration::TargetTriple; use uv_platform_tags::{Tags, TagsError}; use uv_pypi_types::ResolverMarkerEnvironment; use uv_python::{Interpreter, PythonVersion}; pub(crate) mod check; pub(crate) mod compile; pub(crate) mod freeze; pub(crate) mod install; pub(crate) mod latest; pub(crate) mod list; pub(crate) mod loggers; pub(crate) mod operations; pub(crate) mod show; pub(crate) mod sync; pub(crate) mod tree; pub(crate) mod uninstall; pub(crate) fn resolution_markers( python_version: Option<&PythonVersion>, python_platform: Option<&TargetTriple>, interpreter: &Interpreter, ) -> ResolverMarkerEnvironment { match (python_platform, python_version) { (Some(python_platform), Some(python_version)) => ResolverMarkerEnvironment::from( python_version.markers(&python_platform.markers(interpreter.markers())), ), (Some(python_platform), None) => { ResolverMarkerEnvironment::from(python_platform.markers(interpreter.markers())) } (None, Some(python_version)) => { ResolverMarkerEnvironment::from(python_version.markers(interpreter.markers())) } (None, None) => interpreter.resolver_marker_environment(), } } pub(crate) fn resolution_tags<'env>( python_version: Option<&PythonVersion>, python_platform: Option<&TargetTriple>, interpreter: &'env Interpreter, ) -> Result<Cow<'env, Tags>, TagsError> { if python_platform.is_none() && python_version.is_none() { return Ok(Cow::Borrowed(interpreter.tags()?)); } let (platform, manylinux_compatible) = if let Some(python_platform) = python_platform { ( &python_platform.platform(), python_platform.manylinux_compatible(), ) } else { (interpreter.platform(), interpreter.manylinux_compatible()) }; let version_tuple = if let Some(python_version) = python_version { (python_version.major(), python_version.minor()) } else { interpreter.python_tuple() }; let tags = Tags::from_env( platform, version_tuple, interpreter.implementation_name(), interpreter.implementation_tuple(), manylinux_compatible, interpreter.gil_disabled(), true, )?; Ok(Cow::Owned(tags)) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/pip/show.rs
crates/uv/src/commands/pip/show.rs
use std::fmt::Write; use anyhow::Result; use fs_err::File; use itertools::{Either, Itertools}; use owo_colors::OwoColorize; use rustc_hash::FxHashMap; use tracing::debug; use uv_cache::Cache; use uv_distribution_types::{Diagnostic, Name}; use uv_fs::Simplified; use uv_install_wheel::read_record_file; use uv_installer::SitePackages; use uv_normalize::PackageName; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, Prefix, PythonEnvironment, PythonPreference, PythonRequest, Target, }; use crate::commands::ExitStatus; use crate::commands::pip::operations::report_target_environment; use crate::printer::Printer; /// Show information about one or more installed packages. pub(crate) fn pip_show( mut packages: Vec<PackageName>, strict: bool, python: Option<&str>, system: bool, target: Option<Target>, prefix: Option<Prefix>, files: bool, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if packages.is_empty() { #[allow(clippy::print_stderr)] { writeln!( printer.stderr(), "{}{} Please provide a package name or names.", "warning".yellow().bold(), ":".bold(), )?; } return Ok(ExitStatus::Failure); } // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python.map(PythonRequest::parse).unwrap_or_default(), EnvironmentPreference::from_system_flag(system, false), PythonPreference::default().with_system_flag(system), cache, preview, )?; // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; report_target_environment(&environment, cache, printer)?; // Build the installed index. let site_packages = SitePackages::from_environment(&environment)?; // Determine the markers and tags to use for resolution. let markers = environment.interpreter().resolver_marker_environment(); let tags = environment.interpreter().tags()?; // Sort and deduplicate the packages, which are keyed by name. packages.sort_unstable(); packages.dedup(); // Map to the local distributions and collect missing packages. let (missing, distributions): (Vec<_>, Vec<_>) = packages.iter().partition_map(|name| { let installed = site_packages.get_packages(name); if installed.is_empty() { Either::Left(name) } else { Either::Right(installed) } }); if !missing.is_empty() { writeln!( printer.stderr(), "{}{} Package(s) not found for: {}", "warning".yellow().bold(), ":".bold(), missing.iter().join(", ").bold() )?; } let distributions = distributions.iter().flatten().collect_vec(); // Like `pip`, if no packages were found, return a failure. if distributions.is_empty() { return Ok(ExitStatus::Failure); } // Since Requires and Required-by fields need data parsed from metadata, especially the // Required-by field which needs to iterate over other installed packages' metadata. // To prevent the need to parse metadata repeatedly when multiple packages need to be shown, // we parse the metadata once and collect the needed data beforehand. let mut requires_map = FxHashMap::default(); // For Requires field for dist in &distributions { if let Ok(metadata) = dist.read_metadata() { requires_map.insert( dist.name(), metadata .requires_dist .iter() .filter(|req| req.evaluate_markers(&markers, &[])) .map(|req| &req.name) .sorted_unstable() .dedup() .collect_vec(), ); } } // For Required-by field if !requires_map.is_empty() { for installed in site_packages.iter() { if requires_map.contains_key(installed.name()) { continue; } if let Ok(metadata) = installed.read_metadata() { let requires = metadata .requires_dist .iter() .filter(|req| req.evaluate_markers(&markers, &[])) .map(|req| &req.name) .collect_vec(); if !requires.is_empty() { requires_map.insert(installed.name(), requires); } } } } // Print the information for each package. for (i, distribution) in distributions.iter().enumerate() { if i > 0 { // Print a separator between packages. writeln!(printer.stdout(), "---")?; } // Print the name, version, and location (e.g., the `site-packages` directory). writeln!(printer.stdout(), "Name: {}", distribution.name())?; writeln!(printer.stdout(), "Version: {}", distribution.version())?; writeln!( printer.stdout(), "Location: {}", distribution .install_path() .parent() .expect("package path is not root") .simplified_display() )?; if let Some(path) = distribution .as_editable() .and_then(|url| url.to_file_path().ok()) { writeln!( printer.stdout(), "Editable project location: {}", path.simplified_display() )?; } // If available, print the requirements. if let Some(requires) = requires_map.get(distribution.name()) { if requires.is_empty() { writeln!(printer.stdout(), "Requires:")?; } else { writeln!(printer.stdout(), "Requires: {}", requires.iter().join(", "))?; } let required_by = requires_map .iter() .filter(|(name, pkgs)| { **name != distribution.name() && pkgs.iter().any(|pkg| *pkg == distribution.name()) }) .map(|(name, _)| name) .sorted_unstable() .dedup() .collect_vec(); if required_by.is_empty() { writeln!(printer.stdout(), "Required-by:")?; } else { writeln!( printer.stdout(), "Required-by: {}", required_by.into_iter().join(", "), )?; } } // If requests, show the list of installed files. if files { let path = distribution.install_path().join("RECORD"); let record = read_record_file(&mut File::open(path)?)?; writeln!(printer.stdout(), "Files:")?; for entry in record { writeln!(printer.stdout(), " {}", entry.path)?; } } } // Validate that the environment is consistent. if strict { for diagnostic in site_packages.diagnostics(&markers, tags)? { writeln!( printer.stderr(), "{}{} {}", "warning".yellow().bold(), ":".bold(), diagnostic.message().bold() )?; } } Ok(ExitStatus::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/src/commands/pip/latest.rs
crates/uv/src/commands/pip/latest.rs
use tokio::sync::Semaphore; use tracing::debug; use uv_client::{MetadataFormat, RegistryClient, VersionFiles}; use uv_distribution_filename::DistFilename; use uv_distribution_types::{IndexCapabilities, IndexMetadataRef, IndexUrl, RequiresPython}; use uv_normalize::PackageName; use uv_platform_tags::Tags; use uv_resolver::{ExcludeNewer, PrereleaseMode}; use uv_warnings::warn_user_once; /// A client to fetch the latest version of a package from an index. /// /// The returned distribution is guaranteed to be compatible with the provided tags and Python /// requirement (if specified). #[derive(Debug, Clone)] pub(crate) struct LatestClient<'env> { pub(crate) client: &'env RegistryClient, pub(crate) capabilities: &'env IndexCapabilities, pub(crate) prerelease: PrereleaseMode, pub(crate) exclude_newer: &'env ExcludeNewer, pub(crate) tags: Option<&'env Tags>, pub(crate) requires_python: Option<&'env RequiresPython>, } impl LatestClient<'_> { /// Find the latest version of a package from an index. pub(crate) async fn find_latest( &self, package: &PackageName, index: Option<&IndexUrl>, download_concurrency: &Semaphore, ) -> Result<Option<DistFilename>, uv_client::Error> { debug!("Fetching latest version of: `{package}`"); let archives = match self .client .simple_detail( package, index.map(IndexMetadataRef::from), self.capabilities, download_concurrency, ) .await { Ok(archives) => archives, Err(err) => { return match err.kind() { uv_client::ErrorKind::RemotePackageNotFound(_) => Ok(None), uv_client::ErrorKind::NoIndex(_) => Ok(None), uv_client::ErrorKind::Offline(_) => Ok(None), _ => Err(err), }; } }; let mut latest: Option<DistFilename> = None; for (_, archive) in archives { let MetadataFormat::Simple(archive) = archive else { continue; }; for datum in archive.iter().rev() { // Find the first compatible distribution. let files = rkyv::deserialize::<VersionFiles, rkyv::rancor::Error>(&datum.files) .expect("archived version files always deserializes"); // Determine whether there's a compatible wheel and/or source distribution. let mut best = None; for (filename, file) in files.all() { // Skip distributions uploaded after the cutoff. if let Some(exclude_newer) = self.exclude_newer.exclude_newer_package(package) { match file.upload_time_utc_ms.as_ref() { Some(&upload_time) if upload_time >= exclude_newer.timestamp_millis() => { continue; } None => { warn_user_once!( "{} is missing an upload date, but user provided: {}", file.filename, self.exclude_newer ); } _ => {} } } // Skip pre-release distributions. if !filename.version().is_stable() { if !matches!(self.prerelease, PrereleaseMode::Allow) { continue; } } // Skip distributions that are yanked. if file.yanked.is_some_and(|yanked| yanked.is_yanked()) { continue; } // Skip distributions that are incompatible with the Python requirement. if let Some(requires_python) = self.requires_python { if file .requires_python .as_ref() .is_some_and(|file_requires_python| { !requires_python.is_contained_by(file_requires_python) }) { continue; } } // Skip distributions that are incompatible with the current platform. if let DistFilename::WheelFilename(filename) = &filename { if self .tags .is_some_and(|tags| !filename.compatibility(tags).is_compatible()) { continue; } } match filename { DistFilename::WheelFilename(_) => { best = Some(filename); break; } DistFilename::SourceDistFilename(_) => { if best.is_none() { best = Some(filename); } } } } match (latest.as_ref(), best) { (Some(current), Some(best)) => { if best.version() > current.version() { latest = Some(best); } } (None, Some(best)) => { latest = Some(best); } _ => {} } } } Ok(latest) } }
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/src/commands/pip/freeze.rs
crates/uv/src/commands/pip/freeze.rs
use std::fmt::Write; use std::path::PathBuf; use anyhow::Result; use itertools::Itertools; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::Cache; use uv_distribution_types::{Diagnostic, InstalledDistKind, Name}; use uv_fs::Simplified; use uv_installer::SitePackages; use uv_preview::Preview; use uv_python::PythonPreference; use uv_python::{EnvironmentPreference, Prefix, PythonEnvironment, PythonRequest, Target}; use crate::commands::ExitStatus; use crate::commands::pip::operations::report_target_environment; use crate::printer::Printer; /// Enumerate the installed packages in the current environment. pub(crate) fn pip_freeze( exclude_editable: bool, strict: bool, python: Option<&str>, system: bool, target: Option<Target>, prefix: Option<Prefix>, paths: Option<Vec<PathBuf>>, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { // Detect the current Python interpreter. let environment = PythonEnvironment::find( &python.map(PythonRequest::parse).unwrap_or_default(), EnvironmentPreference::from_system_flag(system, false), PythonPreference::default().with_system_flag(system), cache, preview, )?; // Apply any `--target` or `--prefix` directories. let environment = if let Some(target) = target { debug!( "Using `--target` directory at {}", target.root().user_display() ); environment.with_target(target)? } else if let Some(prefix) = prefix { debug!( "Using `--prefix` directory at {}", prefix.root().user_display() ); environment.with_prefix(prefix)? } else { environment }; report_target_environment(&environment, cache, printer)?; // Collect all the `site-packages` directories. let site_packages = match paths { Some(paths) => { paths .into_iter() .filter_map(|path| { environment .clone() .with_target(uv_python::Target::from(path)) // Drop invalid paths as per `pip freeze`. .ok() }) .map(|environment| SitePackages::from_environment(&environment)) .collect::<Result<Vec<_>>>()? } None => vec![SitePackages::from_environment(&environment)?], }; site_packages .iter() .flat_map(uv_installer::SitePackages::iter) .filter(|dist| !(exclude_editable && dist.is_editable())) .sorted_unstable_by(|a, b| a.name().cmp(b.name()).then(a.version().cmp(b.version()))) .map(|dist| match &dist.kind { InstalledDistKind::Registry(dist) => { format!("{}=={}", dist.name().bold(), dist.version) } InstalledDistKind::Url(dist) => { if dist.editable { format!("-e {}", dist.url) } else { format!("{} @ {}", dist.name().bold(), dist.url) } } InstalledDistKind::EggInfoFile(dist) => { format!("{}=={}", dist.name().bold(), dist.version) } InstalledDistKind::EggInfoDirectory(dist) => { format!("{}=={}", dist.name().bold(), dist.version) } InstalledDistKind::LegacyEditable(dist) => { format!("-e {}", dist.target.display()) } }) .dedup() .try_for_each(|dist| writeln!(printer.stdout_important(), "{dist}"))?; // Validate that the environment is consistent. if strict { // Determine the markers and tags to use for resolution. let markers = environment.interpreter().resolver_marker_environment(); let tags = environment.interpreter().tags()?; for entry in site_packages { for diagnostic in entry.diagnostics(&markers, tags)? { writeln!( printer.stderr(), "{}{} {}", "warning".yellow().bold(), ":".bold(), diagnostic.message().bold() )?; } } } Ok(ExitStatus::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/src/commands/tool/uninstall.rs
crates/uv/src/commands/tool/uninstall.rs
use std::fmt::Write; use anyhow::{Result, bail}; use itertools::Itertools; use owo_colors::OwoColorize; use tracing::debug; use uv_fs::Simplified; use uv_normalize::PackageName; use uv_tool::{InstalledTools, Tool, ToolEntrypoint}; use crate::commands::ExitStatus; use crate::printer::Printer; /// Uninstall a tool. pub(crate) async fn uninstall(name: Vec<PackageName>, printer: Printer) -> Result<ExitStatus> { let installed_tools = InstalledTools::from_settings()?.init()?; let _lock = match installed_tools.lock().await { Ok(lock) => lock, Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) => { if !name.is_empty() { for name in name { writeln!(printer.stderr(), "`{name}` is not installed")?; } return Ok(ExitStatus::Success); } writeln!(printer.stderr(), "Nothing to uninstall")?; return Ok(ExitStatus::Success); } Err(err) => return Err(err.into()), }; // Perform the uninstallation. do_uninstall(&installed_tools, name, printer).await?; // Clean up any empty directories. if uv_fs::directories(installed_tools.root())?.all(|path| uv_fs::is_temporary(&path)) { fs_err::tokio::remove_dir_all(&installed_tools.root()) .await .ignore_currently_being_deleted()?; if let Some(parent) = installed_tools.root().parent() { if uv_fs::directories(parent)?.all(|path| uv_fs::is_temporary(&path)) { fs_err::tokio::remove_dir_all(parent) .await .ignore_currently_being_deleted()?; } } } Ok(ExitStatus::Success) } trait IoErrorExt: std::error::Error + 'static { #[inline] fn is_in_process_of_being_deleted(&self) -> bool { if cfg!(target_os = "windows") { use std::error::Error; let mut e: &dyn Error = &self; loop { if e.to_string().contains("The file cannot be opened because it is in the process of being deleted. (os error 303)") { return true; } e = match e.source() { Some(e) => e, None => break, } } } false } } impl IoErrorExt for std::io::Error {} /// An extension trait to suppress "cannot open file because it's currently being deleted" trait IgnoreCurrentlyBeingDeleted { fn ignore_currently_being_deleted(self) -> Self; } impl IgnoreCurrentlyBeingDeleted for Result<(), std::io::Error> { fn ignore_currently_being_deleted(self) -> Self { match self { Ok(()) => Ok(()), Err(err) if err.kind() == std::io::ErrorKind::DirectoryNotEmpty => Ok(()), Err(err) if err.is_in_process_of_being_deleted() => Ok(()), Err(err) => Err(err), } } } /// Perform the uninstallation. async fn do_uninstall( installed_tools: &InstalledTools, names: Vec<PackageName>, printer: Printer, ) -> Result<()> { let mut dangling = false; let mut entrypoints = if names.is_empty() { let mut entrypoints = vec![]; for (name, receipt) in installed_tools.tools()? { let Ok(receipt) = receipt else { // If the tool is not installed properly, attempt to remove the environment anyway. match installed_tools.remove_environment(&name) { Ok(()) => { dangling = true; writeln!( printer.stderr(), "Removed dangling environment for `{name}`" )?; continue; } Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) => { bail!("`{name}` is not installed"); } Err(err) => { return Err(err.into()); } } }; entrypoints.extend(uninstall_tool(&name, &receipt, installed_tools).await?); } entrypoints } else { let mut entrypoints = vec![]; for name in names { let Some(receipt) = installed_tools.get_tool_receipt(&name)? else { // If the tool is not installed properly, attempt to remove the environment anyway. match installed_tools.remove_environment(&name) { Ok(()) => { writeln!( printer.stderr(), "Removed dangling environment for `{name}`" )?; return Ok(()); } Err(uv_tool::Error::VirtualEnvError(uv_virtualenv::Error::Io(err))) if err.kind() == std::io::ErrorKind::NotFound => { bail!("`{name}` is not installed"); } Err(err) => { return Err(err.into()); } } }; entrypoints.extend(uninstall_tool(&name, &receipt, installed_tools).await?); } entrypoints }; entrypoints.sort_unstable_by(|a, b| a.name.cmp(&b.name)); if entrypoints.is_empty() { // If we removed at least one dangling environment, there's no need to summarize. if !dangling { writeln!(printer.stderr(), "Nothing to uninstall")?; } return Ok(()); } let s = if entrypoints.len() == 1 { "" } else { "s" }; writeln!( printer.stderr(), "Uninstalled {} executable{s}: {}", entrypoints.len(), entrypoints .iter() .map(|entrypoint| entrypoint.name.bold()) .join(", ") )?; Ok(()) } /// Uninstall a tool. async fn uninstall_tool( name: &PackageName, receipt: &Tool, tools: &InstalledTools, ) -> Result<Vec<ToolEntrypoint>> { // Remove the tool itself. tools.remove_environment(name)?; #[cfg(windows)] let itself = std::env::current_exe().ok(); // Remove the tool's entrypoints. let entrypoints = receipt.entrypoints(); for entrypoint in entrypoints { debug!( "Removing executable: {}", entrypoint.install_path.user_display() ); #[cfg(windows)] if itself.as_ref().is_some_and(|itself| { std::path::absolute(&entrypoint.install_path).is_ok_and(|target| *itself == target) }) { self_replace::self_delete()?; continue; } match fs_err::tokio::remove_file(&entrypoint.install_path).await { Ok(()) => {} Err(err) if err.kind() == std::io::ErrorKind::NotFound => { debug!( "Executable not found: {}", entrypoint.install_path.user_display() ); } Err(err) => { return Err(err.into()); } } } Ok(entrypoints.to_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/src/commands/tool/list.rs
crates/uv/src/commands/tool/list.rs
use std::fmt::Write; use anyhow::Result; use itertools::Itertools; use owo_colors::OwoColorize; use uv_cache::Cache; use uv_fs::Simplified; use uv_python::LenientImplementationName; use uv_tool::InstalledTools; use uv_warnings::warn_user; use crate::commands::ExitStatus; use crate::printer::Printer; /// List installed tools. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn list( show_paths: bool, show_version_specifiers: bool, show_with: bool, show_extras: bool, show_python: bool, cache: &Cache, printer: Printer, ) -> Result<ExitStatus> { let installed_tools = InstalledTools::from_settings()?; let _lock = match installed_tools.lock().await { Ok(lock) => lock, Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) => { writeln!(printer.stderr(), "No tools installed")?; return Ok(ExitStatus::Success); } Err(err) => return Err(err.into()), }; let mut tools = installed_tools.tools()?.into_iter().collect::<Vec<_>>(); tools.sort_by_key(|(name, _)| name.clone()); if tools.is_empty() { writeln!(printer.stderr(), "No tools installed")?; return Ok(ExitStatus::Success); } for (name, tool) in tools { // Skip invalid tools let Ok(tool) = tool else { warn_user!( "Ignoring malformed tool `{name}` (run `{}` to remove)", format!("uv tool uninstall {name}").green() ); continue; }; // Get the tool environment let tool_env = match installed_tools.get_environment(&name, cache) { Ok(Some(env)) => env, Ok(None) => { warn_user!( "Tool `{name}` environment not found (run `{}` to reinstall)", format!("uv tool install {name} --reinstall").green() ); continue; } Err(e) => { warn_user!( "{e} (run `{}` to reinstall)", format!("uv tool install {name} --reinstall").green() ); continue; } }; // Get the tool version let version = match tool_env.version() { Ok(version) => version, Err(e) => { if let uv_tool::Error::EnvironmentError(e) = e { warn_user!( "{e} (run `{}` to reinstall)", format!("uv tool install {name} --reinstall").green() ); } else { writeln!(printer.stderr(), "{e}")?; } continue; } }; let version_specifier = show_version_specifiers .then(|| { tool.requirements() .iter() .filter(|req| req.name == name) .map(|req| req.source.to_string()) .filter(|s| !s.is_empty()) .peekable() }) .take_if(|specifiers| specifiers.peek().is_some()) .map(|mut specifiers| { let specifiers = specifiers.join(", "); format!(" [required: {specifiers}]") }) .unwrap_or_default(); let extra_requirements = show_extras .then(|| { tool.requirements() .iter() .filter(|req| req.name == name) .flat_map(|req| req.extras.iter()) // Flatten the extras from all matching requirements .peekable() }) .take_if(|extras| extras.peek().is_some()) .map(|extras| { let extras_str = extras.map(ToString::to_string).join(", "); format!(" [extras: {extras_str}]") }) .unwrap_or_default(); let python_version = if show_python { let interpreter = tool_env.environment().interpreter(); let implementation = LenientImplementationName::from(interpreter.implementation_name()); format!( " [{} {}]", implementation.pretty(), interpreter.python_full_version() ) } else { String::new() }; let with_requirements = show_with .then(|| { tool.requirements() .iter() .filter(|req| req.name != name) .peekable() }) .take_if(|requirements| requirements.peek().is_some()) .map(|requirements| { let requirements = requirements .map(|req| format!("{}{}", req.name, req.source)) .join(", "); format!(" [with: {requirements}]") }) .unwrap_or_default(); if show_paths { writeln!( printer.stdout(), "{} ({})", format!( "{name} v{version}{version_specifier}{extra_requirements}{with_requirements}{python_version}" ) .bold(), installed_tools.tool_dir(&name).simplified_display().cyan(), )?; } else { writeln!( printer.stdout(), "{}", format!( "{name} v{version}{version_specifier}{extra_requirements}{with_requirements}{python_version}" ) .bold() )?; } // Output tool entrypoints for entrypoint in tool.entrypoints() { if show_paths { writeln!(printer.stdout(), "- {}", entrypoint.to_string().cyan())?; } else { writeln!(printer.stdout(), "- {}", entrypoint.name)?; } } } Ok(ExitStatus::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/src/commands/tool/install.rs
crates/uv/src/commands/tool/install.rs
use std::fmt::Write; use std::str::FromStr; use anyhow::{Result, bail}; use owo_colors::OwoColorize; use tokio::sync::Semaphore; use tracing::{debug, trace}; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; use uv_client::{BaseClientBuilder, RegistryClientBuilder}; use uv_configuration::{ Concurrency, Constraints, DryRun, GitLfsSetting, Reinstall, TargetTriple, Upgrade, }; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::{ ExtraBuildRequires, IndexCapabilities, NameRequirementSpecification, Requirement, RequirementSource, UnresolvedRequirementSpecification, }; use uv_installer::{InstallationStrategy, SatisfiesResult, SitePackages}; use uv_normalize::PackageName; use uv_pep440::{VersionSpecifier, VersionSpecifiers}; use uv_pep508::MarkerTree; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest, }; use uv_requirements::{RequirementsSource, RequirementsSpecification}; use uv_settings::{PythonInstallMirrors, ResolverInstallerOptions, ToolOptions}; use uv_tool::InstalledTools; use uv_warnings::{warn_user, warn_user_once}; use uv_workspace::WorkspaceCache; use crate::commands::ExitStatus; use crate::commands::pip::latest::LatestClient; use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger}; use crate::commands::pip::operations::{self, Modifications}; use crate::commands::pip::{resolution_markers, resolution_tags}; use crate::commands::project::{ EnvironmentSpecification, PlatformState, ProjectError, resolve_environment, resolve_names, sync_environment, update_environment, }; use crate::commands::tool::common::{ finalize_tool_install, refine_interpreter, remove_entrypoints, }; use crate::commands::tool::{Target, ToolRequest}; use crate::commands::{diagnostics, reporters::PythonDownloadReporter}; use crate::printer::Printer; use crate::settings::{ResolverInstallerSettings, ResolverSettings}; /// Install a tool. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn install( package: String, editable: bool, from: Option<String>, with: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], excludes: &[RequirementsSource], build_constraints: &[RequirementsSource], entrypoints: &[PackageName], lfs: GitLfsSetting, python: Option<String>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, force: bool, options: ResolverInstallerOptions, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, cache: Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { if settings.resolver.torch_backend.is_some() { warn_user_once!( "The `--torch-backend` option is experimental and may change without warning." ); } let reporter = PythonDownloadReporter::single(printer); let python_request = python.as_deref().map(PythonRequest::parse); // Pre-emptively identify a Python interpreter. We need an interpreter to resolve any unnamed // requirements, even if we end up using a different interpreter for the tool install itself. let interpreter = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::OnlySystem, python_preference, python_downloads, &client_builder, &cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); // Initialize any shared state. let state = PlatformState::default(); let workspace_cache = WorkspaceCache::default(); // Parse the input requirement. let request = ToolRequest::parse(&package, from.as_deref())?; // If the user passed, e.g., `ruff@latest`, refresh the cache. let cache = if request.is_latest() { cache.with_refresh(Refresh::All(Timestamp::now())) } else { cache }; // Resolve the `--from` requirement. let requirement = match &request { // Ex) `ruff` ToolRequest::Package { executable, target: Target::Unspecified(from), } => { let source = if editable { RequirementsSource::from_editable(from)? } else { RequirementsSource::from_package(from)? }; let requirement = RequirementsSpecification::from_source(&source, &client_builder) .await? .requirements; // If the user provided an executable name, verify that it matches the `--from` requirement. let executable = if let Some(executable) = executable { let Ok(executable) = PackageName::from_str(executable) else { bail!( "Package requirement (`{from}`) provided with `--from` conflicts with install request (`{executable}`)", from = from.cyan(), executable = executable.cyan() ) }; Some(executable) } else { None }; let requirement = resolve_names( requirement, &interpreter, &settings, &client_builder, &state, concurrency, &cache, &workspace_cache, printer, preview, lfs, ) .await? .pop() .unwrap(); // Determine if it's an entirely different package (e.g., `uv install foo --from bar`). if let Some(executable) = executable { if requirement.name != executable { bail!( "Package name (`{}`) provided with `--from` does not match install request (`{}`)", requirement.name.cyan(), executable.cyan() ); } } requirement } // Ex) `ruff@0.6.0` ToolRequest::Package { target: Target::Version(.., name, extras, version), .. } => { if editable { bail!("`--editable` is only supported for local packages"); } Requirement { name: name.clone(), extras: extras.clone(), groups: Box::new([]), marker: MarkerTree::default(), source: RequirementSource::Registry { specifier: VersionSpecifiers::from(VersionSpecifier::equals_version( version.clone(), )), index: None, conflict: None, }, origin: None, } } // Ex) `ruff@latest` ToolRequest::Package { target: Target::Latest(.., name, extras), .. } => { if editable { bail!("`--editable` is only supported for local packages"); } Requirement { name: name.clone(), extras: extras.clone(), groups: Box::new([]), marker: MarkerTree::default(), source: RequirementSource::Registry { specifier: VersionSpecifiers::empty(), index: None, conflict: None, }, origin: None, } } // Ex) `python` ToolRequest::Python { .. } => { bail!( "Cannot install Python with `{}`. Did you mean to use `{}`?", "uv tool install".cyan(), "uv python install".cyan(), ); } }; // For `@latest`, fetch the latest version and create a constraint. let latest = if let ToolRequest::Package { target: Target::Latest(_, name, _), .. } = &request { // Build the registry client to fetch the latest version. let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone()) .index_locations(settings.resolver.index_locations.clone()) .index_strategy(settings.resolver.index_strategy) .markers(interpreter.markers()) .platform(interpreter.platform()) .build(); // Initialize the capabilities. let capabilities = IndexCapabilities::default(); let download_concurrency = Semaphore::new(concurrency.downloads); // Initialize the client to fetch the latest version. let latest_client = LatestClient { client: &client, capabilities: &capabilities, prerelease: settings.resolver.prerelease, exclude_newer: &settings.resolver.exclude_newer, tags: None, requires_python: None, }; // Fetch the latest version. if let Some(dist_filename) = latest_client .find_latest(name, None, &download_concurrency) .await? { let version = dist_filename.version().clone(); debug!("Resolved `{name}@latest` to `{name}=={version}`"); // The constraint pins the version during resolution to prevent backtracking. Some(Requirement { name: name.clone(), extras: vec![].into_boxed_slice(), groups: Box::new([]), marker: MarkerTree::default(), source: RequirementSource::Registry { specifier: VersionSpecifiers::from(VersionSpecifier::equals_version(version)), index: None, conflict: None, }, origin: None, }) } else { None } } else { None }; let package_name = &requirement.name; // If the user passed, e.g., `ruff@latest`, we need to mark it as upgradable. let settings = if request.is_latest() { ResolverInstallerSettings { resolver: ResolverSettings { upgrade: Upgrade::package(package_name.clone()).combine(settings.resolver.upgrade), ..settings.resolver }, ..settings } } else { settings }; // If the user passed `--force`, it implies `--reinstall-package <from>` let settings = if force { ResolverInstallerSettings { reinstall: Reinstall::package(package_name.clone()).combine(settings.reinstall), ..settings } } else { settings }; // Read the `--with` requirements. let spec = RequirementsSpecification::from_sources( with, constraints, overrides, excludes, None, &client_builder, ) .await?; // Resolve the `--from` and `--with` requirements. let requirements = { let mut requirements = Vec::with_capacity(1 + with.len()); requirements.push(requirement.clone()); requirements.extend( resolve_names( spec.requirements.clone(), &interpreter, &settings, &client_builder, &state, concurrency, &cache, &workspace_cache, printer, preview, lfs, ) .await?, ); requirements }; // Resolve the constraints. let constraints: Vec<_> = spec .constraints .into_iter() .map(|constraint| constraint.requirement) .collect(); // Resolve the overrides. let overrides = resolve_names( spec.overrides, &interpreter, &settings, &client_builder, &state, concurrency, &cache, &workspace_cache, printer, preview, lfs, ) .await?; // Resolve the build constraints. let build_constraints: Vec<Requirement> = operations::read_constraints(build_constraints, &client_builder) .await? .into_iter() .map(|constraint| constraint.requirement) .collect(); // Convert to tool options. let options = ToolOptions::from(options); let installed_tools = InstalledTools::from_settings()?.init()?; let _lock = installed_tools.lock().await?; // Find the existing receipt, if it exists. If the receipt is present but malformed, we'll // remove the environment and continue with the install. // // Later on, we want to replace entrypoints if the tool already exists, regardless of whether // the receipt was valid. // // (If we find existing entrypoints later on, and the tool _doesn't_ exist, we'll avoid removing // the external tool's entrypoints (without `--force`).) let (existing_tool_receipt, invalid_tool_receipt) = match installed_tools.get_tool_receipt(package_name) { Ok(None) => (None, false), Ok(Some(receipt)) => (Some(receipt), false), Err(_) => { // If the tool is not installed properly, remove the environment and continue. match installed_tools.remove_environment(package_name) { Ok(()) => { warn_user!( "Removed existing `{}` with invalid receipt", package_name.cyan() ); } Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) => {} Err(err) => { return Err(err.into()); } } (None, true) } }; let existing_environment = installed_tools .get_environment(package_name, &cache)? .filter(|environment| { if environment.environment().uses(&interpreter) { trace!( "Existing interpreter matches the requested interpreter for `{}`: {}", package_name, environment.environment().interpreter().sys_executable().display() ); true } else { let _ = writeln!( printer.stderr(), "Ignoring existing environment for `{}`: the requested Python interpreter does not match the environment interpreter", package_name.cyan(), ); false } }); // If the requested and receipt requirements are the same... if let Some(environment) = existing_environment.as_ref().filter(|_| { // And the user didn't request a reinstall or upgrade... !request.is_latest() && settings.reinstall.is_none() && settings.resolver.upgrade.is_none() }) { if let Some(tool_receipt) = existing_tool_receipt.as_ref() { if requirements == tool_receipt.requirements() && constraints == tool_receipt.constraints() && overrides == tool_receipt.overrides() && build_constraints == tool_receipt.build_constraints() { let ResolverInstallerSettings { resolver: ResolverSettings { config_setting, config_settings_package, extra_build_dependencies, extra_build_variables, .. }, .. } = &settings; // Lower the extra build dependencies, if any. let extra_build_requires = LoweredExtraBuildDependencies::from_non_lowered( extra_build_dependencies.clone(), ) .into_inner(); // Determine the markers and tags to use for the resolution. let markers = resolution_markers(None, python_platform.as_ref(), &interpreter); let tags = resolution_tags(None, python_platform.as_ref(), &interpreter)?; // Check if the installed packages meet the requirements. let site_packages = SitePackages::from_environment(environment.environment())?; if matches!( site_packages.satisfies_requirements( requirements.iter(), constraints.iter().chain(latest.iter()), overrides.iter(), InstallationStrategy::Permissive, &markers, &tags, config_setting, config_settings_package, &extra_build_requires, extra_build_variables, ), Ok(SatisfiesResult::Fresh { .. }) ) { // Then we're done! Though we might need to update the receipt. if *tool_receipt.options() != options { installed_tools.add_tool_receipt( package_name, tool_receipt.clone().with_options(options), )?; } writeln!( printer.stderr(), "`{}` is already installed", requirement.cyan() )?; return Ok(ExitStatus::Success); } } } } // Create a `RequirementsSpecification` from the resolved requirements, to avoid re-resolving. let spec = RequirementsSpecification { requirements: requirements .iter() .cloned() .map(UnresolvedRequirementSpecification::from) .collect(), constraints: constraints .iter() .cloned() .chain(latest.into_iter()) .map(NameRequirementSpecification::from) .collect(), overrides: overrides .iter() .cloned() .map(UnresolvedRequirementSpecification::from) .collect(), ..spec }; // TODO(zanieb): Build the environment in the cache directory then copy into the tool directory. // This lets us confirm the environment is valid before removing an existing install. However, // entrypoints always contain an absolute path to the relevant Python interpreter, which would // be invalidated by moving the environment. let environment = if let Some(environment) = existing_environment { let environment = match update_environment( environment.into_environment(), spec, Modifications::Exact, python_platform.as_ref(), Constraints::from_requirements(build_constraints.iter().cloned()), ExtraBuildRequires::default(), &settings, &client_builder, &state, Box::new(DefaultResolveLogger), Box::new(DefaultInstallLogger), installer_metadata, concurrency, &cache, workspace_cache, DryRun::Disabled, printer, preview, ) .await { Ok(update) => update.into_environment(), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), }; // At this point, we updated the existing environment, so we should remove any of its // existing executables. if let Some(existing_receipt) = existing_tool_receipt { remove_entrypoints(&existing_receipt); } environment } else { let spec = EnvironmentSpecification::from(spec); // If we're creating a new environment, ensure that we can resolve the requirements prior // to removing any existing tools. let resolution = resolve_environment( spec.clone(), &interpreter, python_platform.as_ref(), Constraints::from_requirements(build_constraints.iter().cloned()), &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, &cache, printer, preview, ) .await; // If the resolution failed, retry with the inferred `requires-python` constraint. let (resolution, interpreter) = match resolution { Ok(resolution) => (resolution, interpreter), Err(err) => match err { ProjectError::Operation(err) => { // If the resolution failed due to the discovered interpreter not satisfying the // `requires-python` constraint, we can try to refine the interpreter. // // For example, if we discovered a Python 3.8 interpreter on the user's machine, // but the tool requires Python 3.10 or later, we can try to download a // Python 3.10 interpreter and re-resolve. let Some(interpreter) = refine_interpreter( &interpreter, python_request.as_ref(), &err, &client_builder, &reporter, &install_mirrors, python_preference, python_downloads, &cache, preview, ) .await .ok() .flatten() else { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); }; debug!( "Re-resolving with Python {} (`{}`)", interpreter.python_version(), interpreter.sys_executable().display() ); match resolve_environment( spec, &interpreter, python_platform.as_ref(), Constraints::from_requirements(build_constraints.iter().cloned()), &settings.resolver, &client_builder, &state, Box::new(DefaultResolveLogger), concurrency, &cache, printer, preview, ) .await { Ok(resolution) => (resolution, interpreter), Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } } err => return Err(err.into()), }, }; let environment = installed_tools.create_environment(package_name, interpreter, preview)?; // At this point, we removed any existing environment, so we should remove any of its // executables. if let Some(existing_receipt) = existing_tool_receipt { remove_entrypoints(&existing_receipt); } // Sync the environment with the resolved requirements. match sync_environment( environment, &resolution.into(), Modifications::Exact, Constraints::from_requirements(build_constraints.iter().cloned()), (&settings).into(), &client_builder, &state, Box::new(DefaultInstallLogger), installer_metadata, concurrency, &cache, printer, preview, ) .await .inspect_err(|_| { // If we failed to sync, remove the newly created environment. debug!("Failed to sync environment; removing `{}`", package_name); let _ = installed_tools.remove_environment(package_name); }) { Ok(environment) => environment, Err(ProjectError::Operation(err)) => { return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(err) => return Err(err.into()), } }; finalize_tool_install( &environment, package_name, entrypoints, &installed_tools, &options, force || invalid_tool_receipt, python_request, requirements, constraints, overrides, build_constraints, printer, )?; Ok(ExitStatus::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/src/commands/tool/upgrade.rs
crates/uv/src/commands/tool/upgrade.rs
use anyhow::Result; use itertools::Itertools; use owo_colors::{AnsiColors, OwoColorize}; use std::collections::BTreeMap; use std::fmt::Write; use std::str::FromStr; use tracing::{debug, trace}; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_configuration::{Concurrency, Constraints, DryRun, TargetTriple}; use uv_distribution_types::{ExtraBuildRequires, Requirement, RequirementSource}; use uv_fs::CWD; use uv_normalize::PackageName; use uv_pep440::{Operator, Version}; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, Interpreter, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest, }; use uv_requirements::RequirementsSpecification; use uv_settings::{Combine, PythonInstallMirrors, ResolverInstallerOptions, ToolOptions}; use uv_tool::{InstalledTools, Tool}; use uv_warnings::write_error_chain; use uv_workspace::WorkspaceCache; use crate::commands::pip::loggers::{ DefaultInstallLogger, SummaryResolveLogger, UpgradeInstallLogger, }; use crate::commands::pip::operations::Modifications; use crate::commands::project::{ EnvironmentUpdate, PlatformState, resolve_environment, sync_environment, update_environment, }; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::tool::common::remove_entrypoints; use crate::commands::{ExitStatus, conjunction, tool::common::finalize_tool_install}; use crate::printer::Printer; use crate::settings::ResolverInstallerSettings; /// Upgrade a tool. pub(crate) async fn upgrade( names: Vec<String>, python: Option<String>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, args: ResolverInstallerOptions, filesystem: ResolverInstallerOptions, client_builder: BaseClientBuilder<'_>, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<ExitStatus> { let installed_tools = InstalledTools::from_settings()?.init()?; let _lock = installed_tools.lock().await?; // Collect the tools to upgrade, along with any constraints. let names: BTreeMap<PackageName, Vec<Requirement>> = { if names.is_empty() { installed_tools .tools() .unwrap_or_default() .into_iter() .map(|(name, _)| (name, Vec::new())) .collect() } else { let mut map = BTreeMap::new(); for name in names { let requirement = Requirement::from(uv_pep508::Requirement::parse(&name, &*CWD)?); map.entry(requirement.name.clone()) .or_insert_with(Vec::new) .push(requirement); } map } }; if names.is_empty() { writeln!(printer.stderr(), "Nothing to upgrade")?; return Ok(ExitStatus::Success); } let reporter = PythonDownloadReporter::single(printer); let python_request = python.as_deref().map(PythonRequest::parse); let interpreter = if python_request.is_some() { Some( PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::OnlySystem, python_preference, python_downloads, &client_builder, cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(), ) } else { None }; // Determine whether we applied any upgrades. let mut did_upgrade_tool = vec![]; // Determine whether we applied any upgrades. let mut did_upgrade_environment = vec![]; // Constraints that caused upgrades to be skipped or altered. let mut collected_constraints: Vec<(PackageName, UpgradeConstraint)> = Vec::new(); let mut errors = Vec::new(); for (name, constraints) in &names { debug!("Upgrading tool: `{name}`"); let result = Box::pin(upgrade_tool( name, constraints, interpreter.as_ref(), python_platform.as_ref(), printer, &installed_tools, &args, &client_builder, cache, &filesystem, installer_metadata, concurrency, preview, )) .await; match result { Ok(report) => { match report.outcome { UpgradeOutcome::UpgradeEnvironment => { did_upgrade_environment.push(name); } UpgradeOutcome::UpgradeTool | UpgradeOutcome::UpgradeDependencies => { did_upgrade_tool.push(name); } UpgradeOutcome::NoOp => { debug!("Upgrading `{name}` was a no-op"); } } if let Some(constraint) = report.constraint.clone() { collected_constraints.push((name.clone(), constraint)); } } Err(err) => { errors.push((name, err)); } } } if !errors.is_empty() { for (name, err) in errors .into_iter() .sorted_unstable_by(|(name_a, _), (name_b, _)| name_a.cmp(name_b)) { trace!("Error trace: {err:?}"); write_error_chain( err.context(format!("Failed to upgrade {}", name.green())) .as_ref(), printer.stderr(), "error", AnsiColors::Red, )?; } return Ok(ExitStatus::Failure); } if did_upgrade_tool.is_empty() && did_upgrade_environment.is_empty() { writeln!(printer.stderr(), "Nothing to upgrade")?; } if let Some(python_request) = python_request { if !did_upgrade_environment.is_empty() { let tools = did_upgrade_environment .iter() .map(|name| format!("`{}`", name.cyan())) .collect::<Vec<_>>(); let s = if tools.len() > 1 { "s" } else { "" }; writeln!( printer.stderr(), "Upgraded tool environment{s} for {} to {}", conjunction(tools), python_request.cyan(), )?; } } if !collected_constraints.is_empty() { writeln!(printer.stderr())?; } for (name, constraint) in collected_constraints { constraint.print(&name, printer)?; } Ok(ExitStatus::Success) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum UpgradeOutcome { /// The tool itself was upgraded. UpgradeTool, /// The tool's dependencies were upgraded, but the tool itself was unchanged. UpgradeDependencies, /// The tool's environment was upgraded. UpgradeEnvironment, /// The tool was already up-to-date. NoOp, } #[derive(Debug, Clone, PartialEq, Eq)] enum UpgradeConstraint { /// The tool remains pinned to an exact version, so an upgrade was skipped. PinnedVersion { version: Version }, } impl UpgradeConstraint { fn print(&self, name: &PackageName, printer: Printer) -> Result<()> { match self { Self::PinnedVersion { version } => { let name = name.to_string(); let reinstall_command = format!("uv tool install {name}@latest"); writeln!( printer.stderr(), "hint: `{}` is pinned to `{}` (installed with an exact version pin); reinstall with `{}` to upgrade to a new version.", name.cyan(), version.to_string().magenta(), reinstall_command.green(), )?; } } Ok(()) } } #[derive(Debug, Clone, PartialEq, Eq)] struct UpgradeReport { outcome: UpgradeOutcome, constraint: Option<UpgradeConstraint>, } /// Upgrade a specific tool. async fn upgrade_tool( name: &PackageName, constraints: &[Requirement], interpreter: Option<&Interpreter>, python_platform: Option<&TargetTriple>, printer: Printer, installed_tools: &InstalledTools, args: &ResolverInstallerOptions, client_builder: &BaseClientBuilder<'_>, cache: &Cache, filesystem: &ResolverInstallerOptions, installer_metadata: bool, concurrency: Concurrency, preview: Preview, ) -> Result<UpgradeReport> { // Ensure the tool is installed. let existing_tool_receipt = match installed_tools.get_tool_receipt(name) { Ok(Some(receipt)) => receipt, Ok(None) => { let install_command = format!("uv tool install {name}"); return Err(anyhow::anyhow!( "`{}` is not installed; run `{}` to install", name.cyan(), install_command.green() )); } Err(_) => { let install_command = format!("uv tool install --force {name}"); return Err(anyhow::anyhow!( "`{}` is missing a valid receipt; run `{}` to reinstall", name.cyan(), install_command.green() )); } }; let environment = match installed_tools.get_environment(name, cache) { Ok(Some(environment)) => environment, Ok(None) => { let install_command = format!("uv tool install {name}"); return Err(anyhow::anyhow!( "`{}` is not installed; run `{}` to install", name.cyan(), install_command.green() )); } Err(_) => { let install_command = format!("uv tool install --force {name}"); return Err(anyhow::anyhow!( "`{}` is missing a valid environment; run `{}` to reinstall", name.cyan(), install_command.green() )); } }; // Resolve the appropriate settings, preferring: CLI > receipt > user. let options = args.clone().combine( ResolverInstallerOptions::from(existing_tool_receipt.options().clone()) .combine(filesystem.clone()), ); let settings = ResolverInstallerSettings::from(options.clone()); let build_constraints = Constraints::from_requirements(existing_tool_receipt.build_constraints().iter().cloned()); // Resolve the requirements. let spec = RequirementsSpecification::from_overrides( existing_tool_receipt.requirements().to_vec(), existing_tool_receipt .constraints() .iter() .chain(constraints) .cloned() .collect(), existing_tool_receipt.overrides().to_vec(), ); // Initialize any shared state. let state = PlatformState::default(); let workspace_cache = WorkspaceCache::default(); // Check if we need to create a new environment — if so, resolve it first, then // install the requested tool let (environment, outcome) = if let Some(interpreter) = interpreter.filter(|interpreter| !environment.environment().uses(interpreter)) { // If we're using a new interpreter, re-create the environment for each tool. let resolution = resolve_environment( spec.into(), interpreter, python_platform, build_constraints.clone(), &settings.resolver, client_builder, &state, Box::new(SummaryResolveLogger), concurrency, cache, printer, preview, ) .await?; let environment = installed_tools.create_environment(name, interpreter.clone(), preview)?; let environment = sync_environment( environment, &resolution.into(), Modifications::Exact, build_constraints, (&settings).into(), client_builder, &state, Box::new(DefaultInstallLogger), installer_metadata, concurrency, cache, printer, preview, ) .await?; (environment, UpgradeOutcome::UpgradeEnvironment) } else { // Otherwise, upgrade the existing environment. // TODO(zanieb): Build the environment in the cache directory then copy into the tool // directory. let EnvironmentUpdate { environment, changelog, } = update_environment( environment.into_environment(), spec, Modifications::Exact, python_platform, build_constraints, ExtraBuildRequires::default(), &settings, client_builder, &state, Box::new(SummaryResolveLogger), Box::new(UpgradeInstallLogger::new(name.clone())), installer_metadata, concurrency, cache, workspace_cache, DryRun::Disabled, printer, preview, ) .await?; let outcome = if changelog.includes(name) { UpgradeOutcome::UpgradeTool } else if changelog.is_empty() { UpgradeOutcome::NoOp } else { UpgradeOutcome::UpgradeDependencies }; (environment, outcome) }; if matches!( outcome, UpgradeOutcome::UpgradeEnvironment | UpgradeOutcome::UpgradeTool ) { // At this point, we updated the existing environment, so we should remove any of its // existing executables. remove_entrypoints(&existing_tool_receipt); let entrypoints: Vec<_> = existing_tool_receipt .entrypoints() .iter() .filter_map(|entry| PackageName::from_str(entry.from.as_ref()?).ok()) .collect(); // If we modified the target tool, reinstall the entrypoints. finalize_tool_install( &environment, name, &entrypoints, installed_tools, &ToolOptions::from(options), true, existing_tool_receipt.python().to_owned(), existing_tool_receipt.requirements().to_vec(), existing_tool_receipt.constraints().to_vec(), existing_tool_receipt.overrides().to_vec(), existing_tool_receipt.build_constraints().to_vec(), printer, )?; } let constraint = match &outcome { UpgradeOutcome::UpgradeDependencies | UpgradeOutcome::NoOp => { pinned_requirement_version(&existing_tool_receipt, name) .map(|version| UpgradeConstraint::PinnedVersion { version }) } UpgradeOutcome::UpgradeTool | UpgradeOutcome::UpgradeEnvironment => None, }; Ok(UpgradeReport { outcome, constraint, }) } fn pinned_requirement_version(tool: &Tool, name: &PackageName) -> Option<Version> { pinned_version_from(tool.requirements(), name) .or_else(|| pinned_version_from(tool.constraints(), name)) } fn pinned_version_from(requirements: &[Requirement], name: &PackageName) -> Option<Version> { requirements .iter() .filter(|requirement| requirement.name == *name) .find_map(|requirement| match &requirement.source { RequirementSource::Registry { specifier, .. } => { specifier .iter() .find_map(|specifier| match specifier.operator() { Operator::Equal | Operator::ExactEqual => Some(specifier.version().clone()), _ => None, }) } _ => 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/src/commands/tool/update_shell.rs
crates/uv/src/commands/tool/update_shell.rs
#![cfg_attr(windows, allow(unreachable_code))] use std::fmt::Write; use anyhow::Result; use owo_colors::OwoColorize; use tokio::io::AsyncWriteExt; use tracing::debug; use uv_fs::Simplified; use uv_shell::Shell; use uv_tool::tool_executable_dir; use crate::commands::ExitStatus; use crate::printer::Printer; /// Ensure that the executable directory is in PATH. pub(crate) async fn update_shell(printer: Printer) -> Result<ExitStatus> { let executable_directory = tool_executable_dir()?; debug!( "Ensuring that the executable directory is in PATH: {}", executable_directory.simplified_display() ); #[cfg(windows)] { if uv_shell::windows::prepend_path(&executable_directory)? { writeln!( printer.stderr(), "Updated PATH to include executable directory {}", executable_directory.simplified_display().cyan() )?; writeln!(printer.stderr(), "Restart your shell to apply changes")?; } else { writeln!( printer.stderr(), "Executable directory {} is already in PATH", executable_directory.simplified_display().cyan() )?; } return Ok(ExitStatus::Success); } if Shell::contains_path(&executable_directory) { writeln!( printer.stderr(), "Executable directory {} is already in PATH", executable_directory.simplified_display().cyan() )?; return Ok(ExitStatus::Success); } // Determine the current shell. let Some(shell) = Shell::from_env() else { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the current shell could not be determined", executable_directory.simplified_display().cyan() )); }; // Look up the configuration files (e.g., `.bashrc`, `.zshrc`) for the shell. let files = shell.configuration_files(); if files.is_empty() { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but updating {shell} is currently unsupported", executable_directory.simplified_display().cyan() )); } // Prepare the command (e.g., `export PATH="$HOME/.cargo/bin:$PATH"`). let Some(command) = shell.prepend_path(&executable_directory) else { return Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the necessary command to update {shell} could not be determined", executable_directory.simplified_display().cyan() )); }; // Update each file, as necessary. let mut updated = false; for file in files { // Search for the command in the file, to avoid redundant updates. match fs_err::tokio::read_to_string(&file).await { Ok(contents) => { if contents .lines() .map(str::trim) .filter(|line| !line.starts_with('#')) .any(|line| line.contains(&command)) { debug!( "Skipping already-updated configuration file: {}", file.simplified_display() ); continue; } // Append the command to the file. fs_err::tokio::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&file) .await? .write_all(format!("{contents}\n# uv\n{command}\n").as_bytes()) .await?; writeln!( printer.stderr(), "Updated configuration file: {}", file.simplified_display().cyan() )?; updated = true; } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { // Ensure that the directory containing the file exists. if let Some(parent) = file.parent() { fs_err::tokio::create_dir_all(&parent).await?; } // Append the command to the file. fs_err::tokio::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&file) .await? .write_all(format!("# uv\n{command}\n").as_bytes()) .await?; writeln!( printer.stderr(), "Created configuration file: {}", file.simplified_display().cyan() )?; updated = true; } Err(err) => { return Err(err.into()); } } } if updated { writeln!(printer.stderr(), "Restart your shell to apply changes")?; Ok(ExitStatus::Success) } else { Err(anyhow::anyhow!( "The executable directory {} is not in PATH, but the {shell} configuration files are already up-to-date", executable_directory.simplified_display().cyan() )) } }
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/src/commands/tool/mod.rs
crates/uv/src/commands/tool/mod.rs
use std::str::FromStr; use tracing::debug; use uv_normalize::{ExtraName, PackageName}; use uv_pep440::Version; use uv_python::PythonRequest; mod common; pub(crate) mod dir; pub(crate) mod install; pub(crate) mod list; pub(crate) mod run; pub(crate) mod uninstall; pub(crate) mod update_shell; pub(crate) mod upgrade; /// A request to run or install a tool (e.g., `uvx ruff@latest`). #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum ToolRequest<'a> { // Running the interpreter directly e.g. `uvx python` or `uvx pypy@3.8` Python { /// The executable name (e.g., `bash`), if the interpreter was given via --from. executable: Option<&'a str>, // The interpreter to install or run (e.g., `python@3.8` or `pypy311`. request: PythonRequest, }, // Running a Python package Package { /// The executable name (e.g., `ruff`), if the target was given via --from. executable: Option<&'a str>, /// The target to install or run (e.g., `ruff@latest` or `ruff==0.6.0`). target: Target<'a>, }, } impl<'a> ToolRequest<'a> { /// Parse a tool request into an executable name and a target. pub(crate) fn parse(command: &'a str, from: Option<&'a str>) -> anyhow::Result<Self> { // If --from is used, the command could be an arbitrary binary in the PATH (e.g. `bash`), // and we don't try to parse it. let (component_to_parse, executable) = match from { Some(from) => (from, Some(command)), None => (command, None), }; // First try parsing the command as a Python interpreter, like `python`, `python39`, or // `pypy@39`. `pythonw` is also allowed on Windows. This overlaps with how `--python` flag // values are parsed, but see `PythonRequest::parse` vs `PythonRequest::try_from_tool_name` // for the differences. if let Some(python_request) = PythonRequest::try_from_tool_name(component_to_parse)? { Ok(Self::Python { request: python_request, executable, }) } else { // Otherwise the command is a Python package, like `ruff` or `ruff@0.6.0`. Ok(Self::Package { target: Target::parse(component_to_parse), executable, }) } } /// Returns `true` if the target is `latest`. pub(crate) fn is_latest(&self) -> bool { matches!( self, Self::Package { target: Target::Latest(..), .. } ) } } #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Target<'a> { /// e.g., `ruff` Unspecified(&'a str), /// e.g., `ruff[extra]@0.6.0` Version(&'a str, PackageName, Box<[ExtraName]>, Version), /// e.g., `ruff[extra]@latest` Latest(&'a str, PackageName, Box<[ExtraName]>), } impl<'a> Target<'a> { /// Parse a target into a command name and a requirement. pub(crate) fn parse(target: &'a str) -> Self { // e.g. `ruff`, no special handling let Some((name, version)) = target.split_once('@') else { return Self::Unspecified(target); }; // e.g. `ruff@`, warn and treat the whole thing as the command if version.is_empty() { debug!("Ignoring empty version request in command"); return Self::Unspecified(target); } // Split into name and extras (e.g., `flask[dotenv]`). let (executable, extras) = match name.split_once('[') { Some((executable, extras)) => { let Some(extras) = extras.strip_suffix(']') else { // e.g., ignore `flask[dotenv`. return Self::Unspecified(target); }; (executable, extras) } None => (name, ""), }; // e.g., ignore `git+https://github.com/astral-sh/ruff.git@main` let Ok(name) = PackageName::from_str(executable) else { debug!("Ignoring non-package name `{name}` in command"); return Self::Unspecified(target); }; // e.g., ignore `ruff[1.0.0]` or any other invalid extra. let Ok(extras) = extras .split(',') .map(str::trim) .filter(|extra| !extra.is_empty()) .map(ExtraName::from_str) .collect::<Result<Box<_>, _>>() else { debug!("Ignoring invalid extras `{extras}` in command"); return Self::Unspecified(target); }; match version { // e.g., `ruff@latest` "latest" => Self::Latest(executable, name, extras), // e.g., `ruff@0.6.0` version => { if let Ok(version) = Version::from_str(version) { Self::Version(executable, name, extras, version) } else { // e.g. `ruff@invalid`, warn and treat the whole thing as the command debug!("Ignoring invalid version request `{version}` in command"); Self::Unspecified(target) } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_target() { let target = Target::parse("flask"); let expected = Target::Unspecified("flask"); assert_eq!(target, expected); let target = Target::parse("flask@3.0.0"); let expected = Target::Version( "flask", PackageName::from_str("flask").unwrap(), Box::new([]), Version::new([3, 0, 0]), ); assert_eq!(target, expected); let target = Target::parse("flask@3.0.0"); let expected = Target::Version( "flask", PackageName::from_str("flask").unwrap(), Box::new([]), Version::new([3, 0, 0]), ); assert_eq!(target, expected); let target = Target::parse("flask@latest"); let expected = Target::Latest( "flask", PackageName::from_str("flask").unwrap(), Box::new([]), ); assert_eq!(target, expected); let target = Target::parse("flask[dotenv]@3.0.0"); let expected = Target::Version( "flask", PackageName::from_str("flask").unwrap(), Box::new([ExtraName::from_str("dotenv").unwrap()]), Version::new([3, 0, 0]), ); assert_eq!(target, expected); let target = Target::parse("flask[dotenv]@latest"); let expected = Target::Latest( "flask", PackageName::from_str("flask").unwrap(), Box::new([ExtraName::from_str("dotenv").unwrap()]), ); assert_eq!(target, expected); // Missing a closing `]`. let target = Target::parse("flask[dotenv"); let expected = Target::Unspecified("flask[dotenv"); assert_eq!(target, expected); // Too many `]`. let target = Target::parse("flask[dotenv]]"); let expected = Target::Unspecified("flask[dotenv]]"); assert_eq!(target, 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/src/commands/tool/run.rs
crates/uv/src/commands/tool/run.rs
use std::fmt::Display; use std::fmt::Write; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; use anstream::eprint; use anyhow::{Context, bail}; use console::Term; use itertools::Itertools; use owo_colors::OwoColorize; use tokio::process::Command; use tokio::sync::Semaphore; use tracing::{debug, warn}; use uv_cache::{Cache, Refresh}; use uv_cache_info::Timestamp; use uv_cli::ExternalCommand; use uv_client::{BaseClientBuilder, RegistryClientBuilder}; use uv_configuration::{Concurrency, Constraints, GitLfsSetting, TargetTriple}; use uv_distribution::LoweredExtraBuildDependencies; use uv_distribution_types::InstalledDist; use uv_distribution_types::{ IndexCapabilities, IndexUrl, Name, NameRequirementSpecification, Requirement, RequirementSource, UnresolvedRequirement, UnresolvedRequirementSpecification, }; use uv_fs::Simplified; use uv_installer::{InstallationStrategy, SatisfiesResult, SitePackages}; use uv_normalize::PackageName; use uv_pep440::{VersionSpecifier, VersionSpecifiers}; use uv_pep508::MarkerTree; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, }; use uv_requirements::{RequirementsSource, RequirementsSpecification}; use uv_settings::{PythonInstallMirrors, ResolverInstallerOptions, ToolOptions}; use uv_shell::runnable::WindowsRunnable; use uv_static::EnvVars; use uv_tool::{InstalledTools, entrypoint_paths}; use uv_warnings::warn_user; use uv_warnings::warn_user_once; use uv_workspace::WorkspaceCache; use crate::child::run_to_completion; use crate::commands::ExitStatus; use crate::commands::pip; use crate::commands::pip::latest::LatestClient; use crate::commands::pip::loggers::{ DefaultInstallLogger, DefaultResolveLogger, SummaryInstallLogger, SummaryResolveLogger, }; use crate::commands::pip::operations; use crate::commands::project::{ EnvironmentSpecification, PlatformState, ProjectError, resolve_names, }; use crate::commands::reporters::PythonDownloadReporter; use crate::commands::tool::common::{matching_packages, refine_interpreter}; use crate::commands::tool::{Target, ToolRequest}; use crate::commands::{diagnostics, project::environment::CachedEnvironment}; use crate::printer::Printer; use crate::settings::ResolverInstallerSettings; use crate::settings::ResolverSettings; /// The user-facing command used to invoke a tool run. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum ToolRunCommand { /// via the `uvx` alias Uvx, /// via `uv tool run` ToolRun, } impl Display for ToolRunCommand { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Uvx => write!(f, "uvx"), Self::ToolRun => write!(f, "uv tool run"), } } } /// Check if the given arguments contain a verbose flag (e.g., `--verbose`, `-v`, `-vv`, etc.) fn find_verbose_flag(args: &[std::ffi::OsString]) -> Option<&str> { args.iter().find_map(|arg| { let arg_str = arg.to_str()?; if arg_str == "--verbose" { Some("--verbose") } else if arg_str.starts_with("-v") && arg_str.chars().skip(1).all(|c| c == 'v') { Some(arg_str) } else { None } }) } /// Run a command. #[allow(clippy::fn_params_excessive_bools)] pub(crate) async fn run( command: Option<ExternalCommand>, from: Option<String>, with: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], build_constraints: &[RequirementsSource], show_resolution: bool, lfs: GitLfsSetting, python: Option<String>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, options: ResolverInstallerOptions, settings: ResolverInstallerSettings, client_builder: BaseClientBuilder<'_>, invocation_source: ToolRunCommand, isolated: bool, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, cache: Cache, printer: Printer, env_file: Vec<PathBuf>, no_env_file: bool, preview: Preview, ) -> anyhow::Result<ExitStatus> { /// Whether or not a path looks like a Python script based on the file extension. fn has_python_script_ext(path: &Path) -> bool { path.extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("py") || ext.eq_ignore_ascii_case("pyw")) } if settings.resolver.torch_backend.is_some() { warn_user_once!( "The `--torch-backend` option is experimental and may change without warning." ); } // Read from the `.env` file, if necessary. if !no_env_file { for env_file_path in env_file.iter().rev().map(PathBuf::as_path) { match dotenvy::from_path(env_file_path) { Err(dotenvy::Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { bail!( "No environment file found at: `{}`", env_file_path.simplified_display() ); } Err(dotenvy::Error::Io(err)) => { bail!( "Failed to read environment file `{}`: {err}", env_file_path.simplified_display() ); } Err(dotenvy::Error::LineParse(content, position)) => { warn_user!( "Failed to parse environment file `{}` at position {position}: {content}", env_file_path.simplified_display(), ); } Err(err) => { warn_user!( "Failed to parse environment file `{}`: {err}", env_file_path.simplified_display(), ); } Ok(()) => { debug!( "Read environment file at: `{}`", env_file_path.simplified_display() ); } } } } let Some(command) = command else { // When a command isn't provided, we'll show a brief help including available tools show_help(invocation_source, &cache, printer).await?; // Exit as Clap would after displaying help return Ok(ExitStatus::Error); }; let (target, args) = command.split(); let Some(target) = target else { return Err(anyhow::anyhow!("No tool command provided")); }; let Some(target) = target.to_str() else { return Err(anyhow::anyhow!( "Tool command could not be parsed as UTF-8 string. Use `--from` to specify the package name" )); }; if let Some(ref from) = from { if has_python_script_ext(Path::new(from)) { let package_name = PackageName::from_str(from)?; return Err(anyhow::anyhow!( "It looks like you provided a Python script to `--from`, which is not supported\n\n{}{} If you meant to run a command from the `{}` package, use the normalized package name instead to disambiguate, e.g., `{}`", "hint".bold().cyan(), ":".bold(), package_name.cyan(), format!( "{} --from {} {}", invocation_source, package_name.cyan(), target ) .green(), )); } } else { let target_path = Path::new(target); // If the user tries to invoke `uvx script.py`, hint them towards `uv run`. if has_python_script_ext(target_path) { return if target_path.try_exists()? { Err(anyhow::anyhow!( "It looks like you tried to run a Python script at `{}`, which is not supported by `{}`\n\n{}{} Use `{}` instead", target_path.user_display(), invocation_source, "hint".bold().cyan(), ":".bold(), format!("uv run {}", target_path.user_display()).green(), )) } else { let package_name = PackageName::from_str(target)?; Err(anyhow::anyhow!( "It looks like you provided a Python script to run, which is not supported supported by `{}`\n\n{}{} We did not find a script at the requested path. If you meant to run a command from the `{}` package, pass the normalized package name to `--from` to disambiguate, e.g., `{}`", invocation_source, "hint".bold().cyan(), ":".bold(), package_name.cyan(), format!("{invocation_source} --from {package_name} {target}").green(), )) }; } } // If the user tries to invoke `uvx run ruff`, hint them towards `uvx ruff`, but only if // the `run` package is guaranteed to come from PyPI. let (mut target, mut args) = (target, args); if from.is_none() && invocation_source == ToolRunCommand::Uvx && target == "run" && settings .resolver .index_locations .indexes() .all(|index| matches!(index.url, IndexUrl::Pypi(..))) { let term = Term::stderr(); if term.is_term() { let rest = args.iter().map(|s| s.to_string_lossy()).join(" "); let prompt = format!( "`{}` invokes the `{}` package. Did you mean `{}`?", format!("uvx run {rest}").green(), "run".cyan(), format!("uvx {rest}").green() ); let confirmation = uv_console::confirm(&prompt, &term, true)?; if confirmation { let Some((next_target, next_args)) = args.split_first() else { return Err(anyhow::anyhow!("No tool command provided")); }; let Some(next_target) = next_target.to_str() else { return Err(anyhow::anyhow!( "Tool command could not be parsed as UTF-8 string. Use `--from` to specify the package name" )); }; target = next_target; args = next_args; } } } let request = ToolRequest::parse(target, from.as_deref())?; // If the user passed, e.g., `ruff@latest`, refresh the cache. let cache = if request.is_latest() { cache.with_refresh(Refresh::All(Timestamp::now())) } else { cache }; // Get or create a compatible environment in which to execute the tool. let result = Box::pin(get_or_create_environment( &request, with, constraints, overrides, build_constraints, show_resolution, python.as_deref(), python_platform, install_mirrors, options, &settings, &client_builder, isolated, lfs, python_preference, python_downloads, installer_metadata, concurrency, &cache, printer, preview, )) .await; let explicit_from = from.is_some(); let (from, environment) = match result { Ok(resolution) => resolution, Err(ProjectError::Operation(err)) => { // If the user ran `uvx run ...`, the `run` is likely a mistake. Show a dedicated hint. if from.is_none() && invocation_source == ToolRunCommand::Uvx && target == "run" { let rest = args.iter().map(|s| s.to_string_lossy()).join(" "); return diagnostics::OperationDiagnostic::native_tls( client_builder.is_native_tls(), ) .with_hint(format!( "`{}` invokes the `{}` package. Did you mean `{}`?", format!("uvx run {rest}").green(), "run".cyan(), format!("uvx {rest}").green() )) .with_context("tool") .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } let diagnostic = diagnostics::OperationDiagnostic::native_tls(client_builder.is_native_tls()); let diagnostic = if let Some(verbose_flag) = find_verbose_flag(args) { diagnostic.with_hint(format!( "You provided `{}` to `{}`. Did you mean to provide it to `{}`? e.g., `{}`", verbose_flag.cyan(), target.cyan(), invocation_source.to_string().cyan(), format!("{invocation_source} {verbose_flag} {target}").green() )) } else { diagnostic.with_context("tool") }; return diagnostic .report(err) .map_or(Ok(ExitStatus::Failure), |err| Err(err.into())); } Err(ProjectError::Requirements(err)) => { let err = miette::Report::msg(format!("{err}")) .context("Failed to resolve `--with` requirement"); eprint!("{err:?}"); return Ok(ExitStatus::Failure); } Err(err) => return Err(err.into()), }; // TODO(zanieb): Determine the executable command via the package entry points let executable = from.executable(); let site_packages = SitePackages::from_environment(&environment)?; // Check if the provided command is not part of the executables for the `from` package, // and if it's provided by another package in the environment. let provider_hints = match &from { ToolRequirement::Python { .. } => None, ToolRequirement::Package { requirement, .. } => Some(ExecutableProviderHints::new( executable, requirement, &site_packages, invocation_source, )), }; if let Some(ref provider_hints) = provider_hints { if provider_hints.not_from_any() { if !explicit_from { // If the user didn't use `--from` and the command isn't in the environment, we're now // just invoking an arbitrary executable on the `PATH` and should exit instead. writeln!(printer.stderr(), "{provider_hints}")?; return Ok(ExitStatus::Failure); } // In the case where `--from` is used, we'll warn on failure if the command is not found // TODO(zanieb): Consider if we should require `--with` instead of `--from` in this case? // It'd be a breaking change but would make `uvx` invocations safer. } else if provider_hints.not_from_expected() { // However, if the user used `--from`, we shouldn't fail because they requested that the // package and executable be different. We'll warn if the executable comes from another // package though, because that could be confusing warn_user_once!("{provider_hints}"); } } // Construct the command let mut process = if cfg!(windows) { WindowsRunnable::from_script_path(environment.scripts(), executable.as_ref()).into() } else { Command::new(executable) }; process.args(args); // Construct the `PATH` environment variable. let new_path = std::env::join_paths( std::iter::once(environment.scripts().to_path_buf()).chain( std::env::var_os(EnvVars::PATH) .as_ref() .iter() .flat_map(std::env::split_paths), ), ) .context("Failed to build new PATH variable")?; process.env(EnvVars::PATH, new_path); // Spawn and wait for completion // Standard input, output, and error streams are all inherited let space = if args.is_empty() { "" } else { " " }; debug!( "Running `{}{space}{}`", executable, args.iter().map(|arg| arg.to_string_lossy()).join(" ") ); let handle = match process.spawn() { Ok(handle) => Ok(handle), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { if let Some(ref provider_hints) = provider_hints { if provider_hints.not_from_any() && explicit_from { // We deferred this warning earlier, because `--from` was used and the command // could have come from the `PATH`. Display a more helpful message instead of the // OS error. writeln!(printer.stderr(), "{provider_hints}")?; return Ok(ExitStatus::Failure); } } Err(err) } Err(err) => Err(err), } .with_context(|| format!("Failed to spawn: `{executable}`"))?; run_to_completion(handle).await } /// Return the entry points for the specified package. fn get_entrypoints( from: &PackageName, site_packages: &SitePackages, ) -> anyhow::Result<Vec<(String, PathBuf)>> { let installed = site_packages.get_packages(from); let Some(installed_dist) = installed.first().copied() else { bail!("Expected at least one requirement") }; Ok(entrypoint_paths( site_packages, installed_dist.name(), installed_dist.version(), )?) } /// Display a list of tools that provide the executable. /// /// If there is no package providing the executable, we will display a message to how to install a package. async fn show_help( invocation_source: ToolRunCommand, cache: &Cache, printer: Printer, ) -> anyhow::Result<()> { let help = format!( "See `{}` for more information.", format!("{invocation_source} --help").bold() ); writeln!( printer.stdout(), "Provide a command to run with `{}`.\n", format!("{invocation_source} <command>").bold() )?; let installed_tools = InstalledTools::from_settings()?; let _lock = match installed_tools.lock().await { Ok(lock) => lock, Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) => { writeln!(printer.stdout(), "{help}")?; return Ok(()); } Err(err) => return Err(err.into()), }; let tools = installed_tools .tools()? .into_iter() // Skip invalid tools .filter_map(|(name, tool)| { tool.ok().and_then(|_| { installed_tools .get_environment(&name, cache) .ok() .flatten() .and_then(|tool_env| tool_env.version().ok()) .map(|version| (name, version)) }) }) .sorted_by(|(name1, ..), (name2, ..)| name1.cmp(name2)) .collect::<Vec<_>>(); // No tools installed or they're all malformed if tools.is_empty() { writeln!(printer.stdout(), "{help}")?; return Ok(()); } // Display the tools writeln!(printer.stdout(), "The following tools are installed:\n")?; for (name, version) in tools { writeln!( printer.stdout(), "- {} v{version}", format!("{name}").bold() )?; } writeln!(printer.stdout(), "\n{help}")?; Ok(()) } /// A set of hints about the packages that provide an executable. #[derive(Debug)] struct ExecutableProviderHints<'a> { /// The requested executable for the command executable: &'a str, /// The package from which the executable is expected to come from from: &'a Requirement, /// The packages in the [`PythonEnvironment`] the command will run in site_packages: &'a SitePackages, /// The packages with matching executable names packages: Vec<InstalledDist>, /// The source of the invocation, for suggestions to the user invocation_source: ToolRunCommand, } impl<'a> ExecutableProviderHints<'a> { fn new( executable: &'a str, from: &'a Requirement, site_packages: &'a SitePackages, invocation_source: ToolRunCommand, ) -> Self { let packages = matching_packages(executable, site_packages); ExecutableProviderHints { executable, from, site_packages, packages, invocation_source, } } /// If the executable is not provided by the expected package. fn not_from_expected(&self) -> bool { !self .packages .iter() .any(|package| package.name() == &self.from.name) } /// If the executable is not provided by any package. fn not_from_any(&self) -> bool { self.packages.is_empty() } } impl std::fmt::Display for ExecutableProviderHints<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { executable, from, site_packages, packages, invocation_source, } = self; match packages.as_slice() { [] => { let entrypoints = match get_entrypoints(&from.name, site_packages) { Ok(entrypoints) => entrypoints, Err(err) => { warn!("Failed to get entrypoints for `{from}`: {err}"); return Ok(()); } }; if entrypoints.is_empty() { write!( f, "Package `{}` does not provide any executables.", from.name.red() )?; return Ok(()); } writeln!( f, "An executable named `{}` is not provided by package `{}`.", executable.cyan(), from.name.cyan(), )?; writeln!(f, "The following executables are available:")?; for (name, _) in &entrypoints { writeln!(f, "- {}", name.cyan())?; } let name = match entrypoints.as_slice() { [entrypoint] => entrypoint.0.as_str(), _ => "<EXECUTABLE-NAME>", }; // If the user didn't use `--from`, suggest it if *executable == from.name.as_str() { let suggested_command = format!("{} --from {} {name}", invocation_source, from.name); writeln!(f, "\nUse `{}` instead.", suggested_command.green().bold())?; } } [package] if package.name() == &from.name => { write!( f, "An executable named `{}` is provided by package `{}`", executable.cyan(), from.name.cyan(), )?; } [package] => { let suggested_command = format!( "{invocation_source} --from {} {}", package.name(), executable ); write!( f, "An executable named `{}` is not provided by package `{}` but is available via the dependency `{}`. Consider using `{}` instead.", executable.cyan(), from.name.cyan(), package.name().cyan(), suggested_command.green() )?; } packages => { let provided_by = packages .iter() .map(uv_distribution_types::Name::name) .map(|name| format!("- {}", name.cyan())) .join("\n"); if self.not_from_expected() { let suggested_command = format!("{invocation_source} --from PKG {executable}"); write!( f, "An executable named `{}` is not provided by package `{}` but is available via the following dependencies:\n- {}\nConsider using `{}` instead.", executable.cyan(), from.name.cyan(), provided_by, suggested_command.green(), )?; } else { write!( f, "An executable named `{}` is provided by package `{}` but is also available via the following dependencies:\n- {}\nUnexpected behavior may occur.", executable.cyan(), from.name.cyan(), provided_by, )?; } } } Ok(()) } } // Clippy isn't happy about the difference in size between these variants, but // [`ToolRequirement::Package`] is the more common case and it seems annoying to box it. #[derive(Debug)] #[allow(clippy::large_enum_variant)] pub(crate) enum ToolRequirement { Python { executable: String, }, Package { executable: String, requirement: Requirement, }, } impl ToolRequirement { fn executable(&self) -> &str { match self { Self::Python { executable, .. } => executable, Self::Package { executable, .. } => executable, } } } impl std::fmt::Display for ToolRequirement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Python { .. } => write!(f, "python"), Self::Package { requirement, .. } => write!(f, "{requirement}"), } } } /// Get or create a [`PythonEnvironment`] in which to run the specified tools. /// /// If the target tool is already installed in a compatible environment, returns that /// [`PythonEnvironment`]. Otherwise, gets or creates a [`CachedEnvironment`]. #[allow(clippy::fn_params_excessive_bools)] async fn get_or_create_environment( request: &ToolRequest<'_>, with: &[RequirementsSource], constraints: &[RequirementsSource], overrides: &[RequirementsSource], build_constraints: &[RequirementsSource], show_resolution: bool, python: Option<&str>, python_platform: Option<TargetTriple>, install_mirrors: PythonInstallMirrors, options: ResolverInstallerOptions, settings: &ResolverInstallerSettings, client_builder: &BaseClientBuilder<'_>, isolated: bool, lfs: GitLfsSetting, python_preference: PythonPreference, python_downloads: PythonDownloads, installer_metadata: bool, concurrency: Concurrency, cache: &Cache, printer: Printer, preview: Preview, ) -> Result<(ToolRequirement, PythonEnvironment), ProjectError> { let reporter = PythonDownloadReporter::single(printer); // Figure out what Python we're targeting, either explicitly like `uvx python@3`, or via the // -p/--python flag. let python_request = match request { ToolRequest::Python { request: tool_python_request, .. } => { match python { None => Some(tool_python_request.clone()), // The user is both invoking a python interpreter directly and also supplying the // -p/--python flag. Cases like `uvx -p pypy python` are allowed, for two reasons: // 1) Previously this was the only way to invoke e.g. PyPy via `uvx`, and it's nice // to remain compatible with that. 2) A script might define an alias like `uvx // --python $MY_PYTHON ...`, and it's nice to be able to run the interpreter // directly while sticking to that alias. // // However, we want to error out if we see conflicting or redundant versions like // `uvx -p python38 python39`. // // Note that a command like `uvx default` doesn't bring us here. ToolRequest::parse // returns ToolRequest::Package rather than ToolRequest::Python in that case. See // PythonRequest::try_from_tool_name. Some(python_flag) => { if tool_python_request != &PythonRequest::Default { return Err(anyhow::anyhow!( "Received multiple Python version requests: `{}` and `{}`", python_flag.to_string().cyan(), tool_python_request.to_canonical_string().cyan() ) .into()); } Some(PythonRequest::parse(python_flag)) } } } ToolRequest::Package { .. } => python.map(PythonRequest::parse), }; // Discover an interpreter. let interpreter = PythonInstallation::find_or_download( python_request.as_ref(), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(&reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); // Initialize any shared state. let state = PlatformState::default(); let workspace_cache = WorkspaceCache::default(); let from = match request { ToolRequest::Python { executable: request_executable, .. } => ToolRequirement::Python { executable: request_executable.unwrap_or("python").to_string(), }, ToolRequest::Package { executable: request_executable, target, } => { let (executable, requirement) = match target { // Ex) `ruff>=0.6.0` Target::Unspecified(requirement) => { let spec = RequirementsSpecification::parse_package(requirement)?; // Extract the verbatim executable name, if possible. let name = match &spec.requirement { UnresolvedRequirement::Named(..) => { // Identify the package name from the PEP 508 specifier. // // For example, given `ruff>=0.6.0`, extract `ruff`, to use as the executable name. let content = requirement.trim(); let index = content .find(|c| !matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.')) .unwrap_or(content.len()); Some(&content[..index]) } UnresolvedRequirement::Unnamed(..) => None, }; let requirement = resolve_names( vec![spec], &interpreter, settings, client_builder, &state, concurrency, cache, &workspace_cache, printer, preview, lfs, ) .await? .pop() .unwrap(); // Prefer, in order: // 1. The verbatim executable provided by the user, independent of the requirement (as in: `uvx --from package executable`). // 2. The verbatim executable provided by the user as a named requirement (as in: `uvx change_wheel_version`). // 3. The resolved package name (as in: `uvx git+https://github.com/pallets/flask`). let executable = request_executable .map(ToString::to_string) .or_else(|| name.map(ToString::to_string)) .unwrap_or_else(|| requirement.name.to_string()); (executable, requirement) } // Ex) `ruff@0.6.0` Target::Version(executable, name, extras, version) => {
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv/src/commands/tool/dir.rs
crates/uv/src/commands/tool/dir.rs
use std::fmt::Write; use anyhow::Context; use owo_colors::OwoColorize; use uv_fs::Simplified; use uv_preview::Preview; use uv_tool::{InstalledTools, tool_executable_dir}; use crate::printer::Printer; /// Show the tool directory. pub(crate) fn dir(bin: bool, _preview: Preview, printer: Printer) -> anyhow::Result<()> { if bin { let executable_directory = tool_executable_dir()?; writeln!( printer.stdout(), "{}", executable_directory.simplified_display().cyan() )?; } else { let installed_tools = InstalledTools::from_settings().context("Failed to initialize tools settings")?; writeln!( printer.stdout(), "{}", installed_tools.root().simplified_display().cyan() )?; } 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/src/commands/tool/common.rs
crates/uv/src/commands/tool/common.rs
use anyhow::{Context, bail}; use itertools::Itertools; use owo_colors::OwoColorize; use std::{ collections::{BTreeSet, Bound}, ffi::OsString, fmt::Write, path::Path, }; use tracing::{debug, warn}; use uv_cache::Cache; use uv_client::BaseClientBuilder; use uv_distribution_types::Requirement; use uv_distribution_types::{InstalledDist, Name}; use uv_fs::Simplified; #[cfg(unix)] use uv_fs::replace_symlink; use uv_installer::SitePackages; use uv_normalize::PackageName; use uv_pep440::{Version, VersionSpecifier, VersionSpecifiers}; use uv_preview::Preview; use uv_python::{ EnvironmentPreference, Interpreter, PythonDownloads, PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, PythonVariant, VersionRequest, }; use uv_settings::{PythonInstallMirrors, ToolOptions}; use uv_shell::Shell; use uv_tool::{InstalledTools, Tool, ToolEntrypoint, entrypoint_paths}; use uv_warnings::warn_user_once; use crate::commands::pip; use crate::commands::project::ProjectError; use crate::commands::reporters::PythonDownloadReporter; use crate::printer::Printer; /// Return all packages which contain an executable with the given name. pub(super) fn matching_packages(name: &str, site_packages: &SitePackages) -> Vec<InstalledDist> { site_packages .iter() .filter_map(|package| { entrypoint_paths(site_packages, package.name(), package.version()) .ok() .and_then(|entrypoints| { entrypoints .iter() .any(|entrypoint| { entrypoint .0 .strip_suffix(std::env::consts::EXE_SUFFIX) .is_some_and(|stripped| stripped == name) }) .then(|| package.clone()) }) }) .collect() } /// Remove any entrypoints attached to the [`Tool`]. pub(crate) fn remove_entrypoints(tool: &Tool) { for executable in tool .entrypoints() .iter() .map(|entrypoint| &entrypoint.install_path) { debug!("Removing executable: `{}`", executable.simplified_display()); if let Err(err) = fs_err::remove_file(executable) { warn!( "Failed to remove executable: `{}`: {err}", executable.simplified_display() ); } } } /// Given a no-solution error and the [`Interpreter`] that was used during the solve, attempt to /// discover an alternate [`Interpreter`] that satisfies the `requires-python` constraint. pub(crate) async fn refine_interpreter( interpreter: &Interpreter, python_request: Option<&PythonRequest>, err: &pip::operations::Error, client_builder: &BaseClientBuilder<'_>, reporter: &PythonDownloadReporter, install_mirrors: &PythonInstallMirrors, python_preference: PythonPreference, python_downloads: PythonDownloads, cache: &Cache, preview: Preview, ) -> anyhow::Result<Option<Interpreter>, ProjectError> { let pip::operations::Error::Resolve(uv_resolver::ResolveError::NoSolution(no_solution_err)) = err else { return Ok(None); }; // Infer the `requires-python` constraint from the error. let requires_python = no_solution_err.find_requires_python(); // If the existing interpreter already satisfies the `requires-python` constraint, we don't need // to refine it. We'd expect to fail again anyway. if requires_python.contains(interpreter.python_version()) { return Ok(None); } // We want an interpreter that's as close to the required version as possible. If we choose the // "latest" Python, we risk choosing a version that lacks wheels for the tool's requirements // (assuming those requirements don't publish source distributions). // // TODO(charlie): Solve for the Python version iteratively (or even, within the resolver // itself). The current strategy can also fail if the tool's requirements have greater // `requires-python` constraints, and we didn't see them in the initial solve. It can also fail // if the tool's requirements don't publish wheels for this interpreter version, though that's // rarer. let lower_bound = match requires_python.as_ref() { Bound::Included(version) => VersionSpecifier::greater_than_equal_version(version.clone()), Bound::Excluded(version) => VersionSpecifier::greater_than_version(version.clone()), Bound::Unbounded => unreachable!("`requires-python` should never be unbounded"), }; let upper_bound = match requires_python.as_ref() { Bound::Included(version) => { let major = version.release().first().copied().unwrap_or(0); let minor = version.release().get(1).copied().unwrap_or(0); VersionSpecifier::less_than_version(Version::new([major, minor + 1])) } Bound::Excluded(version) => { let major = version.release().first().copied().unwrap_or(0); let minor = version.release().get(1).copied().unwrap_or(0); VersionSpecifier::less_than_version(Version::new([major, minor + 1])) } Bound::Unbounded => unreachable!("`requires-python` should never be unbounded"), }; let requires_python_request = PythonRequest::Version(VersionRequest::Range( VersionSpecifiers::from_iter([lower_bound, upper_bound]), PythonVariant::default(), )); debug!("Refining interpreter with: {requires_python_request}"); let interpreter = PythonInstallation::find_or_download( Some(&requires_python_request), EnvironmentPreference::OnlySystem, python_preference, python_downloads, client_builder, cache, Some(reporter), install_mirrors.python_install_mirror.as_deref(), install_mirrors.pypy_install_mirror.as_deref(), install_mirrors.python_downloads_json_url.as_deref(), preview, ) .await? .into_interpreter(); // If the user passed a `--python` request, and the refined interpreter is incompatible, we // can't use it. if let Some(python_request) = python_request { if !python_request.satisfied(&interpreter, cache) { return Ok(None); } } Ok(Some(interpreter)) } /// Finalizes a tool installation, after creation of an environment. /// /// Installs tool executables for a given package, handling any conflicts. /// /// Adds a receipt for the tool. pub(crate) fn finalize_tool_install( environment: &PythonEnvironment, name: &PackageName, entrypoints: &[PackageName], installed_tools: &InstalledTools, options: &ToolOptions, force: bool, python: Option<PythonRequest>, requirements: Vec<Requirement>, constraints: Vec<Requirement>, overrides: Vec<Requirement>, build_constraints: Vec<Requirement>, printer: Printer, ) -> anyhow::Result<()> { let executable_directory = uv_tool::tool_executable_dir()?; fs_err::create_dir_all(&executable_directory) .context("Failed to create executable directory")?; debug!( "Installing tool executables into: {}", executable_directory.user_display() ); let mut installed_entrypoints = Vec::new(); let site_packages = SitePackages::from_environment(environment)?; let ordered_packages = entrypoints // Install dependencies first .iter() .filter(|pkg| *pkg != name) .collect::<BTreeSet<_>>() // Then install the root package last .into_iter() .chain(std::iter::once(name)); for package in ordered_packages { if package == name { debug!("Installing entrypoints for tool `{package}`"); } else { debug!("Installing entrypoints for `{package}` as part of tool `{name}`"); } let installed = site_packages.get_packages(package); let dist = installed .first() .context("Expected at least one requirement")?; let dist_entrypoints = entrypoint_paths(&site_packages, dist.name(), dist.version())?; // Determine the entry points targets. Use a sorted collection for deterministic output. let target_entrypoints = dist_entrypoints .into_iter() .map(|(name, source_path)| { let target_path = executable_directory.join( source_path .file_name() .map(std::borrow::ToOwned::to_owned) .unwrap_or_else(|| OsString::from(name.clone())), ); (name, source_path, target_path) }) .collect::<BTreeSet<_>>(); if target_entrypoints.is_empty() { // If package is not the root package, suggest to install it as a dependency. if package != name { writeln!( printer.stdout(), "No executables are provided by package `{}`\n{}{} Use `--with {}` to include `{}` as a dependency without installing its executables.", package.cyan(), "hint".bold().cyan(), ":".bold(), package.cyan(), package.cyan(), )?; continue; } // For the root package, this is a fatal error writeln!( printer.stdout(), "No executables are provided by package `{}`; removing tool", package.cyan() )?; hint_executable_from_dependency(package, &site_packages, printer)?; // Clean up the environment we just created. installed_tools.remove_environment(name)?; return Err(anyhow::anyhow!( "Failed to install entrypoints for `{}`", package.cyan() )); } // Error if we're overwriting an existing entrypoint, unless the user passed `--force`. if !force { let mut existing_entrypoints = target_entrypoints .iter() .filter(|(_, _, target_path)| target_path.exists()) .peekable(); if existing_entrypoints.peek().is_some() { // Clean up the environment we just created installed_tools.remove_environment(name)?; let existing_entrypoints = existing_entrypoints // SAFETY: We know the target has a filename because we just constructed it above .map(|(_, _, target)| target.file_name().unwrap().to_string_lossy()) .collect::<Vec<_>>(); let (s, exists) = if existing_entrypoints.len() == 1 { ("", "exists") } else { ("s", "exist") }; bail!( "Executable{s} already {exists}: {} (use `--force` to overwrite)", existing_entrypoints .iter() .map(|name| name.bold()) .join(", ") ) } } #[cfg(windows)] let itself = std::env::current_exe().ok(); let mut names = BTreeSet::new(); for (name, src, target) in target_entrypoints { debug!("Installing executable: `{name}`"); #[cfg(unix)] replace_symlink(src, &target).context("Failed to install executable")?; #[cfg(windows)] if itself.as_ref().is_some_and(|itself| { std::path::absolute(&target).is_ok_and(|target| *itself == target) }) { self_replace::self_replace(src).context("Failed to install entrypoint")?; } else { fs_err::copy(src, &target).context("Failed to install entrypoint")?; } let tool_entry = ToolEntrypoint::new(&name, target, package.to_string()); names.insert(tool_entry.name.clone()); installed_entrypoints.push(tool_entry); } let s = if names.len() == 1 { "" } else { "s" }; let from_pkg = if name == package { String::new() } else { format!(" from `{package}`") }; writeln!( printer.stderr(), "Installed {} executable{s}{from_pkg}: {}", names.len(), names.iter().map(|name| name.bold()).join(", ") )?; } debug!("Adding receipt for tool `{name}`"); let tool = Tool::new( requirements, constraints, overrides, build_constraints, python, installed_entrypoints, options.clone(), ); installed_tools.add_tool_receipt(name, tool)?; warn_out_of_path(&executable_directory); Ok(()) } fn warn_out_of_path(executable_directory: &Path) { // If the executable directory isn't on the user's PATH, warn. if !Shell::contains_path(executable_directory) { if let Some(shell) = Shell::from_env() { if let Some(command) = shell.prepend_path(executable_directory) { if shell.supports_update() { warn_user_once!( "`{}` is not on your PATH. To use installed tools, run `{}` or `{}`.", executable_directory.simplified_display().cyan(), command.green(), "uv tool update-shell".green() ); } else { warn_user_once!( "`{}` is not on your PATH. To use installed tools, run `{}`.", executable_directory.simplified_display().cyan(), command.green() ); } } else { warn_user_once!( "`{}` is not on your PATH. To use installed tools, add the directory to your PATH.", executable_directory.simplified_display().cyan(), ); } } else { warn_user_once!( "`{}` is not on your PATH. To use installed tools, add the directory to your PATH.", executable_directory.simplified_display().cyan(), ); } } } /// Displays a hint if an executable matching the package name can be found in a dependency of the package. fn hint_executable_from_dependency( name: &PackageName, site_packages: &SitePackages, printer: Printer, ) -> anyhow::Result<()> { let packages = matching_packages(name.as_ref(), site_packages); match packages.as_slice() { [] => {} [package] => { let command = format!("uv tool install {}", package.name()); writeln!( printer.stdout(), "{}{} An executable with the name `{}` is available via dependency `{}`.\n Did you mean `{}`?", "hint".bold().cyan(), ":".bold(), name.cyan(), package.name().cyan(), command.bold(), )?; } packages => { writeln!( printer.stdout(), "{}{} An executable with the name `{}` is available via the following dependencies::", "hint".bold().cyan(), ":".bold(), name.cyan(), )?; for package in packages { writeln!(printer.stdout(), "- {}", package.name().cyan())?; } writeln!( printer.stdout(), " Did you mean to install one of them instead?" )?; } } 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/src/bin/uvw.rs
crates/uv/src/bin/uvw.rs
#![cfg_attr(windows, windows_subsystem = "windows")] use std::convert::Infallible; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, ExitStatus}; /// Spawns a command exec style. fn exec_spawn(cmd: &mut Command) -> std::io::Result<Infallible> { #[cfg(unix)] { use std::os::unix::process::CommandExt; let err = cmd.exec(); Err(err) } #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; cmd.stdin(std::process::Stdio::inherit()); let status = cmd.creation_flags(CREATE_NO_WINDOW).status()?; #[allow(clippy::exit)] std::process::exit(status.code().unwrap()) } } /// Assuming the binary is called something like `uvw@1.2.3(.exe)`, compute the `@1.2.3(.exe)` part /// so that we can preferentially find `uv@1.2.3(.exe)`, for folks who like managing multiple /// installs in this way. fn get_uvw_suffix(current_exe: &Path) -> Option<&str> { let os_file_name = current_exe.file_name()?; let file_name_str = os_file_name.to_str()?; file_name_str.strip_prefix("uvw") } /// Gets the path to `uv`, given info about `uvw` fn get_uv_path(current_exe_parent: &Path, uvw_suffix: Option<&str>) -> std::io::Result<PathBuf> { // First try to find a matching suffixed `uv`, e.g. `uv@1.2.3(.exe)` let uv_with_suffix = uvw_suffix.map(|suffix| current_exe_parent.join(format!("uv{suffix}"))); if let Some(uv_with_suffix) = &uv_with_suffix { #[allow(clippy::print_stderr, reason = "printing a very rare warning")] match uv_with_suffix.try_exists() { Ok(true) => return Ok(uv_with_suffix.to_owned()), Ok(false) => { /* definitely not there, proceed to fallback */ } Err(err) => { // We don't know if `uv@1.2.3` exists, something errored when checking. // We *could* blindly use `uv@1.2.3` in this case, as the code below does, however // in this extremely narrow corner case it's *probably* better to default to `uv`, // since we don't want to mess up existing users who weren't using suffixes? eprintln!( "warning: failed to determine if `{}` exists, trying `uv` instead: {err}", uv_with_suffix.display() ); } } } // Then just look for good ol' `uv` let uv = current_exe_parent.join(format!("uv{}", std::env::consts::EXE_SUFFIX)); // If we are sure the `uv` binary does not exist, display a clearer error message. // If we're not certain if uv exists (try_exists == Err), keep going and hope it works. if matches!(uv.try_exists(), Ok(false)) { let message = if let Some(uv_with_suffix) = uv_with_suffix { format!( "Could not find the `uv` binary at either of:\n {}\n {}", uv_with_suffix.display(), uv.display(), ) } else { format!("Could not find the `uv` binary at: {}", uv.display()) }; Err(std::io::Error::new(std::io::ErrorKind::NotFound, message)) } else { Ok(uv) } } fn run() -> std::io::Result<ExitStatus> { let current_exe = std::env::current_exe()?; let Some(bin) = current_exe.parent() else { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "Could not determine the location of the `uvw` binary", )); }; let uvw_suffix = get_uvw_suffix(&current_exe); let uv = get_uv_path(bin, uvw_suffix)?; let args = std::env::args_os() // Skip the `uvw` name .skip(1) .collect::<Vec<_>>(); let mut cmd = Command::new(uv); cmd.args(&args); match exec_spawn(&mut cmd)? {} } #[allow(clippy::print_stderr)] fn main() -> ExitCode { let result = run(); match result { // Fail with 2 if the status cannot be cast to an exit code Ok(status) => u8::try_from(status.code().unwrap_or(2)).unwrap_or(2).into(), Err(err) => { eprintln!("error: {err}"); ExitCode::from(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/src/bin/uvx.rs
crates/uv/src/bin/uvx.rs
use std::convert::Infallible; use std::path::{Path, PathBuf}; use std::{ ffi::OsString, process::{Command, ExitCode, ExitStatus}, }; /// Spawns a command exec style. fn exec_spawn(cmd: &mut Command) -> std::io::Result<Infallible> { #[cfg(unix)] { use std::os::unix::process::CommandExt; let err = cmd.exec(); Err(err) } #[cfg(windows)] { cmd.stdin(std::process::Stdio::inherit()); let status = cmd.status()?; #[allow(clippy::exit)] std::process::exit(status.code().unwrap()) } } /// Assuming the binary is called something like `uvx@1.2.3(.exe)`, compute the `@1.2.3(.exe)` part /// so that we can preferentially find `uv@1.2.3(.exe)`, for folks who like managing multiple /// installs in this way. fn get_uvx_suffix(current_exe: &Path) -> Option<&str> { let os_file_name = current_exe.file_name()?; let file_name_str = os_file_name.to_str()?; file_name_str.strip_prefix("uvx") } /// Gets the path to `uv`, given info about `uvx` fn get_uv_path(current_exe_parent: &Path, uvx_suffix: Option<&str>) -> std::io::Result<PathBuf> { // First try to find a matching suffixed `uv`, e.g. `uv@1.2.3(.exe)` let uv_with_suffix = uvx_suffix.map(|suffix| current_exe_parent.join(format!("uv{suffix}"))); if let Some(uv_with_suffix) = &uv_with_suffix { #[allow(clippy::print_stderr, reason = "printing a very rare warning")] match uv_with_suffix.try_exists() { Ok(true) => return Ok(uv_with_suffix.to_owned()), Ok(false) => { /* definitely not there, proceed to fallback */ } Err(err) => { // We don't know if `uv@1.2.3` exists, something errored when checking. // We *could* blindly use `uv@1.2.3` in this case, as the code below does, however // in this extremely narrow corner case it's *probably* better to default to `uv`, // since we don't want to mess up existing users who weren't using suffixes? eprintln!( "warning: failed to determine if `{}` exists, trying `uv` instead: {err}", uv_with_suffix.display() ); } } } // Then just look for good ol' `uv` let uv = current_exe_parent.join(format!("uv{}", std::env::consts::EXE_SUFFIX)); // If we are sure the `uv` binary does not exist, display a clearer error message. // If we're not certain if uv exists (try_exists == Err), keep going and hope it works. if matches!(uv.try_exists(), Ok(false)) { let message = if let Some(uv_with_suffix) = uv_with_suffix { format!( "Could not find the `uv` binary at either of:\n {}\n {}", uv_with_suffix.display(), uv.display(), ) } else { format!("Could not find the `uv` binary at: {}", uv.display()) }; Err(std::io::Error::new(std::io::ErrorKind::NotFound, message)) } else { Ok(uv) } } fn run() -> std::io::Result<ExitStatus> { let current_exe = std::env::current_exe()?; let Some(bin) = current_exe.parent() else { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "Could not determine the location of the `uvx` binary", )); }; let uvx_suffix = get_uvx_suffix(&current_exe); let uv = get_uv_path(bin, uvx_suffix)?; let args = ["tool", "uvx"] .iter() .map(OsString::from) // Skip the `uvx` name .chain(std::env::args_os().skip(1)) .collect::<Vec<_>>(); let mut cmd = Command::new(uv); cmd.args(&args); match exec_spawn(&mut cmd)? {} } #[allow(clippy::print_stderr)] fn main() -> ExitCode { let result = run(); match result { // Fail with 2 if the status cannot be cast to an exit code Ok(status) => u8::try_from(status.code().unwrap_or(2)).unwrap_or(2).into(), Err(err) => { eprintln!("error: {err}"); ExitCode::from(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/src/bin/uv.rs
crates/uv/src/bin/uv.rs
// Don't optimize the alloc crate away due to it being otherwise unused. // https://github.com/rust-lang/rust/issues/64402 #[cfg(feature = "performance-memory-allocator")] extern crate uv_performance_memory_allocator; use std::process::ExitCode; use uv::main as uv_main; #[allow(unsafe_code)] fn main() -> ExitCode { // SAFETY: This is safe because we are running it early in `main` before spawning any threads. unsafe { uv_main(std::env::args_os()) } }
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/tests/it/lock_exclude_newer_relative.rs
crates/uv/tests/it/lock_exclude_newer_relative.rs
use anyhow::Result; use assert_fs::fixture::{FileWriteStr, PathChild}; use insta::assert_snapshot; use uv_static::EnvVars; use crate::common::{TestContext, uv_snapshot}; /// Lock with a relative exclude-newer value. /// /// Uses idna which has releases at: /// - 3.6: 2023-11-25 /// - 3.7: 2024-04-11 #[test] fn lock_exclude_newer_relative() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["idna"] "#, )?; // 3 weeks before 2024-05-01 is 2024-04-10, which is before idna 3.7 (released 2024-04-11). let current_timestamp = "2024-05-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("3 weeks"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "###); let lock = context.read("uv.lock"); // Should resolve to idna 3.6 (released 2023-11-25, before cutoff of 2024-04-10) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-04-10T00:00:00Z" exclude-newer-span = "P3W" [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); // Changing the current time should not result in a new lockfile let later_timestamp = "2024-06-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, later_timestamp) .arg("--exclude-newer") .arg("3 weeks") .arg("--locked"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); // Changing the span to 2 weeks should cause a new resolution. // 2 weeks before 2024-05-01 is 2024-04-17, which is after idna 3.7 (released 2024-04-11). uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P3W` to `P2W` Resolved 2 packages in [TIME] Updated idna v3.6 -> v3.7 "); // Both `exclude-newer` values in the lockfile should be changed, and we should now have idna 3.7 let lock = context.read("uv.lock"); assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-04-17T00:00:00Z" exclude-newer-span = "P2W" [[package]] name = "idna" version = "3.7" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/ed/f86a79a07470cb07819390452f178b3bef1d375f2ec021ecfc709fc7cf07/idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc", size = 189575, upload-time = "2024-04-11T03:34:43.276Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0", size = 66836, upload-time = "2024-04-11T03:34:41.447Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); // Similarly, using something like `--upgrade` should cause a new resolution let current_timestamp = "2024-06-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2 weeks") .arg("--upgrade"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); // And the `exclude-newer` timestamp value in the lockfile should be changed let lock = context.read("uv.lock"); assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-05-18T00:00:00Z" exclude-newer-span = "P2W" [[package]] name = "idna" version = "3.7" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/ed/f86a79a07470cb07819390452f178b3bef1d375f2ec021ecfc709fc7cf07/idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc", size = 189575, upload-time = "2024-04-11T03:34:43.276Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0", size = 66836, upload-time = "2024-04-11T03:34:41.447Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); // Similarly, using something like `--refresh` should cause a new resolution let current_timestamp = "2024-07-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2 weeks") .arg("--refresh"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); Ok(()) } /// Lock with a relative exclude-newer-package value. /// /// Uses idna which has releases at: /// - 3.6: 2023-11-25 /// - 3.7: 2024-04-11 #[test] fn lock_exclude_newer_package_relative() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["idna"] "#, )?; // 3 weeks before 2024-05-01 is 2024-04-10, which is before idna 3.7 (released 2024-04-11). let current_timestamp = "2024-05-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer-package") .arg("idna=3 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); let lock = context.read("uv.lock"); // Should resolve to idna 3.6 (released 2023-11-25, before cutoff of 2024-04-10) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] [options.exclude-newer-package] idna = { timestamp = "2024-04-10T00:00:00Z", span = "P3W" } [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); // Changing the current time should not result in a new lockfile let later_timestamp = "2024-06-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, later_timestamp) .arg("--exclude-newer-package") .arg("idna=3 weeks") .arg("--locked"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); // Changing the span to 2 weeks should cause a new resolution. // 2 weeks before 2024-05-01 is 2024-04-17, which is after idna 3.7 (released 2024-04-11). uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer-package") .arg("idna=2 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P3W` to `P2W` for package `idna` Resolved 2 packages in [TIME] Updated idna v3.6 -> v3.7 "); // Both `exclude-newer-package` values in the lockfile should be changed, and we should now have idna 3.7 let lock = context.read("uv.lock"); assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] [options.exclude-newer-package] idna = { timestamp = "2024-04-17T00:00:00Z", span = "P2W" } [[package]] name = "idna" version = "3.7" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/ed/f86a79a07470cb07819390452f178b3bef1d375f2ec021ecfc709fc7cf07/idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc", size = 189575, upload-time = "2024-04-11T03:34:43.276Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0", size = 66836, upload-time = "2024-04-11T03:34:41.447Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); // Similarly, using something like `--upgrade` should cause a new resolution let current_timestamp = "2024-06-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer-package") .arg("idna=2 weeks") .arg("--upgrade"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); // And the `exclude-newer-package` timestamp value in the lockfile should be changed let lock = context.read("uv.lock"); assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] [options.exclude-newer-package] idna = { timestamp = "2024-05-18T00:00:00Z", span = "P2W" } [[package]] name = "idna" version = "3.7" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/ed/f86a79a07470cb07819390452f178b3bef1d375f2ec021ecfc709fc7cf07/idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc", size = 189575, upload-time = "2024-04-11T03:34:43.276Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0", size = 66836, upload-time = "2024-04-11T03:34:41.447Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); Ok(()) } /// Lock with a relative exclude-newer value from the `pyproject.toml`. /// /// Uses idna which has releases at: /// - 3.6: 2023-11-25 /// - 3.7: 2024-04-11 #[test] fn lock_exclude_newer_relative_pyproject() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["idna"] [tool.uv] exclude-newer = "3 weeks" "#, )?; // 3 weeks before 2024-05-01 is 2024-04-10, which is before idna 3.7 (released 2024-04-11). let current_timestamp = "2024-05-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); let lock = context.read("uv.lock"); // Should resolve to idna 3.6 (released 2023-11-25, before cutoff of 2024-04-10) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-04-10T00:00:00Z" exclude-newer-span = "P3W" [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); Ok(()) } /// Lock with a relative exclude-newer-package value from the `pyproject.toml`. /// /// Uses idna which has releases at: /// - 3.6: 2023-11-25 /// - 3.7: 2024-04-11 #[test] fn lock_exclude_newer_package_relative_pyproject() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["idna"] [tool.uv] exclude-newer-package = { idna = "3 weeks" } "#, )?; // 3 weeks before 2024-05-01 is 2024-04-10, which is before idna 3.7 (released 2024-04-11). let current_timestamp = "2024-05-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "); let lock = context.read("uv.lock"); // Should resolve to idna 3.6 (released 2023-11-25, before cutoff of 2024-04-10) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] [options.exclude-newer-package] idna = { timestamp = "2024-04-10T00:00:00Z", span = "P3W" } [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, ] [package.metadata] requires-dist = [{ name = "idna" }] "#); Ok(()) } /// Lock with both global and per-package relative exclude-newer values. /// /// Uses idna which has releases at: /// - 3.6: 2023-11-25 /// - 3.7: 2024-04-11 /// /// And typing-extensions which has releases at: /// - 4.10.0: 2024-02-25 /// - 4.11.0: 2024-04-05 #[test] fn lock_exclude_newer_relative_global_and_package() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["idna", "typing-extensions"] "#, )?; // Use a fixed timestamp so the test is reproducible. // Current time: 2024-05-01 // Global: 3 weeks back = 2024-04-10 (before idna 3.7 released 2024-04-11) → idna 3.6 // Per-package: 2 weeks back = 2024-04-17 (after typing-extensions 4.11.0 released 2024-04-05) → typing-extensions 4.11.0 let current_timestamp = "2024-05-01T00:00:00Z"; // Lock with both global exclude-newer and package-specific override using relative durations uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("3 weeks") .arg("--exclude-newer-package") .arg("typing-extensions=2 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 3 packages in [TIME] "); let lock = context.read("uv.lock"); // idna 3.6 (global cutoff 2024-04-10 is before 3.7 release on 2024-04-11) // typing-extensions 4.11.0 (per-package cutoff 2024-04-17 is after 4.11.0 release on 2024-04-05) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-04-10T00:00:00Z" exclude-newer-span = "P3W" [options.exclude-newer-package] typing-extensions = { timestamp = "2024-04-17T00:00:00Z", span = "P2W" } [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, { name = "typing-extensions" }, ] [package.metadata] requires-dist = [ { name = "idna" }, { name = "typing-extensions" }, ] [[package]] name = "typing-extensions" version = "4.11.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f6/f3/b827b3ab53b4e3d8513914586dcca61c355fa2ce8252dea4da56e67bf8f2/typing_extensions-4.11.0.tar.gz", hash = "sha256:83f085bd5ca59c80295fc2a82ab5dac679cbe02b9f33f7d83af68e241bea51b0", size = 78744, upload-time = "2024-04-05T12:35:47.093Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/01/f3/936e209267d6ef7510322191003885de524fc48d1b43269810cd589ceaf5/typing_extensions-4.11.0-py3-none-any.whl", hash = "sha256:c1f94d72897edaf4ce775bb7558d5b79d8126906a14ea5ed1635921406c0387a", size = 34698, upload-time = "2024-04-05T12:35:44.388Z" }, ] "#); // Changing the current time should not invalidate the lockfile let later_timestamp = "2024-07-01T00:00:00Z"; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, later_timestamp) .arg("--exclude-newer") .arg("3 weeks") .arg("--exclude-newer-package") .arg("typing-extensions=2 weeks") .arg("--locked"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 3 packages in [TIME] "); // Changing the global span to 2 weeks should cause a new resolution. // 2 weeks before 2024-05-01 is 2024-04-17 (after idna 3.7 released 2024-04-11) → idna 3.7 uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2 weeks") .arg("--exclude-newer-package") .arg("typing-extensions=2 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P3W` to `P2W` Resolved 3 packages in [TIME] Updated idna v3.6 -> v3.7 "); // Changing the package-specific span should also invalidate the lockfile uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2 weeks") .arg("--exclude-newer-package") .arg("typing-extensions=3 days"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P2W` to `P3D` for package `typing-extensions` Resolved 3 packages in [TIME] "); // Use an absolute global value and relative package value uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("2024-05-20T00:00:00Z") .arg("--exclude-newer-package") .arg("typing-extensions=2 weeks"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to removal of exclude newer span Resolved 3 packages in [TIME] "); let lock = context.read("uv.lock"); // idna 3.7 (absolute cutoff 2024-05-20 is after 3.7 release on 2024-04-11) // typing-extensions 4.11.0 (relative cutoff 2024-04-17) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-05-20T00:00:00Z" [options.exclude-newer-package] typing-extensions = { timestamp = "2024-04-17T00:00:00Z", span = "P2W" } [[package]] name = "idna" version = "3.7" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/ed/f86a79a07470cb07819390452f178b3bef1d375f2ec021ecfc709fc7cf07/idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc", size = 189575, upload-time = "2024-04-11T03:34:43.276Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0", size = 66836, upload-time = "2024-04-11T03:34:41.447Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, { name = "typing-extensions" }, ] [package.metadata] requires-dist = [ { name = "idna" }, { name = "typing-extensions" }, ] [[package]] name = "typing-extensions" version = "4.11.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f6/f3/b827b3ab53b4e3d8513914586dcca61c355fa2ce8252dea4da56e67bf8f2/typing_extensions-4.11.0.tar.gz", hash = "sha256:83f085bd5ca59c80295fc2a82ab5dac679cbe02b9f33f7d83af68e241bea51b0", size = 78744, upload-time = "2024-04-05T12:35:47.093Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/01/f3/936e209267d6ef7510322191003885de524fc48d1b43269810cd589ceaf5/typing_extensions-4.11.0-py3-none-any.whl", hash = "sha256:c1f94d72897edaf4ce775bb7558d5b79d8126906a14ea5ed1635921406c0387a", size = 34698, upload-time = "2024-04-05T12:35:44.388Z" }, ] "#); // Use a relative global value and absolute package value uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, current_timestamp) .arg("--exclude-newer") .arg("3 weeks") .arg("--exclude-newer-package") .arg("typing-extensions=2024-04-01T00:00:00Z"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to addition of exclude newer span `P3W` Resolved 3 packages in [TIME] Updated idna v3.7 -> v3.6 Updated typing-extensions v4.11.0 -> v4.10.0 "); let lock = context.read("uv.lock"); // idna 3.6 (relative cutoff 2024-04-10 is before 3.7 release on 2024-04-11) // typing-extensions 4.10.0 (absolute cutoff 2024-04-01 is before 4.11.0 release on 2024-04-05) assert_snapshot!(lock, @r#" version = 1 revision = 3 requires-python = ">=3.12" [options] exclude-newer = "2024-04-10T00:00:00Z" exclude-newer-span = "P3W" [options.exclude-newer-package] typing-extensions = "2024-04-01T00:00:00Z" [[package]] name = "idna" version = "3.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/bf/3f/ea4b9117521a1e9c50344b909be7886dd00a519552724809bb1f486986c2/idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca", size = 175426, upload-time = "2023-11-25T15:40:54.902Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/e7/a82b05cf63a603df6e68d59ae6a68bf5064484a0718ea5033660af4b54a9/idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f", size = 61567, upload-time = "2023-11-25T15:40:52.604Z" }, ] [[package]] name = "project" version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "idna" }, { name = "typing-extensions" }, ] [package.metadata] requires-dist = [ { name = "idna" }, { name = "typing-extensions" }, ] [[package]] name = "typing-extensions" version = "4.10.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/16/3a/0d26ce356c7465a19c9ea8814b960f8a36c3b0d07c323176620b7b483e44/typing_extensions-4.10.0.tar.gz", hash = "sha256:b0abd7c89e8fb96f98db18d86106ff1d90ab692004eb746cf6eda2682f91b3cb", size = 77558, upload-time = "2024-02-25T22:12:49.693Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f9/de/dc04a3ea60b22624b51c703a84bbe0184abcd1d0b9bc8074b5d6b7ab90bb/typing_extensions-4.10.0-py3-none-any.whl", hash = "sha256:69b1a937c3a517342112fb4c6df7e72fc39a38e7891a5730ed4985b5214b5475", size = 33926, upload-time = "2024-02-25T22:12:47.72Z" }, ] "#); Ok(()) } /// Lock with various relative exclude newer value formats. #[test] fn lock_exclude_newer_relative_values() -> Result<()> { let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["iniconfig"] "#, )?; uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("1 day"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] "###); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("30days"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P1D` to `P30D` Resolved 2 packages in [TIME] "); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("P1D"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P30D` to `P1D` Resolved 2 packages in [TIME] "); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("1 week"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P1D` to `P1W` Resolved 2 packages in [TIME] "); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("1 week ago"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Ignoring existing lockfile due to change of exclude newer span from `P1W` to `-P1W` Resolved 2 packages in [TIME] "); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER) .arg("--exclude-newer") .arg("3 months"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: invalid value '3 months' for '--exclude-newer <EXCLUDE_NEWER>': Duration `3 months` uses 'months' which is not allowed; use days instead, e.g., `90 days`. For more information, try '--help'. "); uv_snapshot!(context.filters(), context .lock() .env_remove(EnvVars::UV_EXCLUDE_NEWER)
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/tests/it/venv.rs
crates/uv/tests/it/venv.rs
use anyhow::Result; use assert_cmd::prelude::*; use assert_fs::prelude::*; use indoc::indoc; use predicates::prelude::*; use uv_python::{PYTHON_VERSION_FILENAME, PYTHON_VERSIONS_FILENAME}; use uv_static::EnvVars; #[cfg(unix)] use fs_err::os::unix::fs::symlink; use crate::common::{TestContext, uv_snapshot}; #[test] fn create_venv() { let context = TestContext::new_with_versions(&["3.12"]); // Create a virtual environment at `.venv`. uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv warning: A virtual environment already exists at `.venv`. In the future, uv will require `--clear` to replace it Activate with: source .venv/[BIN]/activate " ); // Create a virtual environment at the same location using `--clear`, // which should replace it. uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--clear") .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_313() { let context = TestContext::new_with_versions(&["3.13"]); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.13"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.13.[X] interpreter at: [PYTHON-3.13] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_project_environment() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); // `uv venv` ignores `UV_PROJECT_ENVIRONMENT` when it's not a project uv_snapshot!(context.filters(), context.venv().env(EnvVars::UV_PROJECT_ENVIRONMENT, "foo"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); context .temp_dir .child("foo") .assert(predicates::path::missing()); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str( r#" [project] name = "project" version = "0.1.0" requires-python = ">=3.12" dependencies = ["iniconfig"] "#, )?; // But, if we're in a project we'll respect it uv_snapshot!(context.filters(), context.venv().env(EnvVars::UV_PROJECT_ENVIRONMENT, "foo"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: foo Activate with: source foo/[BIN]/activate "### ); context .temp_dir .child("foo") .assert(predicates::path::is_dir()); // Unless we're in a child directory let child = context.temp_dir.child("child"); child.create_dir_all()?; uv_snapshot!(context.filters(), context.venv().env(EnvVars::UV_PROJECT_ENVIRONMENT, "foo").current_dir(child.path()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // In which case, we'll use the default name of `.venv` child.child("foo").assert(predicates::path::missing()); child.child(".venv").assert(predicates::path::is_dir()); // Or, if a name is provided uv_snapshot!(context.filters(), context.venv().arg("bar"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: bar Activate with: source bar/[BIN]/activate "### ); context .temp_dir .child("bar") .assert(predicates::path::is_dir()); // Or, of they opt-out with `--no-workspace` or `--no-project` uv_snapshot!(context.filters(), context.venv().arg("--clear").arg("--no-workspace"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); uv_snapshot!(context.filters(), context.venv().arg("--clear").arg("--no-project"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); Ok(()) } #[test] fn virtual_empty() -> Result<()> { // testing how `uv venv` reacts to a pyproject with no `[project]` and nothing useful to it let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! {r#" [tool.mycooltool] wow = "someconfig" "#})?; uv_snapshot!(context.filters(), context.venv(), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv warning: A virtual environment already exists at `.venv`. In the future, uv will require `--clear` to replace it Activate with: source .venv/[BIN]/activate "); Ok(()) } #[test] fn virtual_dependency_group() -> Result<()> { // testing basic `uv venv` functionality // when the pyproject.toml is fully virtual (no `[project]`, but `[dependency-groups]` defined) let context = TestContext::new("3.12"); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! {r#" [dependency-groups] foo = ["sortedcontainers"] bar = ["iniconfig"] dev = ["sniffio"] "#})?; uv_snapshot!(context.filters(), context.venv(), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv warning: A virtual environment already exists at `.venv`. In the future, uv will require `--clear` to replace it Activate with: source .venv/[BIN]/activate "); Ok(()) } #[test] fn create_venv_defaults_to_cwd() { let context = TestContext::new_with_versions(&["3.12"]); uv_snapshot!(context.filters(), context.venv() .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_ignores_virtual_env_variable() { let context = TestContext::new_with_versions(&["3.12"]); // We shouldn't care if `VIRTUAL_ENV` is set to an non-existent directory // because we ignore virtual environment interpreter sources (we require a system interpreter) uv_snapshot!(context.filters(), context.venv() .env(EnvVars::VIRTUAL_ENV, context.temp_dir.child("does-not-exist").as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); } #[test] fn create_venv_reads_request_from_python_version_file() { let context = TestContext::new_with_versions(&["3.11", "3.12"]); // Without the file, we should use the first on the PATH uv_snapshot!(context.filters(), context.venv(), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With a version file, we should prefer that version context .temp_dir .child(PYTHON_VERSION_FILENAME) .write_str("3.12") .unwrap(); uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_reads_request_from_python_versions_file() { let context = TestContext::new_with_versions(&["3.11", "3.12"]); // Without the file, we should use the first on the PATH uv_snapshot!(context.filters(), context.venv(), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With a versions file, we should prefer the first listed version context .temp_dir .child(PYTHON_VERSIONS_FILENAME) .write_str("3.12\n3.11") .unwrap(); uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_respects_pyproject_requires_python() -> Result<()> { let context = TestContext::new_with_versions(&["3.11", "3.9", "3.10", "3.12"]); // Without a Python requirement, we use the first on the PATH uv_snapshot!(context.filters(), context.venv(), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = "<3.11"`, we prefer the first available version let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = "<3.11" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.9.[X] interpreter at: [PYTHON-3.9] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = "==3.11.*"`, we prefer exact version (3.11) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = "==3.11.*" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = ">=3.11,<3.12"`, we prefer exact version (3.11) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.11,<3.12" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = ">=3.10"`, we prefer first compatible version (3.11) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.11" dependencies = [] "# })?; // With `requires-python = ">=3.11"`, we prefer first compatible version (3.11) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.11" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = ">3.11"`, we prefer first compatible version (3.11) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">3.11" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // With `requires-python = ">=3.12"`, we prefer first compatible version (3.12) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.12" dependencies = [] "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); // We warn if we receive an incompatible version uv_snapshot!(context.filters(), context.venv().arg("--clear").arg("--python").arg("3.11"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] warning: The requested interpreter resolved to Python 3.11.[X], which is incompatible with the project's Python requirement: `>=3.12` (from `project.requires-python`) Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); Ok(()) } #[test] fn create_venv_respects_group_requires_python() -> Result<()> { let context = TestContext::new_with_versions(&["3.9", "3.10", "3.11", "3.12"]); // Without a Python requirement, we use the first on the PATH uv_snapshot!(context.filters(), context.venv(), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.9.[X] interpreter at: [PYTHON-3.9] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); // With `requires-python = ">=3.10"` on the default group, we pick 3.10 // However non-default groups should not be consulted! let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" dependencies = [] [dependency-groups] dev = ["sortedcontainers"] other = ["sniffio"] [tool.uv.dependency-groups] dev = {requires-python = ">=3.10"} other = {requires-python = ">=3.12"} "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.10.[X] interpreter at: [PYTHON-3.10] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); // When the top-level requires-python and default group requires-python // both apply, their intersection is used. However non-default groups // should not be consulted! (here the top-level wins) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.11" dependencies = [] [dependency-groups] dev = ["sortedcontainers"] other = ["sniffio"] [tool.uv.dependency-groups] dev = {requires-python = ">=3.10"} other = {requires-python = ">=3.12"} "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); // When the top-level requires-python and default group requires-python // both apply, their intersection is used. However non-default groups // should not be consulted! (here the group wins) let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = ">=3.10" dependencies = [] [dependency-groups] dev = ["sortedcontainers"] other = ["sniffio"] [tool.uv.dependency-groups] dev = {requires-python = ">=3.11"} other = {requires-python = ">=3.12"} "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); // We warn if we receive an incompatible version let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" dependencies = [] [dependency-groups] dev = ["sortedcontainers"] [tool.uv.dependency-groups] dev = {requires-python = ">=3.12"} "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear").arg("--python").arg("3.11"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] warning: The requested interpreter resolved to Python 3.11.[X], which is incompatible with the project's Python requirement: `>=3.12` (from `tool.uv.dependency-groups.dev.requires-python`). Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); // We error if there's no compatible version // non-default groups are not consulted here! let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r#" [project] name = "foo" version = "1.0.0" requires-python = "<3.12" dependencies = [] [dependency-groups] dev = ["sortedcontainers"] other = ["sniffio"] [tool.uv.dependency-groups] dev = {requires-python = ">=3.12"} other = {requires-python = ">=3.11"} "# })?; uv_snapshot!(context.filters(), context.venv().arg("--clear").arg("--python").arg("3.11"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Found conflicting Python requirements: - foo: <3.12 - foo:dev: >=3.12 " ); Ok(()) } #[test] fn create_venv_ignores_missing_pyproject_metadata() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r"[tool.no.project.here]" })?; uv_snapshot!(context.filters(), context.venv(), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); Ok(()) } #[test] fn create_venv_warns_user_on_requires_python_discovery_error() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); let pyproject_toml = context.temp_dir.child("pyproject.toml"); pyproject_toml.write_str(indoc! { r"invalid toml" })?; uv_snapshot!(context.filters(), context.venv(), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- warning: Failed to parse `pyproject.toml` during settings discovery: TOML parse error at line 1, column 9 | 1 | invalid toml | ^ key with no value, expected `=` warning: Failed to parse `pyproject.toml` during environment creation: TOML parse error at line 1, column 9 | 1 | invalid toml | ^ key with no value, expected `=` Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); context.venv.assert(predicates::path::is_dir()); Ok(()) } #[test] fn create_venv_explicit_request_takes_priority_over_python_version_file() { let context = TestContext::new_with_versions(&["3.11", "3.12"]); context .temp_dir .child(PYTHON_VERSION_FILENAME) .write_str("3.12") .unwrap(); uv_snapshot!(context.filters(), context.venv().arg("--python").arg("3.11"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] #[cfg(feature = "pypi")] fn seed() { let context = TestContext::new_with_versions(&["3.12"]); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--seed") .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment with seed packages at: .venv + pip==24.0 Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] #[cfg(feature = "pypi")] fn seed_older_python_version() { let context = TestContext::new_with_versions(&["3.11"]); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--seed") .arg("--python") .arg("3.11"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.11.[X] interpreter at: [PYTHON-3.11] Creating virtual environment with seed packages at: .venv + pip==24.0 + setuptools==69.2.0 + wheel==0.43.0 Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); } #[test] fn create_venv_with_invalid_http_timeout() { let context = TestContext::new_with_versions(&["3.12"]).with_http_timeout("not_a_number"); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Failed to parse environment variable `UV_HTTP_TIMEOUT` with invalid value `not_a_number`: invalid digit found in string "###); } #[test] fn create_venv_with_invalid_concurrent_installs() { let context = TestContext::new_with_versions(&["3.12"]).with_concurrent_installs("0"); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Failed to parse environment variable `UV_CONCURRENT_INSTALLS` with invalid value `0`: number would be zero for non-zero type "###); } #[test] fn create_venv_unknown_python_minor() { let context = TestContext::new_with_versions(&["3.12"]).with_filtered_python_sources(); let mut command = context.venv(); command .arg(context.venv.as_os_str()) // Request a version we know we'll never see .arg("--python") .arg("3.100") // Unset this variable to force what the user would see .env_remove(EnvVars::UV_TEST_PYTHON_PATH); uv_snapshot!(context.filters(), &mut command, @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: No interpreter found for Python 3.100 in [PYTHON SOURCES] " ); context.venv.assert(predicates::path::missing()); } #[test] fn create_venv_unknown_python_patch() { let context = TestContext::new_with_versions(&["3.12"]).with_filtered_python_sources(); let mut command = context.venv(); command .arg(context.venv.as_os_str()) // Request a version we know we'll never see .arg("--python") .arg("3.12.100") // Unset this variable to force what the user would see .env_remove(EnvVars::UV_TEST_PYTHON_PATH); uv_snapshot!(context.filters(), &mut command, @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: No interpreter found for Python 3.12.[X] in [PYTHON SOURCES] " ); context.venv.assert(predicates::path::missing()); } #[cfg(feature = "python-patch")] #[test] fn create_venv_python_patch() { let context = TestContext::new_with_versions(&["3.12.9"]); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12.9"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.9 interpreter at: [PYTHON-3.12.9] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); context.venv.assert(predicates::path::is_dir()); } #[test] fn file_exists() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); // Create a file at `.venv`. Creating a virtualenv at the same path should fail. context.venv.touch()?; uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv error: Failed to create virtual environment Caused by: File exists at `.venv` " ); Ok(()) } #[test] fn empty_dir_exists() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); // Create an empty directory at `.venv`. Creating a virtualenv at the same path should succeed. context.venv.create_dir_all()?; uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); context.venv.assert(predicates::path::is_dir()); Ok(()) } #[test] fn non_empty_dir_exists() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); // Create a non-empty directory at `.venv`. Creating a virtualenv at the same path should fail, // unless `--clear` is specified. context.venv.create_dir_all()?; context.venv.child("file").touch()?; uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv error: Failed to create virtual environment Caused by: A directory already exists at: .venv hint: Use the `--clear` flag or set `UV_VENV_CLEAR=1` to replace the existing directory "); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--clear") .arg("--python") .arg("3.12"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate " ); Ok(()) } #[test] fn non_empty_dir_exists_allow_existing() -> Result<()> { let context = TestContext::new_with_versions(&["3.12"]); // Create a non-empty directory at `.venv`. Creating a virtualenv at the same path should // succeed when `--allow-existing` is specified, but fail when it is not. context.venv.create_dir_all()?; context.venv.child("file").touch()?; uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--python") .arg("3.12"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv error: Failed to create virtual environment Caused by: A directory already exists at: .venv hint: Use the `--clear` flag or set `UV_VENV_CLEAR=1` to replace the existing directory " ); uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--allow-existing") .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv Activate with: source .venv/[BIN]/activate "### ); // Running again should _also_ succeed, overwriting existing symlinks and respecting existing // directories. uv_snapshot!(context.filters(), context.venv() .arg(context.venv.as_os_str()) .arg("--allow-existing") .arg("--python") .arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Using CPython 3.12.[X] interpreter at: [PYTHON-3.12] Creating virtual environment at: .venv
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/tests/it/python_list.rs
crates/uv/tests/it/python_list.rs
use uv_platform::{Arch, Os}; use uv_static::EnvVars; use crate::common::{TestContext, uv_snapshot}; use anyhow::Result; use wiremock::{ Mock, MockServer, ResponseTemplate, matchers::{method, path}, }; #[test] fn python_list() { let mut context: TestContext = TestContext::new_with_versions(&["3.11", "3.12"]) .with_filtered_python_symlinks() .with_filtered_python_keys() .with_collapsed_whitespace(); uv_snapshot!(context.filters(), context.python_list().env(EnvVars::UV_TEST_PYTHON_PATH, ""), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); // We show all interpreters uv_snapshot!(context.filters(), context.python_list(), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Request Python 3.12 uv_snapshot!(context.filters(), context.python_list().arg("3.12"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] ----- stderr ----- "); // Request Python 3.11 uv_snapshot!(context.filters(), context.python_list().arg("3.11"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Request CPython uv_snapshot!(context.filters(), context.python_list().arg("cpython"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Request CPython 3.12 uv_snapshot!(context.filters(), context.python_list().arg("cpython@3.12"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] ----- stderr ----- "); // Request CPython 3.12 via partial key syntax uv_snapshot!(context.filters(), context.python_list().arg("cpython-3.12"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] ----- stderr ----- "); // Request CPython 3.12 for the current platform let os = Os::from_env(); let arch = Arch::from_env(); uv_snapshot!(context.filters(), context.python_list().arg(format!("cpython-3.12-{os}-{arch}")), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] ----- stderr ----- "); // Request PyPy (which should be missing) uv_snapshot!(context.filters(), context.python_list().arg("pypy"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); // Swap the order of the Python versions context.python_versions.reverse(); uv_snapshot!(context.filters(), context.python_list(), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Request Python 3.11 uv_snapshot!(context.filters(), context.python_list().arg("3.11"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); } #[test] fn python_list_pin() { let context: TestContext = TestContext::new_with_versions(&["3.11", "3.12"]) .with_filtered_python_symlinks() .with_filtered_python_keys() .with_collapsed_whitespace(); // Pin to a version uv_snapshot!(context.filters(), context.python_pin().arg("3.12"), @r###" success: true exit_code: 0 ----- stdout ----- Pinned `.python-version` to `3.12` ----- stderr ----- "###); // The pin should not affect the listing uv_snapshot!(context.filters(), context.python_list(), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // So `--no-config` has no effect uv_snapshot!(context.filters(), context.python_list().arg("--no-config"), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); } #[test] fn python_list_venv() { let context: TestContext = TestContext::new_with_versions(&["3.11", "3.12"]) .with_filtered_python_symlinks() .with_filtered_python_keys() .with_filtered_exe_suffix() .with_filtered_python_names() .with_filtered_virtualenv_bin() .with_collapsed_whitespace(); // Create a virtual environment uv_snapshot!(context.filters(), context.venv().arg("--python").arg("3.12").arg("-q"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "###); // We should not display the virtual environment uv_snapshot!(context.filters(), context.python_list(), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Same if the `VIRTUAL_ENV` is not set (the test context includes it by default) uv_snapshot!(context.filters(), context.python_list().env_remove(EnvVars::VIRTUAL_ENV), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); } #[cfg(unix)] #[test] fn python_list_unsupported_version() { let context: TestContext = TestContext::new_with_versions(&["3.12"]) .with_filtered_python_symlinks() .with_filtered_python_keys(); // Request a low version uv_snapshot!(context.filters(), context.python_list().arg("3.6"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Invalid version request: Python <3.7 is not supported but 3.6 was requested. "); // Request a low version with a patch uv_snapshot!(context.filters(), context.python_list().arg("3.6.9"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Invalid version request: Python <3.7 is not supported but 3.6.9 was requested. "); // Request a really low version uv_snapshot!(context.filters(), context.python_list().arg("2.6"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Invalid version request: Python <3.7 is not supported but 2.6 was requested. "); // Request a really low version with a patch uv_snapshot!(context.filters(), context.python_list().arg("2.6.8"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Invalid version request: Python <3.7 is not supported but 2.6.8 was requested. "); // Request a future version uv_snapshot!(context.filters(), context.python_list().arg("4.2"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); // Request a low version with a range uv_snapshot!(context.filters(), context.python_list().arg("<3.0"), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); // Request free-threaded Python on unsupported version uv_snapshot!(context.filters(), context.python_list().arg("3.12t"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Invalid version request: Python <3.13 does not support free-threading but 3.12+freethreaded was requested. "); } #[test] fn python_list_duplicate_path_entries() { let context: TestContext = TestContext::new_with_versions(&["3.11", "3.12"]) .with_filtered_python_symlinks() .with_filtered_python_keys() .with_collapsed_whitespace(); // Construct a `PATH` with all entries duplicated let path = std::env::join_paths( std::env::split_paths(&context.python_path()) .chain(std::env::split_paths(&context.python_path())), ) .unwrap(); uv_snapshot!(context.filters(), context.python_list().env(EnvVars::UV_TEST_PYTHON_PATH, &path), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); #[cfg(unix)] { // Construct a `PATH` with symlinks let path = std::env::join_paths(std::env::split_paths(&context.python_path()).chain( std::env::split_paths(&context.python_path()).map(|path| { let dst = format!("{}-link", path.display()); fs_err::os::unix::fs::symlink(&path, &dst).unwrap(); std::path::PathBuf::from(dst) }), )) .unwrap(); uv_snapshot!(context.filters(), context.python_list().env(EnvVars::UV_TEST_PYTHON_PATH, &path), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12] cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11] ----- stderr ----- "); // Reverse the order so the symlinks are first let path = std::env::join_paths( { let mut paths = std::env::split_paths(&path).collect::<Vec<_>>(); paths.reverse(); paths } .iter(), ) .unwrap(); uv_snapshot!(context.filters(), context.python_list().env(EnvVars::UV_TEST_PYTHON_PATH, &path), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.12.[X]-[PLATFORM] [PYTHON-3.12]-link/python3 cpython-3.11.[X]-[PLATFORM] [PYTHON-3.11]-link/python3 ----- stderr ----- "); } } #[test] fn python_list_downloads() { let context: TestContext = TestContext::new_with_versions(&[]).with_filtered_python_keys(); // We do not test showing all interpreters — as it differs per platform // Instead, we choose a Python version where our available distributions are stable // Test the default display, which requires reverting the test context disabling Python downloads uv_snapshot!(context.filters(), context.python_list().arg("3.10").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] <download available> pypy-3.10.16-[PLATFORM] <download available> graalpy-3.10.0-[PLATFORM] <download available> ----- stderr ----- "); // Show patch versions uv_snapshot!(context.filters(), context.python_list().arg("3.10").arg("--all-versions").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] <download available> cpython-3.10.18-[PLATFORM] <download available> cpython-3.10.17-[PLATFORM] <download available> cpython-3.10.16-[PLATFORM] <download available> cpython-3.10.15-[PLATFORM] <download available> cpython-3.10.14-[PLATFORM] <download available> cpython-3.10.13-[PLATFORM] <download available> cpython-3.10.12-[PLATFORM] <download available> cpython-3.10.11-[PLATFORM] <download available> cpython-3.10.9-[PLATFORM] <download available> cpython-3.10.8-[PLATFORM] <download available> cpython-3.10.7-[PLATFORM] <download available> cpython-3.10.6-[PLATFORM] <download available> cpython-3.10.5-[PLATFORM] <download available> cpython-3.10.4-[PLATFORM] <download available> cpython-3.10.3-[PLATFORM] <download available> cpython-3.10.2-[PLATFORM] <download available> cpython-3.10.0-[PLATFORM] <download available> pypy-3.10.16-[PLATFORM] <download available> pypy-3.10.14-[PLATFORM] <download available> pypy-3.10.13-[PLATFORM] <download available> pypy-3.10.12-[PLATFORM] <download available> graalpy-3.10.0-[PLATFORM] <download available> ----- stderr ----- "); } #[test] #[cfg(feature = "python-managed")] fn python_list_downloads_installed() { use assert_cmd::assert::OutputAssertExt; let context: TestContext = TestContext::new_with_versions(&[]) .with_filtered_python_keys() .with_filtered_python_install_bin() .with_filtered_python_names() .with_managed_python_dirs(); // We do not test showing all interpreters — as it differs per platform // Instead, we choose a Python version where our available distributions are stable // First, the download is shown as available uv_snapshot!(context.filters(), context.python_list().arg("3.10").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] <download available> pypy-3.10.16-[PLATFORM] <download available> graalpy-3.10.0-[PLATFORM] <download available> ----- stderr ----- "); // TODO(zanieb): It'd be nice to test `--show-urls` here too but we need special filtering for // the URL // But not if `--only-installed` is used uv_snapshot!(context.filters(), context.python_list().arg("3.10").arg("--only-installed").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); // Install a Python version context.python_install().arg("3.10").assert().success(); // Then, it should be listed as installed instead of available uv_snapshot!(context.filters(), context.python_list().arg("3.10").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] managed/cpython-3.10.19-[PLATFORM]/[INSTALL-BIN]/[PYTHON] pypy-3.10.16-[PLATFORM] <download available> graalpy-3.10.0-[PLATFORM] <download available> ----- stderr ----- "); // But, the display should be reverted if `--only-downloads` is used uv_snapshot!(context.filters(), context.python_list().arg("3.10").arg("--only-downloads").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] <download available> pypy-3.10.16-[PLATFORM] <download available> graalpy-3.10.0-[PLATFORM] <download available> ----- stderr ----- "); // And should not be shown if `--no-managed-python` is used uv_snapshot!(context.filters(), context.python_list().arg("3.10").arg("--no-managed-python").env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- "); } #[tokio::test] async fn python_list_remote_python_downloads_json_url() -> Result<()> { let context: TestContext = TestContext::new_with_versions(&[]); let server = MockServer::start().await; let remote_json = r#" { "cpython-3.14.0-darwin-aarch64-none": { "name": "cpython", "arch": { "family": "aarch64", "variant": null }, "os": "darwin", "libc": "none", "major": 3, "minor": 14, "patch": 0, "prerelease": "", "url": "https://custom.com/cpython-3.14.0-darwin-aarch64-none.tar.gz", "sha256": "c3223d5924a0ed0ef5958a750377c362d0957587f896c0f6c635ae4b39e0f337", "variant": null, "build": "20251028" }, "cpython-3.13.2+freethreaded-linux-powerpc64le-gnu": { "name": "cpython", "arch": { "family": "powerpc64le", "variant": null }, "os": "linux", "libc": "gnu", "major": 3, "minor": 13, "patch": 2, "prerelease": "", "url": "https://custom.com/ccpython-3.13.2+freethreaded-linux-powerpc64le-gnu.tar.gz", "sha256": "6ae8fa44cb2edf4ab49cff1820b53c40c10349c0f39e11b8cd76ce7f3e7e1def", "variant": "freethreaded", "build": "20250317" } } "#; Mock::given(method("GET")) .and(path("/")) .respond_with(ResponseTemplate::new(200).set_body_raw(remote_json, "application/json")) .mount(&server) .await; Mock::given(method("GET")) .and(path("/invalid")) .respond_with(ResponseTemplate::new(200).set_body_raw("{", "application/json")) .mount(&server) .await; // Test showing all interpreters from the remote JSON URL uv_snapshot!(context .python_list() .env_remove(EnvVars::UV_PYTHON_DOWNLOADS) .arg("--all-versions") .arg("--all-platforms") .arg("--all-arches") .arg("--show-urls") .arg("--python-downloads-json-url").arg(server.uri()), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.14.0-macos-aarch64-none https://custom.com/cpython-3.14.0-darwin-aarch64-none.tar.gz cpython-3.13.2+freethreaded-linux-powerpc64le-gnu https://custom.com/ccpython-3.13.2+freethreaded-linux-powerpc64le-gnu.tar.gz ----- stderr ----- "); // test invalid URL path uv_snapshot!(context.filters(), context .python_list() .env_remove(EnvVars::UV_PYTHON_DOWNLOADS) .arg("--python-downloads-json-url").arg(format!("{}/404", server.uri())), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Error while fetching remote python downloads json from 'http://[LOCALHOST]/404' Caused by: Failed to download http://[LOCALHOST]/404 Caused by: HTTP status client error (404 Not Found) for url (http://[LOCALHOST]/404) "); // test invalid json uv_snapshot!(context.filters(), context .python_list() .env_remove(EnvVars::UV_PYTHON_DOWNLOADS) .arg("--python-downloads-json-url").arg(format!("{}/invalid", server.uri())), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Unable to parse the JSON Python download list at http://[LOCALHOST]/invalid Caused by: EOF while parsing an object at line 1 column 1 "); Ok(()) } #[test] fn python_list_with_mirrors() { let context: TestContext = TestContext::new_with_versions(&[]) .with_filtered_python_keys() .with_collapsed_whitespace() // Add filters to normalize file paths in URLs .with_filter(( r"(https://mirror\.example\.com/).*".to_string(), "$1[FILE-PATH]".to_string(), )) .with_filter(( r"(https://python-mirror\.example\.com/).*".to_string(), "$1[FILE-PATH]".to_string(), )) .with_filter(( r"(https://pypy-mirror\.example\.com/).*".to_string(), "$1[FILE-PATH]".to_string(), )) .with_filter(( r"(https://github\.com/astral-sh/python-build-standalone/releases/download/).*" .to_string(), "$1[FILE-PATH]".to_string(), )) .with_filter(( r"(https://downloads\.python\.org/pypy/).*".to_string(), "$1[FILE-PATH]".to_string(), )) .with_filter(( r"(https://github\.com/oracle/graalpython/releases/download/).*".to_string(), "$1[FILE-PATH]".to_string(), )); // Test with UV_PYTHON_INSTALL_MIRROR environment variable - verify mirror URL is used uv_snapshot!(context.filters(), context.python_list() .arg("cpython@3.10.19") .arg("--show-urls") .env(EnvVars::UV_PYTHON_INSTALL_MIRROR, "https://mirror.example.com") .env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] https://mirror.example.com/[FILE-PATH] ----- stderr ----- "); // Test with UV_PYPY_INSTALL_MIRROR environment variable - verify PyPy mirror URL is used uv_snapshot!(context.filters(), context.python_list() .arg("pypy@3.10") .arg("--show-urls") .env(EnvVars::UV_PYPY_INSTALL_MIRROR, "https://pypy-mirror.example.com") .env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- pypy-3.10.16-[PLATFORM] https://pypy-mirror.example.com/[FILE-PATH] ----- stderr ----- "); // Test with both mirror environment variables set uv_snapshot!(context.filters(), context.python_list() .arg("3.10") .arg("--show-urls") .env(EnvVars::UV_PYTHON_INSTALL_MIRROR, "https://python-mirror.example.com") .env(EnvVars::UV_PYPY_INSTALL_MIRROR, "https://pypy-mirror.example.com") .env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] https://python-mirror.example.com/[FILE-PATH] pypy-3.10.16-[PLATFORM] https://pypy-mirror.example.com/[FILE-PATH] graalpy-3.10.0-[PLATFORM] https://github.com/oracle/graalpython/releases/download/[FILE-PATH] ----- stderr ----- "); // Test without mirrors - verify default URLs are used uv_snapshot!(context.filters(), context.python_list() .arg("3.10") .arg("--show-urls") .env_remove(EnvVars::UV_PYTHON_DOWNLOADS), @r" success: true exit_code: 0 ----- stdout ----- cpython-3.10.19-[PLATFORM] https://github.com/astral-sh/python-build-standalone/releases/download/[FILE-PATH] pypy-3.10.16-[PLATFORM] https://downloads.python.org/pypy/[FILE-PATH] graalpy-3.10.0-[PLATFORM] https://github.com/oracle/graalpython/releases/download/[FILE-PATH] ----- stderr ----- "); }
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/tests/it/ecosystem.rs
crates/uv/tests/it/ecosystem.rs
use crate::common::{self, TestContext, get_bin}; use anyhow::Result; use insta::assert_snapshot; use std::path::Path; use std::process::Command; use uv_static::EnvVars; // These tests just run `uv lock` on an assorted of ecosystem // projects. // // The idea here is to provide a body of ecosystem projects that // let us very easily observe any changes to the actual resolution // produced in the lock file. /// We use a different exclude newer here because, at the time of /// creating these benchmarks, the `pyproject.toml` files from the /// projects wouldn't work with the exclude-newer value we use /// elsewhere (which is 2024-03-25 at time of writing). So Instead of /// bumping everything else, we just use our own here. static EXCLUDE_NEWER: &str = "2024-08-08T00:00:00Z"; // Source: https://github.com/astral-sh/packse/blob/737bc7008fa7825669ee50e90d9d0c26df32a016/pyproject.toml #[test] fn packse() -> Result<()> { lock_ecosystem_package("3.12", "packse") } // Source: https://github.com/konstin/github-wikidata-bot/blob/8218d20985eb480cb8633026f9dabc9e5ec4b5e3/pyproject.toml #[test] fn github_wikidata_bot() -> Result<()> { lock_ecosystem_package("3.12", "github-wikidata-bot") } // Source: https://github.com/psf/black/blob/9ff047a9575f105f659043f28573e1941e9cdfb3/pyproject.toml #[test] fn black() -> Result<()> { lock_ecosystem_package("3.12", "black") } // Source: https://github.com/home-assistant/core/blob/7c5fcec062e1d2cfaa794a169fafa629a70bbc9e/pyproject.toml #[test] fn home_assistant_core() -> Result<()> { lock_ecosystem_package("3.12", "home-assistant-core") } // Source: https://github.com/konstin/transformers/blob/da3c00433d93e43bf1e7360b1057e8c160e7978e/pyproject.toml #[test] #[cfg(unix)] // deepspeed fails on windows due to missing torch fn transformers() -> Result<()> { // Takes too long on non-Linux in CI. if !cfg!(target_os = "linux") && std::env::var_os(EnvVars::CI).is_some() { return Ok(()); } lock_ecosystem_package("3.12", "transformers") } // Source: https://github.com/konstin/warehouse/blob/baae127d90417104c8dee3fdd3855e2ba17aa428/pyproject.toml #[test] fn warehouse() -> Result<()> { // Also, takes too long on non-Linux in CI. if !cfg!(target_os = "linux") && std::env::var_os(EnvVars::CI).is_some() { return Ok(()); } lock_ecosystem_package("3.11", "warehouse") } // Source: https://github.com/saleor/saleor/blob/6e6f3eee4f6a33b64c3d05348215062ca732c1ca/pyproject.toml #[test] fn saleor() -> Result<()> { lock_ecosystem_package("3.12", "saleor") } // Currently ignored because the project doesn't build with `uv` yet. // // Source: https://github.com/apache/airflow/blob/c55438d9b2eb9b6680641eefdd0cbc67a28d1d29/pyproject.toml #[test] #[ignore = "Airflow doesn't build with `uv` yet"] fn airflow() -> Result<()> { lock_ecosystem_package("3.12", "airflow") } /// Does a lock on the given ecosystem package for the given name. That /// is, there should be a directory at `./test/ecosystem/{name}` from the /// root of the `uv` repository. fn lock_ecosystem_package(python_version: &str, name: &str) -> Result<()> { let context = TestContext::new(python_version); context.copy_ecosystem_project(name); // Cache source distribution builds to speed up the tests. let cache_dir = std::path::absolute(Path::new("../../target/ecosystem-test-caches").join(name))?; // Custom command since we need to change the cache dir. let mut command = Command::new(get_bin()); command .arg("lock") .arg("--cache-dir") .arg(&cache_dir) // When running the tests in a venv, ignore that venv, otherwise we'll capture warnings. .env_remove(EnvVars::VIRTUAL_ENV) .env(EnvVars::UV_NO_WRAP, "1") .env(EnvVars::HOME, context.home_dir.as_os_str()) .env(EnvVars::UV_PYTHON_INSTALL_DIR, "") .env(EnvVars::UV_TEST_PYTHON_PATH, context.python_path()) .env(EnvVars::UV_EXCLUDE_NEWER, EXCLUDE_NEWER) .current_dir(context.temp_dir.path()); let (snapshot, _) = common::run_and_format( &mut command, context.filters(), name, Some(common::WindowsFilters::Platform), None, ); let lock = context.read("uv.lock"); insta::with_settings!({ filters => context.filters(), }, { assert_snapshot!(format!("{name}-lock-file"), lock); }); assert_snapshot!(format!("{name}-uv-lock-output"), snapshot); 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/tests/it/pip_sync.rs
crates/uv/tests/it/pip_sync.rs
use std::env::consts::EXE_SUFFIX; use anyhow::Result; use assert_cmd::prelude::*; use assert_fs::fixture::ChildPath; use assert_fs::prelude::*; use fs_err as fs; use indoc::indoc; use predicates::Predicate; use url::Url; use crate::common::{TestContext, download_to_disk, site_packages_path, uv_snapshot}; use uv_fs::{Simplified, copy_dir_all}; use uv_static::EnvVars; #[test] fn missing_requirements_txt() { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: File not found: `requirements.txt` "###); requirements_txt.assert(predicates::path::missing()); } #[test] fn missing_venv() -> Result<()> { let context = TestContext::new("3.12") .with_filtered_virtualenv_bin() .with_filtered_python_names(); let requirements = context.temp_dir.child("requirements.txt"); requirements.write_str("anyio")?; fs::remove_dir_all(&context.venv)?; uv_snapshot!(context.filters(), context.pip_sync().arg("requirements.txt"), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: Failed to inspect Python interpreter from active virtual environment at `.venv/[BIN]/[PYTHON]` Caused by: Python interpreter not found at `[VENV]/[BIN]/[PYTHON]` "); assert!(predicates::path::missing().eval(&context.venv)); // If not "active", we hint to create one uv_snapshot!(context.filters(), context.pip_sync().arg("requirements.txt").env_remove(EnvVars::VIRTUAL_ENV), @r" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: No virtual environment found; run `uv venv` to create an environment, or pass `--system` to install into a non-virtual environment "); assert!(predicates::path::missing().eval(&context.venv)); Ok(()) } #[test] fn missing_system() -> Result<()> { let context = TestContext::new_with_versions(&[]); let requirements = context.temp_dir.child("requirements.txt"); requirements.write_str("anyio")?; uv_snapshot!(context.filters(), context.pip_sync().arg("requirements.txt").arg("--system"), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: No system Python installation found "###); Ok(()) } /// Install a package into a virtual environment using the default link semantics. (On macOS, /// this using `clone` semantics.) #[test] fn install() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + markupsafe==2.1.3 "### ); // Counterpart for the `compile()` test. assert!( !context .site_packages() .join("markupsafe") .join("__pycache__") .join("__init__.cpython-312.pyc") .exists() ); context .assert_command("from markupsafe import Markup") .success(); // Removing the cache shouldn't invalidate the virtual environment. fs::remove_dir_all(context.cache_dir.path())?; context .assert_command("from markupsafe import Markup") .success(); Ok(()) } /// Install a package into a virtual environment using copy semantics. #[test] fn install_copy() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--link-mode") .arg("copy") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + markupsafe==2.1.3 "### ); context .assert_command("from markupsafe import Markup") .success(); // Removing the cache shouldn't invalidate the virtual environment. fs::remove_dir_all(context.cache_dir.path())?; context .assert_command("from markupsafe import Markup") .success(); Ok(()) } /// Install a package into a virtual environment using hardlink semantics. #[test] fn install_hardlink() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--link-mode") .arg("hardlink") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + markupsafe==2.1.3 "### ); context .assert_command("from markupsafe import Markup") .success(); // Removing the cache shouldn't invalidate the virtual environment. fs::remove_dir_all(context.cache_dir.path())?; context .assert_command("from markupsafe import Markup") .success(); Ok(()) } /// Install a package into a virtual environment using symlink semantics. #[test] #[cfg(unix)] // Windows does not allow symlinks by default fn install_symlink() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--link-mode") .arg("symlink") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + markupsafe==2.1.3 "### ); context .assert_command("from markupsafe import Markup") .success(); // Removing the cache _should_ invalidate the virtual environment. fs::remove_dir_all(context.cache_dir.path())?; context .assert_command("from markupsafe import Markup") .failure(); Ok(()) } /// Reject attempts to use symlink semantics with `--no-cache`. #[test] fn install_symlink_no_cache() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--link-mode") .arg("symlink") .arg("--no-cache") .arg("--strict"), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] error: Symlink-based installation is not supported with `--no-cache`. The created environment will be rendered unusable by the removal of the cache. "### ); Ok(()) } /// Install multiple packages into a virtual environment. #[test] fn install_many() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3\ntomli==2.0.1")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] Prepared 2 packages in [TIME] Installed 2 packages in [TIME] + markupsafe==2.1.3 + tomli==2.0.1 "### ); context .assert_command("from markupsafe import Markup; import tomli") .success(); Ok(()) } /// Attempt to install an already-installed package into a virtual environment. #[test] fn noop() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("MarkupSafe==2.1.3")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Audited 1 package in [TIME] "### ); context .assert_command("from markupsafe import Markup") .success(); Ok(()) } /// Attempt to sync an empty set of requirements. #[test] fn pip_sync_empty() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.touch()?; uv_snapshot!(context.pip_sync() .arg("requirements.txt"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- warning: Requirements file `requirements.txt` does not contain any dependencies No requirements found (hint: use `--allow-empty-requirements` to clear the environment) "### ); uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--allow-empty-requirements"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- warning: Requirements file `requirements.txt` does not contain any dependencies Resolved in [TIME] Audited in [TIME] "### ); // Install a package. requirements_txt.write_str("iniconfig==2.0.0")?; context .pip_sync() .arg("requirements.txt") .assert() .success(); // Now, syncing should remove the package. requirements_txt.write_str("")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--allow-empty-requirements"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- warning: Requirements file `requirements.txt` does not contain any dependencies Resolved in [TIME] Uninstalled 1 package in [TIME] - iniconfig==2.0.0 "### ); Ok(()) } /// Install a package into a virtual environment, then install the same package into a different /// virtual environment. #[test] fn link() -> Result<()> { // Sync `anyio` into the first virtual environment. let context1 = TestContext::new("3.12"); let requirements_txt = context1.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0")?; context1 .pip_sync() .arg(requirements_txt.path()) .arg("--strict") .assert() .success(); // Create a separate virtual environment, but reuse the same cache. let context2 = TestContext::new("3.12"); let mut cmd = context1.pip_sync(); cmd.env(EnvVars::VIRTUAL_ENV, context2.venv.as_os_str()) .current_dir(&context2.temp_dir); uv_snapshot!(cmd .arg(requirements_txt.path()) .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Installed 1 package in [TIME] + iniconfig==2.0.0 "### ); context2 .python_command() .arg("-c") .arg("import iniconfig") .current_dir(&context2.temp_dir) .assert() .success(); Ok(()) } /// Install a package into a virtual environment, then sync the virtual environment with a /// different requirements file. #[test] fn add_remove() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("tomli==2.0.1")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Uninstalled 1 package in [TIME] Installed 1 package in [TIME] - iniconfig==2.0.0 + tomli==2.0.1 "### ); context.assert_command("import tomli").success(); context.assert_command("import markupsafe").failure(); Ok(()) } /// Install a package into a virtual environment, then install a second package into the same /// virtual environment. #[test] fn install_sequential() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0\ntomli==2.0.1")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + tomli==2.0.1 "### ); context .assert_command("import iniconfig; import tomli") .success(); Ok(()) } /// Install a package into a virtual environment, then install a second package into the same /// virtual environment. #[test] fn upgrade() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("tomli==2.0.0")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("tomli==2.0.1")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Uninstalled 1 package in [TIME] Installed 1 package in [TIME] - tomli==2.0.0 + tomli==2.0.1 "### ); context.assert_command("import tomli").success(); Ok(()) } /// Install a package into a virtual environment from a URL. #[test] fn install_url() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug @ https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + werkzeug==2.0.0 (from https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl) "### ); context.assert_command("import werkzeug").success(); Ok(()) } /// Install a package into a virtual environment from a Git repository. #[test] #[cfg(feature = "git")] fn install_git_commit() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("uv-public-pypackage @ git+https://github.com/astral-test/uv-public-pypackage@b270df1a2fb5d012294e9aaf05e7e0bab1e6a389")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + uv-public-pypackage==0.1.0 (from git+https://github.com/astral-test/uv-public-pypackage@b270df1a2fb5d012294e9aaf05e7e0bab1e6a389) "### ); context .assert_command("import uv_public_pypackage") .success(); Ok(()) } /// Install a package into a virtual environment from a Git repository. #[test] #[cfg(feature = "git")] fn install_git_tag() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str( "uv-public-pypackage @ git+https://github.com/astral-test/uv-public-pypackage@test-tag", )?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + uv-public-pypackage==0.1.0 (from git+https://github.com/astral-test/uv-public-pypackage@0dacfd662c64cb4ceb16e6cf65a157a8b715b979) "### ); context .assert_command("import uv_public_pypackage") .success(); Ok(()) } /// Install two packages from the same Git repository. #[test] #[cfg(feature = "git")] fn install_git_subdirectories() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("example-pkg-a @ git+https://github.com/pypa/sample-namespace-packages.git@df7530eeb8fa0cb7dbb8ecb28363e8e36bfa2f45#subdirectory=pkg_resources/pkg_a\nexample-pkg-b @ git+https://github.com/pypa/sample-namespace-packages.git@df7530eeb8fa0cb7dbb8ecb28363e8e36bfa2f45#subdirectory=pkg_resources/pkg_b")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 2 packages in [TIME] Prepared 2 packages in [TIME] Installed 2 packages in [TIME] + example-pkg-a==1 (from git+https://github.com/pypa/sample-namespace-packages.git@df7530eeb8fa0cb7dbb8ecb28363e8e36bfa2f45#subdirectory=pkg_resources/pkg_a) + example-pkg-b==1 (from git+https://github.com/pypa/sample-namespace-packages.git@df7530eeb8fa0cb7dbb8ecb28363e8e36bfa2f45#subdirectory=pkg_resources/pkg_b) "### ); context.assert_command("import example_pkg").success(); context.assert_command("import example_pkg.a").success(); context.assert_command("import example_pkg.b").success(); Ok(()) } /// Install a source distribution into a virtual environment. #[test] fn install_sdist() -> Result<()> { let context = TestContext::new("3.12").with_exclude_newer("2025-01-29T00:00:00Z"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("source-distribution==0.0.1")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + source-distribution==0.0.1 "### ); context .assert_command("import source_distribution") .success(); Ok(()) } /// Install a source distribution into a virtual environment. #[test] fn install_sdist_url() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("source-distribution @ https://files.pythonhosted.org/packages/10/1f/57aa4cce1b1abf6b433106676e15f9fa2c92ed2bd4cf77c3b50a9e9ac773/source_distribution-0.0.1.tar.gz")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + source-distribution==0.0.1 (from https://files.pythonhosted.org/packages/10/1f/57aa4cce1b1abf6b433106676e15f9fa2c92ed2bd4cf77c3b50a9e9ac773/source_distribution-0.0.1.tar.gz) "### ); context .assert_command("import source_distribution") .success(); Ok(()) } /// Install a package with source archive format `.tar.bz2`. #[test] fn install_sdist_archive_type_bz2() -> Result<()> { let context = TestContext::new("3.9"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str(&format!( "bz2 @ {}", context .workspace_root .join("test/links/bz2-1.0.0.tar.bz2") .display() ))?; uv_snapshot!(context.filters(), context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + bz2==1.0.0 (from file://[WORKSPACE]/test/links/bz2-1.0.0.tar.bz2) "### ); Ok(()) } /// Attempt to re-install a package into a virtual environment from a URL. The second install /// should be a no-op. #[test] fn install_url_then_install_url() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug @ https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Audited 1 package in [TIME] "### ); context.assert_command("import werkzeug").success(); Ok(()) } /// Install a package via a URL, then via a registry version. The second install _should_ remove the /// URL-based version, but doesn't right now. #[test] fn install_url_then_install_version() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug @ https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug==2.0.0")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Audited 1 package in [TIME] "### ); context.assert_command("import werkzeug").success(); Ok(()) } /// Install a package via a registry version, then via a direct URL version. The second install /// should remove the registry-based version. #[test] fn install_version_then_install_url() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug==2.0.0")?; context .pip_sync() .arg("requirements.txt") .arg("--strict") .assert() .success(); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("werkzeug @ https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Uninstalled 1 package in [TIME] Installed 1 package in [TIME] - werkzeug==2.0.0 + werkzeug==2.0.0 (from https://files.pythonhosted.org/packages/ff/1d/960bb4017c68674a1cb099534840f18d3def3ce44aed12b5ed8b78e0153e/Werkzeug-2.0.0-py3-none-any.whl) "### ); context.assert_command("import werkzeug").success(); Ok(()) } /// Test that we select the last 3.8 compatible numpy version instead of trying to compile an /// incompatible sdist <https://github.com/astral-sh/uv/issues/388> #[cfg(feature = "python-eol")] #[test] fn install_numpy_py38() -> Result<()> { let context = TestContext::new("3.8"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("numpy")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + numpy==1.24.4 "### ); context.assert_command("import numpy").success(); Ok(()) } /// Attempt to install a package without using a remote index. #[test] fn install_no_index() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--no-index") .arg("--strict"), @r###" success: false exit_code: 1 ----- stdout ----- ----- stderr ----- × No solution found when resolving dependencies: ╰─▶ Because iniconfig was not found in the provided package locations and you require iniconfig==2.0.0, we can conclude that your requirements are unsatisfiable. hint: Packages were unavailable because index lookups were disabled and no additional package locations were provided (try: `--find-links <uri>`) "### ); context.assert_command("import iniconfig").failure(); Ok(()) } /// Attempt to install a package without using a remote index /// after a previous successful installation. #[test] fn install_no_index_cached() -> Result<()> { let context = TestContext::new("3.12"); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str("iniconfig==2.0.0")?; uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + iniconfig==2.0.0 "### ); context.assert_command("import iniconfig").success(); context.pip_uninstall().arg("iniconfig").assert().success(); uv_snapshot!(context.pip_sync() .arg("requirements.txt") .arg("--no-index") .arg("--strict"), @r###" success: false exit_code: 1 ----- stdout ----- ----- stderr ----- × No solution found when resolving dependencies: ╰─▶ Because iniconfig was not found in the provided package locations and you require iniconfig==2.0.0, we can conclude that your requirements are unsatisfiable. hint: Packages were unavailable because index lookups were disabled and no additional package locations were provided (try: `--find-links <uri>`) "### ); context.assert_command("import iniconfig").failure(); Ok(()) } #[test] fn warn_on_yanked() -> Result<()> { let context = TestContext::new("3.12"); // This version is yanked. let requirements_in = context.temp_dir.child("requirements.txt"); requirements_in.write_str("colorama==0.4.2")?; uv_snapshot!(context.filters(), windows_filters=false, context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + colorama==0.4.2 warning: `colorama==0.4.2` is yanked (reason: "Bad build, missing files, will not install") "### ); Ok(()) } #[test] fn warn_on_yanked_dry_run() -> Result<()> { let context = TestContext::new("3.12"); // This version is yanked. let requirements_in = context.temp_dir.child("requirements.txt"); requirements_in.write_str("colorama==0.4.2")?; uv_snapshot!(context.filters(), windows_filters=false, context.pip_sync() .arg("requirements.txt") .arg("--dry-run") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Would download 1 package Would install 1 package + colorama==0.4.2 warning: `colorama==0.4.2` is yanked (reason: "Bad build, missing files, will not install") "### ); Ok(()) } /// Resolve a local wheel. #[test] fn install_local_wheel() -> Result<()> { let context = TestContext::new("3.12"); // Download a wheel. let archive = context.temp_dir.child("tomli-2.0.1-py3-none-any.whl"); download_to_disk( "https://files.pythonhosted.org/packages/97/75/10a9ebee3fd790d20926a90a2547f0bf78f371b2f13aa822c759680ca7b9/tomli-2.0.1-py3-none-any.whl", &archive, ); let requirements_txt = context.temp_dir.child("requirements.txt"); requirements_txt.write_str(&format!( "tomli @ {}", Url::from_file_path(archive.path()).unwrap() ))?; uv_snapshot!(context.filters(), context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + tomli==2.0.1 (from file://[TEMP_DIR]/tomli-2.0.1-py3-none-any.whl) "### ); context.assert_command("import tomli").success(); // Create a new virtual environment. context.reset_venv(); // Reinstall. The wheel should come from the cache, so there shouldn't be a "download". uv_snapshot!(context.filters(), context.pip_sync() .arg("requirements.txt") .arg("--strict") , @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Installed 1 package in [TIME] + tomli==2.0.1 (from file://[TEMP_DIR]/tomli-2.0.1-py3-none-any.whl) "### ); context.assert_command("import tomli").success(); // Create a new virtual environment. context.reset_venv(); // "Modify" the wheel. // The `filetime` crate works on Windows unlike the std. filetime::set_file_mtime(&archive, filetime::FileTime::now()).unwrap(); // Reinstall. The wheel should be "downloaded" again. uv_snapshot!(context.filters(), context.pip_sync() .arg("requirements.txt") .arg("--strict") , @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 1 package in [TIME] Prepared 1 package in [TIME] Installed 1 package in [TIME] + tomli==2.0.1 (from file://[TEMP_DIR]/tomli-2.0.1-py3-none-any.whl) "### ); context.assert_command("import tomli").success(); // "Modify" the wheel. filetime::set_file_mtime(&archive, filetime::FileTime::now()).unwrap(); // Reinstall into the same virtual environment. The wheel should be reinstalled. uv_snapshot!(context.filters(), context.pip_sync() .arg("requirements.txt") .arg("--strict"), @r###" success: true exit_code: 0
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/tests/it/tool_uninstall.rs
crates/uv/tests/it/tool_uninstall.rs
use assert_cmd::assert::OutputAssertExt; use assert_fs::fixture::PathChild; use uv_static::EnvVars; use crate::common::{TestContext, uv_snapshot}; #[test] fn tool_uninstall() { let context = TestContext::new("3.12").with_filtered_exe_suffix(); let tool_dir = context.temp_dir.child("tools"); let bin_dir = context.temp_dir.child("bin"); // Install `black` context .tool_install() .arg("black==24.2.0") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .assert() .success(); uv_snapshot!(context.filters(), context.tool_uninstall().arg("black") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Uninstalled 2 executables: black, blackd "###); // After uninstalling the tool, it shouldn't be listed. uv_snapshot!(context.filters(), context.tool_list() .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- No tools installed "###); // After uninstalling the tool, we should be able to reinstall it. uv_snapshot!(context.filters(), context.tool_install() .arg("black==24.2.0") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .env(EnvVars::PATH, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Resolved 6 packages in [TIME] Installed 6 packages in [TIME] + black==24.2.0 + click==8.1.7 + mypy-extensions==1.0.0 + packaging==24.0 + pathspec==0.12.1 + platformdirs==4.2.0 Installed 2 executables: black, blackd "###); } #[test] fn tool_uninstall_multiple_names() { let context = TestContext::new("3.12").with_filtered_exe_suffix(); let tool_dir = context.temp_dir.child("tools"); let bin_dir = context.temp_dir.child("bin"); // Install `black` context .tool_install() .arg("black==24.2.0") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .assert() .success(); context .tool_install() .arg("ruff==0.3.4") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .assert() .success(); uv_snapshot!(context.filters(), context.tool_uninstall().arg("black").arg("ruff") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Uninstalled 3 executables: black, blackd, ruff "###); // After uninstalling the tool, it shouldn't be listed. uv_snapshot!(context.filters(), context.tool_list() .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- No tools installed "###); } #[test] fn tool_uninstall_not_installed() { let context = TestContext::new("3.12").with_filtered_exe_suffix(); let tool_dir = context.temp_dir.child("tools"); let bin_dir = context.temp_dir.child("bin"); uv_snapshot!(context.filters(), context.tool_uninstall().arg("black") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: false exit_code: 2 ----- stdout ----- ----- stderr ----- error: `black` is not installed "###); } #[test] fn tool_uninstall_missing_receipt() { let context = TestContext::new("3.12").with_filtered_exe_suffix(); let tool_dir = context.temp_dir.child("tools"); let bin_dir = context.temp_dir.child("bin"); // Install `black` context .tool_install() .arg("black==24.2.0") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .assert() .success(); fs_err::remove_file(tool_dir.join("black").join("uv-receipt.toml")).unwrap(); uv_snapshot!(context.filters(), context.tool_uninstall().arg("black") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Removed dangling environment for `black` "###); } #[test] fn tool_uninstall_all_missing_receipt() { let context = TestContext::new("3.12").with_filtered_exe_suffix(); let tool_dir = context.temp_dir.child("tools"); let bin_dir = context.temp_dir.child("bin"); // Install `black` context .tool_install() .arg("black==24.2.0") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) .assert() .success(); fs_err::remove_file(tool_dir.join("black").join("uv-receipt.toml")).unwrap(); uv_snapshot!(context.filters(), context.tool_uninstall().arg("--all") .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()), @r###" success: true exit_code: 0 ----- stdout ----- ----- stderr ----- Removed dangling environment for `black` "###); }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false