Rename Virtualenv and PythonPlatform structs (#2034)

## Summary

`PythonPlatform` only exists to format paths to directories within
virtual environments based on a root and an OS, so it's now
`VirtualenvLayout`.

`Virtualenv` is now used for non-virtual environment Pythons, so it's
now `PythonEnvironment`.
This commit is contained in:
Charlie Marsh 2024-02-28 10:04:55 -05:00 committed by GitHub
parent 02703281f0
commit 1ee28f78cd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 101 additions and 121 deletions

View file

@ -5,7 +5,7 @@ use camino::{FromPathError, Utf8Path};
use thiserror::Error; use thiserror::Error;
use platform_host::PlatformError; use platform_host::PlatformError;
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
pub use crate::bare::create_bare_venv; pub use crate::bare::create_bare_venv;
@ -52,12 +52,12 @@ pub fn create_venv(
interpreter: Interpreter, interpreter: Interpreter,
prompt: Prompt, prompt: Prompt,
extra_cfg: Vec<(String, String)>, extra_cfg: Vec<(String, String)>,
) -> Result<Virtualenv, Error> { ) -> Result<PythonEnvironment, Error> {
let location: &Utf8Path = location let location: &Utf8Path = location
.try_into() .try_into()
.map_err(|err: FromPathError| err.into_io_error())?; .map_err(|err: FromPathError| err.into_io_error())?;
let paths = create_bare_venv(location, &interpreter, prompt, extra_cfg)?; let paths = create_bare_venv(location, &interpreter, prompt, extra_cfg)?;
Ok(Virtualenv::from_interpreter( Ok(PythonEnvironment::from_interpreter(
interpreter, interpreter,
paths.root.as_std_path(), paths.root.as_std_path(),
)) ))

View file

@ -29,7 +29,7 @@ use tracing::{debug, info_span, instrument, Instrument};
use distribution_types::Resolution; use distribution_types::Resolution;
use pep508_rs::Requirement; use pep508_rs::Requirement;
use uv_fs::Normalized; use uv_fs::Normalized;
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
use uv_traits::{BuildContext, BuildKind, ConfigSettings, SetupPyStrategy, SourceBuildTrait}; use uv_traits::{BuildContext, BuildKind, ConfigSettings, SetupPyStrategy, SourceBuildTrait};
/// e.g. `pygraphviz/graphviz_wrap.c:3020:10: fatal error: graphviz/cgraph.h: No such file or directory` /// e.g. `pygraphviz/graphviz_wrap.c:3020:10: fatal error: graphviz/cgraph.h: No such file or directory`
@ -316,7 +316,7 @@ pub struct SourceBuild {
/// If performing a PEP 517 build, the backend to use. /// If performing a PEP 517 build, the backend to use.
pep517_backend: Option<Pep517Backend>, pep517_backend: Option<Pep517Backend>,
/// The virtual environment in which to build the source distribution. /// The virtual environment in which to build the source distribution.
venv: Virtualenv, venv: PythonEnvironment,
/// Populated if `prepare_metadata_for_build_wheel` was called. /// Populated if `prepare_metadata_for_build_wheel` was called.
/// ///
/// > If the build frontend has previously called prepare_metadata_for_build_wheel and depends /// > If the build frontend has previously called prepare_metadata_for_build_wheel and depends
@ -757,7 +757,7 @@ fn escape_path_for_python(path: &Path) -> String {
/// Not a method because we call it before the builder is completely initialized /// Not a method because we call it before the builder is completely initialized
async fn create_pep517_build_environment( async fn create_pep517_build_environment(
source_tree: &Path, source_tree: &Path,
venv: &Virtualenv, venv: &PythonEnvironment,
pep517_backend: &Pep517Backend, pep517_backend: &Pep517Backend,
build_context: &impl BuildContext, build_context: &impl BuildContext,
package_id: &str, package_id: &str,
@ -846,7 +846,7 @@ async fn create_pep517_build_environment(
/// It is the caller's responsibility to create an informative span. /// It is the caller's responsibility to create an informative span.
async fn run_python_script( async fn run_python_script(
venv: &Virtualenv, venv: &PythonEnvironment,
script: &str, script: &str,
source_tree: &Path, source_tree: &Path,
) -> Result<Output, Error> { ) -> Result<Output, Error> {

View file

@ -12,7 +12,7 @@ use uv_cache::{Cache, CacheArgs};
use uv_client::{FlatIndex, RegistryClientBuilder}; use uv_client::{FlatIndex, RegistryClientBuilder};
use uv_dispatch::BuildDispatch; use uv_dispatch::BuildDispatch;
use uv_installer::NoBinary; use uv_installer::NoBinary;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_resolver::InMemoryIndex; use uv_resolver::InMemoryIndex;
use uv_traits::{BuildContext, BuildKind, ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{BuildContext, BuildKind, ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -54,7 +54,7 @@ pub(crate) async fn build(args: BuildArgs) -> Result<PathBuf> {
let cache = Cache::try_from(args.cache_args)?; let cache = Cache::try_from(args.cache_args)?;
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = Virtualenv::from_env(platform, &cache)?; let venv = PythonEnvironment::from_virtualenv(platform, &cache)?;
let client = RegistryClientBuilder::new(cache.clone()).build(); let client = RegistryClientBuilder::new(cache.clone()).build();
let index_urls = IndexLocations::default(); let index_urls = IndexLocations::default();
let flat_index = FlatIndex::default(); let flat_index = FlatIndex::default();

View file

@ -21,7 +21,7 @@ use uv_client::{FlatIndex, RegistryClient, RegistryClientBuilder};
use uv_dispatch::BuildDispatch; use uv_dispatch::BuildDispatch;
use uv_distribution::RegistryWheelIndex; use uv_distribution::RegistryWheelIndex;
use uv_installer::{Downloader, NoBinary}; use uv_installer::{Downloader, NoBinary};
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_normalize::PackageName; use uv_normalize::PackageName;
use uv_resolver::{DistFinder, InMemoryIndex}; use uv_resolver::{DistFinder, InMemoryIndex};
use uv_traits::{BuildContext, ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{BuildContext, ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -56,7 +56,7 @@ pub(crate) async fn install_many(args: InstallManyArgs) -> Result<()> {
let cache = Cache::try_from(args.cache_args)?; let cache = Cache::try_from(args.cache_args)?;
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = Virtualenv::from_env(platform, &cache)?; let venv = PythonEnvironment::from_virtualenv(platform, &cache)?;
let client = RegistryClientBuilder::new(cache.clone()).build(); let client = RegistryClientBuilder::new(cache.clone()).build();
let index_locations = IndexLocations::default(); let index_locations = IndexLocations::default();
let flat_index = FlatIndex::default(); let flat_index = FlatIndex::default();
@ -112,7 +112,7 @@ async fn install_chunk(
build_dispatch: &BuildDispatch<'_>, build_dispatch: &BuildDispatch<'_>,
tags: &Tags, tags: &Tags,
client: &RegistryClient, client: &RegistryClient,
venv: &Virtualenv, venv: &PythonEnvironment,
index_locations: &IndexLocations, index_locations: &IndexLocations,
) -> Result<()> { ) -> Result<()> {
let resolution: Vec<_> = DistFinder::new( let resolution: Vec<_> = DistFinder::new(

View file

@ -16,7 +16,7 @@ use uv_cache::{Cache, CacheArgs};
use uv_client::{FlatIndex, FlatIndexClient, RegistryClientBuilder}; use uv_client::{FlatIndex, FlatIndexClient, RegistryClientBuilder};
use uv_dispatch::BuildDispatch; use uv_dispatch::BuildDispatch;
use uv_installer::NoBinary; use uv_installer::NoBinary;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_resolver::{InMemoryIndex, Manifest, Options, Resolver}; use uv_resolver::{InMemoryIndex, Manifest, Options, Resolver};
use uv_traits::{ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -55,7 +55,7 @@ pub(crate) async fn resolve_cli(args: ResolveCliArgs) -> Result<()> {
let cache = Cache::try_from(args.cache_args)?; let cache = Cache::try_from(args.cache_args)?;
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = Virtualenv::from_env(platform, &cache)?; let venv = PythonEnvironment::from_virtualenv(platform, &cache)?;
let index_locations = IndexLocations::new( let index_locations = IndexLocations::new(
Some(args.index_url), Some(args.index_url),
args.extra_index_url, args.extra_index_url,

View file

@ -18,7 +18,7 @@ use uv_cache::{Cache, CacheArgs};
use uv_client::{FlatIndex, OwnedArchive, RegistryClient, RegistryClientBuilder}; use uv_client::{FlatIndex, OwnedArchive, RegistryClient, RegistryClientBuilder};
use uv_dispatch::BuildDispatch; use uv_dispatch::BuildDispatch;
use uv_installer::NoBinary; use uv_installer::NoBinary;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_normalize::PackageName; use uv_normalize::PackageName;
use uv_resolver::InMemoryIndex; use uv_resolver::InMemoryIndex;
use uv_traits::{BuildContext, ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{BuildContext, ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -73,7 +73,7 @@ pub(crate) async fn resolve_many(args: ResolveManyArgs) -> Result<()> {
let total = requirements.len(); let total = requirements.len();
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = Virtualenv::from_env(platform, &cache)?; let venv = PythonEnvironment::from_virtualenv(platform, &cache)?;
let in_flight = InFlight::default(); let in_flight = InFlight::default();
let client = RegistryClientBuilder::new(cache.clone()).build(); let client = RegistryClientBuilder::new(cache.clone()).build();

View file

@ -16,7 +16,7 @@ use uv_build::{SourceBuild, SourceBuildContext};
use uv_cache::Cache; use uv_cache::Cache;
use uv_client::{FlatIndex, RegistryClient}; use uv_client::{FlatIndex, RegistryClient};
use uv_installer::{Downloader, Installer, NoBinary, Plan, Planner, Reinstall, SitePackages}; use uv_installer::{Downloader, Installer, NoBinary, Plan, Planner, Reinstall, SitePackages};
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
use uv_resolver::{InMemoryIndex, Manifest, Options, Resolver}; use uv_resolver::{InMemoryIndex, Manifest, Options, Resolver};
use uv_traits::{BuildContext, BuildKind, ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{BuildContext, BuildKind, ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -138,7 +138,7 @@ impl<'a> BuildContext for BuildDispatch<'a> {
fn install<'data>( fn install<'data>(
&'data self, &'data self,
resolution: &'data Resolution, resolution: &'data Resolution,
venv: &'data Virtualenv, venv: &'data PythonEnvironment,
) -> impl Future<Output = Result<()>> + Send + 'data { ) -> impl Future<Output = Result<()>> + Send + 'data {
async move { async move {
debug!( debug!(

View file

@ -3,17 +3,17 @@ use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use tracing::instrument; use tracing::instrument;
use distribution_types::CachedDist; use distribution_types::CachedDist;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
pub struct Installer<'a> { pub struct Installer<'a> {
venv: &'a Virtualenv, venv: &'a PythonEnvironment,
link_mode: install_wheel_rs::linker::LinkMode, link_mode: install_wheel_rs::linker::LinkMode,
reporter: Option<Box<dyn Reporter>>, reporter: Option<Box<dyn Reporter>>,
} }
impl<'a> Installer<'a> { impl<'a> Installer<'a> {
/// Initialize a new installer. /// Initialize a new installer.
pub fn new(venv: &'a Virtualenv) -> Self { pub fn new(venv: &'a PythonEnvironment) -> Self {
Self { Self {
venv, venv,
link_mode: install_wheel_rs::linker::LinkMode::default(), link_mode: install_wheel_rs::linker::LinkMode::default(),

View file

@ -16,7 +16,7 @@ use platform_tags::Tags;
use uv_cache::{ArchiveTimestamp, Cache, CacheBucket, CacheEntry, Timestamp, WheelCache}; use uv_cache::{ArchiveTimestamp, Cache, CacheBucket, CacheEntry, Timestamp, WheelCache};
use uv_distribution::{BuiltWheelIndex, RegistryWheelIndex}; use uv_distribution::{BuiltWheelIndex, RegistryWheelIndex};
use uv_fs::Normalized; use uv_fs::Normalized;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_normalize::PackageName; use uv_normalize::PackageName;
use uv_traits::NoBinary; use uv_traits::NoBinary;
@ -63,7 +63,7 @@ impl<'a> Planner<'a> {
no_binary: &NoBinary, no_binary: &NoBinary,
index_locations: &IndexLocations, index_locations: &IndexLocations,
cache: &Cache, cache: &Cache,
venv: &Virtualenv, venv: &PythonEnvironment,
tags: &Tags, tags: &Tags,
) -> Result<Plan> { ) -> Result<Plan> {
// Index all the already-downloaded wheels in the cache. // Index all the already-downloaded wheels in the cache.

View file

@ -11,7 +11,7 @@ use distribution_types::{InstalledDist, InstalledMetadata, InstalledVersion, Nam
use pep440_rs::{Version, VersionSpecifiers}; use pep440_rs::{Version, VersionSpecifiers};
use pep508_rs::{Requirement, VerbatimUrl}; use pep508_rs::{Requirement, VerbatimUrl};
use requirements_txt::EditableRequirement; use requirements_txt::EditableRequirement;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_normalize::PackageName; use uv_normalize::PackageName;
use crate::{is_dynamic, not_modified}; use crate::{is_dynamic, not_modified};
@ -21,7 +21,7 @@ use crate::{is_dynamic, not_modified};
/// Packages are indexed by both name and (for editable installs) URL. /// Packages are indexed by both name and (for editable installs) URL.
#[derive(Debug)] #[derive(Debug)]
pub struct SitePackages<'a> { pub struct SitePackages<'a> {
venv: &'a Virtualenv, venv: &'a PythonEnvironment,
/// The vector of all installed distributions. The `by_name` and `by_url` indices index into /// The vector of all installed distributions. The `by_name` and `by_url` indices index into
/// this vector. The vector may contain `None` values, which represent distributions that were /// this vector. The vector may contain `None` values, which represent distributions that were
/// removed from the virtual environment. /// removed from the virtual environment.
@ -36,7 +36,7 @@ pub struct SitePackages<'a> {
impl<'a> SitePackages<'a> { impl<'a> SitePackages<'a> {
/// Build an index of installed packages from the given Python executable. /// Build an index of installed packages from the given Python executable.
pub fn from_executable(venv: &'a Virtualenv) -> Result<SitePackages<'a>> { pub fn from_executable(venv: &'a PythonEnvironment) -> Result<SitePackages<'a>> {
let mut distributions: Vec<Option<InstalledDist>> = Vec::new(); let mut distributions: Vec<Option<InstalledDist>> = Vec::new();
let mut by_name = FxHashMap::default(); let mut by_name = FxHashMap::default();
let mut by_url = FxHashMap::default(); let mut by_url = FxHashMap::default();

View file

@ -18,15 +18,15 @@ use platform_tags::{Tags, TagsError};
use uv_cache::{Cache, CacheBucket, CachedByTimestamp, Freshness, Timestamp}; use uv_cache::{Cache, CacheBucket, CachedByTimestamp, Freshness, Timestamp};
use uv_fs::write_atomic_sync; use uv_fs::write_atomic_sync;
use crate::python_platform::PythonPlatform; use crate::python_environment::detect_virtual_env;
use crate::python_query::try_find_default_python; use crate::python_query::try_find_default_python;
use crate::virtual_env::detect_virtual_env; use crate::virtualenv_layout::VirtualenvLayout;
use crate::{find_requested_python, Error, PythonVersion}; use crate::{find_requested_python, Error, PythonVersion};
/// A Python executable and its associated platform markers. /// A Python executable and its associated platform markers.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Interpreter { pub struct Interpreter {
platform: PythonPlatform, platform: Platform,
markers: Box<MarkerEnvironment>, markers: Box<MarkerEnvironment>,
sysconfig_paths: SysconfigPaths, sysconfig_paths: SysconfigPaths,
prefix: PathBuf, prefix: PathBuf,
@ -48,7 +48,7 @@ impl Interpreter {
); );
Ok(Self { Ok(Self {
platform: PythonPlatform(platform), platform,
markers: Box::new(info.markers), markers: Box::new(info.markers),
sysconfig_paths: info.sysconfig_paths, sysconfig_paths: info.sysconfig_paths,
prefix: info.prefix, prefix: info.prefix,
@ -62,7 +62,7 @@ impl Interpreter {
// TODO(konstin): Find a better way mocking the fields // TODO(konstin): Find a better way mocking the fields
pub fn artificial(platform: Platform, markers: MarkerEnvironment) -> Self { pub fn artificial(platform: Platform, markers: MarkerEnvironment) -> Self {
Self { Self {
platform: PythonPlatform(platform), platform,
markers: Box::new(markers), markers: Box::new(markers),
sysconfig_paths: SysconfigPaths { sysconfig_paths: SysconfigPaths {
stdlib: PathBuf::from("/dev/null"), stdlib: PathBuf::from("/dev/null"),
@ -85,6 +85,7 @@ impl Interpreter {
/// Return a new [`Interpreter`] with the given virtual environment root. /// Return a new [`Interpreter`] with the given virtual environment root.
#[must_use] #[must_use]
pub(crate) fn with_venv_root(self, venv_root: PathBuf) -> Self { pub(crate) fn with_venv_root(self, venv_root: PathBuf) -> Self {
let layout = VirtualenvLayout::from_platform(&self.platform);
Self { Self {
// Given that we know `venv_root` is a virtualenv, and not an arbitrary Python // Given that we know `venv_root` is a virtualenv, and not an arbitrary Python
// interpreter, we can safely assume that the platform is the same as the host // interpreter, we can safely assume that the platform is the same as the host
@ -92,20 +93,14 @@ impl Interpreter {
// structure, which allows us to avoid querying the interpreter for the `sysconfig` // structure, which allows us to avoid querying the interpreter for the `sysconfig`
// paths. // paths.
sysconfig_paths: SysconfigPaths { sysconfig_paths: SysconfigPaths {
purelib: self purelib: layout.site_packages(&venv_root, self.python_tuple()),
.platform platlib: layout.site_packages(&venv_root, self.python_tuple()),
.venv_site_packages(&venv_root, self.python_tuple()), platstdlib: layout.platstdlib(&venv_root, self.python_tuple()),
platlib: self scripts: layout.scripts(&venv_root),
.platform data: layout.data(&venv_root),
.venv_site_packages(&venv_root, self.python_tuple()),
platstdlib: self
.platform
.venv_platstdlib_dir(&venv_root, self.python_tuple()),
scripts: self.platform.venv_scripts_dir(&venv_root),
data: self.platform.venv_data_dir(&venv_root),
..self.sysconfig_paths ..self.sysconfig_paths
}, },
sys_executable: self.platform.venv_python(&venv_root), sys_executable: layout.python_executable(&venv_root),
prefix: venv_root, prefix: venv_root,
..self ..self
} }
@ -192,10 +187,10 @@ impl Interpreter {
}; };
// Check if the venv Python matches. // Check if the venv Python matches.
let python_platform = PythonPlatform::from(platform.to_owned()); let python_platform = VirtualenvLayout::from_platform(platform);
if let Some(venv) = detect_virtual_env(&python_platform)? { if let Some(venv) = detect_virtual_env(&python_platform)? {
let executable = python_platform.venv_python(venv); let executable = python_platform.python_executable(venv);
let interpreter = Self::query(&executable, python_platform.0, cache)?; let interpreter = Self::query(&executable, platform.clone(), cache)?;
if version_matches(&interpreter) { if version_matches(&interpreter) {
return Ok(Some(interpreter)); return Ok(Some(interpreter));

View file

@ -6,16 +6,16 @@ use thiserror::Error;
pub use crate::cfg::PyVenvConfiguration; pub use crate::cfg::PyVenvConfiguration;
pub use crate::interpreter::Interpreter; pub use crate::interpreter::Interpreter;
pub use crate::python_environment::PythonEnvironment;
pub use crate::python_query::{find_default_python, find_requested_python}; pub use crate::python_query::{find_default_python, find_requested_python};
pub use crate::python_version::PythonVersion; pub use crate::python_version::PythonVersion;
pub use crate::virtual_env::Virtualenv;
mod cfg; mod cfg;
mod interpreter; mod interpreter;
mod python_platform; mod python_environment;
mod python_query; mod python_query;
mod python_version; mod python_version;
mod virtual_env; mod virtualenv_layout;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum Error { pub enum Error {

View file

@ -8,26 +8,26 @@ use uv_cache::Cache;
use uv_fs::{LockedFile, Normalized}; use uv_fs::{LockedFile, Normalized};
use crate::cfg::PyVenvConfiguration; use crate::cfg::PyVenvConfiguration;
use crate::python_platform::PythonPlatform; use crate::virtualenv_layout::VirtualenvLayout;
use crate::{find_default_python, find_requested_python, Error, Interpreter}; use crate::{find_default_python, find_requested_python, Error, Interpreter};
/// A Python executable and its associated platform markers. /// A Python environment, consisting of a Python [`Interpreter`] and a root directory.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Virtualenv { pub struct PythonEnvironment {
root: PathBuf, root: PathBuf,
interpreter: Interpreter, interpreter: Interpreter,
} }
impl Virtualenv { impl PythonEnvironment {
/// Create a [`Virtualenv`] for an existing virtual environment. /// Create a [`PythonEnvironment`] for an existing virtual environment.
pub fn from_env(platform: Platform, cache: &Cache) -> Result<Self, Error> { pub fn from_virtualenv(platform: Platform, cache: &Cache) -> Result<Self, Error> {
let platform = PythonPlatform::from(platform); let layout = VirtualenvLayout::from_platform(&platform);
let Some(venv) = detect_virtual_env(&platform)? else { let Some(venv) = detect_virtual_env(&layout)? else {
return Err(Error::VenvNotFound); return Err(Error::VenvNotFound);
}; };
let venv = fs_err::canonicalize(venv)?; let venv = fs_err::canonicalize(venv)?;
let executable = platform.venv_python(&venv); let executable = layout.python_executable(&venv);
let interpreter = Interpreter::query(&executable, platform.0, cache)?; let interpreter = Interpreter::query(&executable, platform, cache)?;
debug_assert!( debug_assert!(
interpreter.base_prefix() == interpreter.base_exec_prefix(), interpreter.base_prefix() == interpreter.base_exec_prefix(),
@ -42,7 +42,7 @@ impl Virtualenv {
}) })
} }
/// Create a [`Virtualenv`] for a new virtual environment, created with the given interpreter. /// Create a [`PythonEnvironment`] for a new virtual environment, created with the given interpreter.
pub fn from_interpreter(interpreter: Interpreter, venv: &Path) -> Self { pub fn from_interpreter(interpreter: Interpreter, venv: &Path) -> Self {
Self { Self {
interpreter: interpreter.with_venv_root(venv.to_path_buf()), interpreter: interpreter.with_venv_root(venv.to_path_buf()),
@ -50,7 +50,7 @@ impl Virtualenv {
} }
} }
/// Create a [`Virtualenv`] for a Python interpreter specifier (e.g., a path or a binary name). /// Create a [`PythonEnvironment`] for a Python interpreter specifier (e.g., a path or a binary name).
pub fn from_requested_python( pub fn from_requested_python(
python: &str, python: &str,
platform: &Platform, platform: &Platform,
@ -65,7 +65,7 @@ impl Virtualenv {
}) })
} }
/// Create a [`Virtualenv`] for the default Python interpreter. /// Create a [`PythonEnvironment`] for the default Python interpreter.
pub fn from_default_python(platform: &Platform, cache: &Cache) -> Result<Self, Error> { pub fn from_default_python(platform: &Platform, cache: &Cache) -> Result<Self, Error> {
let interpreter = find_default_python(platform, cache)?; let interpreter = find_default_python(platform, cache)?;
Ok(Self { Ok(Self {
@ -112,7 +112,7 @@ impl Virtualenv {
} }
/// Locate the current virtual environment. /// Locate the current virtual environment.
pub(crate) fn detect_virtual_env(target: &PythonPlatform) -> Result<Option<PathBuf>, Error> { pub(crate) fn detect_virtual_env(layout: &VirtualenvLayout) -> Result<Option<PathBuf>, Error> {
match ( match (
env::var_os("VIRTUAL_ENV").filter(|value| !value.is_empty()), env::var_os("VIRTUAL_ENV").filter(|value| !value.is_empty()),
env::var_os("CONDA_PREFIX").filter(|value| !value.is_empty()), env::var_os("CONDA_PREFIX").filter(|value| !value.is_empty()),
@ -148,7 +148,7 @@ pub(crate) fn detect_virtual_env(target: &PythonPlatform) -> Result<Option<PathB
if !dot_venv.join("pyvenv.cfg").is_file() { if !dot_venv.join("pyvenv.cfg").is_file() {
return Err(Error::MissingPyVenvCfg(dot_venv)); return Err(Error::MissingPyVenvCfg(dot_venv));
} }
let python = target.venv_python(&dot_venv); let python = layout.python_executable(&dot_venv);
if !python.is_file() { if !python.is_file() {
return Err(Error::BrokenVenv(dot_venv, python)); return Err(Error::BrokenVenv(dot_venv, python));
} }

View file

@ -1,23 +1,26 @@
use std::env::consts::EXE_SUFFIX; use std::env::consts::EXE_SUFFIX;
use std::ops::Deref;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use platform_host::{Os, Platform}; use platform_host::{Os, Platform};
/// A Python-aware wrapper around [`Platform`]. /// Construct paths to various locations inside a virtual environment based on the platform.
#[derive(Debug, Clone, Eq, PartialEq)] #[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct PythonPlatform(pub(crate) Platform); pub(crate) struct VirtualenvLayout<'a>(&'a Platform);
impl<'a> VirtualenvLayout<'a> {
/// Create a new [`VirtualenvLayout`] for the given platform.
pub(crate) fn from_platform(platform: &'a Platform) -> Self {
Self(platform)
}
impl PythonPlatform {
/// Returns the path to the `python` executable inside a virtual environment. /// Returns the path to the `python` executable inside a virtual environment.
pub(crate) fn venv_python(&self, venv_root: impl AsRef<Path>) -> PathBuf { pub(crate) fn python_executable(&self, venv_root: impl AsRef<Path>) -> PathBuf {
self.venv_scripts_dir(venv_root) self.scripts(venv_root).join(format!("python{EXE_SUFFIX}"))
.join(format!("python{EXE_SUFFIX}"))
} }
/// Returns the directory in which the binaries are stored inside a virtual environment. /// Returns the directory in which the binaries are stored inside a virtual environment.
pub(crate) fn venv_scripts_dir(&self, venv_root: impl AsRef<Path>) -> PathBuf { pub(crate) fn scripts(&self, venv_root: impl AsRef<Path>) -> PathBuf {
let venv = venv_root.as_ref(); let venv = venv_root.as_ref();
if matches!(self.0.os(), Os::Windows) { if matches!(self.0.os(), Os::Windows) {
let bin_dir = venv.join("Scripts"); let bin_dir = venv.join("Scripts");
@ -38,11 +41,7 @@ impl PythonPlatform {
} }
/// Returns the path to the `site-packages` directory inside a virtual environment. /// Returns the path to the `site-packages` directory inside a virtual environment.
pub(crate) fn venv_site_packages( pub(crate) fn site_packages(&self, venv_root: impl AsRef<Path>, version: (u8, u8)) -> PathBuf {
&self,
venv_root: impl AsRef<Path>,
version: (u8, u8),
) -> PathBuf {
let venv = venv_root.as_ref(); let venv = venv_root.as_ref();
if matches!(self.0.os(), Os::Windows) { if matches!(self.0.os(), Os::Windows) {
venv.join("Lib").join("site-packages") venv.join("Lib").join("site-packages")
@ -55,17 +54,13 @@ impl PythonPlatform {
/// Returns the path to the `data` directory inside a virtual environment. /// Returns the path to the `data` directory inside a virtual environment.
#[allow(clippy::unused_self)] #[allow(clippy::unused_self)]
pub(crate) fn venv_data_dir(&self, venv_root: impl AsRef<Path>) -> PathBuf { pub(crate) fn data(&self, venv_root: impl AsRef<Path>) -> PathBuf {
venv_root.as_ref().to_path_buf() venv_root.as_ref().to_path_buf()
} }
/// Returns the path to the `platstdlib` directory inside a virtual environment. /// Returns the path to the `platstdlib` directory inside a virtual environment.
#[allow(clippy::unused_self)] #[allow(clippy::unused_self)]
pub(crate) fn venv_platstdlib_dir( pub(crate) fn platstdlib(&self, venv_root: impl AsRef<Path>, version: (u8, u8)) -> PathBuf {
&self,
venv_root: impl AsRef<Path>,
version: (u8, u8),
) -> PathBuf {
let venv = venv_root.as_ref(); let venv = venv_root.as_ref();
if matches!(self.0.os(), Os::Windows) { if matches!(self.0.os(), Os::Windows) {
venv.join("Lib") venv.join("Lib")
@ -76,17 +71,3 @@ impl PythonPlatform {
} }
} }
} }
impl From<Platform> for PythonPlatform {
fn from(platform: Platform) -> Self {
Self(platform)
}
}
impl Deref for PythonPlatform {
type Target = Platform;
fn deref(&self) -> &Self::Target {
&self.0
}
}

View file

@ -16,7 +16,7 @@ use platform_host::{Arch, Os, Platform};
use platform_tags::Tags; use platform_tags::Tags;
use uv_cache::Cache; use uv_cache::Cache;
use uv_client::{FlatIndex, RegistryClientBuilder}; use uv_client::{FlatIndex, RegistryClientBuilder};
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
use uv_resolver::{ use uv_resolver::{
DisplayResolutionGraph, InMemoryIndex, Manifest, Options, OptionsBuilder, PreReleaseMode, DisplayResolutionGraph, InMemoryIndex, Manifest, Options, OptionsBuilder, PreReleaseMode,
ResolutionGraph, ResolutionMode, Resolver, ResolutionGraph, ResolutionMode, Resolver,
@ -77,7 +77,7 @@ impl BuildContext for DummyContext {
panic!("The test should not need to build source distributions") panic!("The test should not need to build source distributions")
} }
async fn install<'a>(&'a self, _: &'a Resolution, _: &'a Virtualenv) -> Result<()> { async fn install<'a>(&'a self, _: &'a Resolution, _: &'a PythonEnvironment) -> Result<()> {
panic!("The test should not need to build source distributions") panic!("The test should not need to build source distributions")
} }

View file

@ -14,7 +14,7 @@ use distribution_types::{CachedDist, DistributionId, IndexLocations, Resolution,
use once_map::OnceMap; use once_map::OnceMap;
use pep508_rs::Requirement; use pep508_rs::Requirement;
use uv_cache::Cache; use uv_cache::Cache;
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
use uv_normalize::PackageName; use uv_normalize::PackageName;
/// Avoid cyclic crate dependencies between resolver, installer and builder. /// Avoid cyclic crate dependencies between resolver, installer and builder.
@ -90,7 +90,7 @@ pub trait BuildContext: Sync {
fn install<'a>( fn install<'a>(
&'a self, &'a self,
resolution: &'a Resolution, resolution: &'a Resolution,
venv: &'a Virtualenv, venv: &'a PythonEnvironment,
) -> impl Future<Output = Result<()>> + Send + 'a; ) -> impl Future<Output = Result<()>> + Send + 'a;
/// Setup a source distribution build by installing the required dependencies. A wrapper for /// Setup a source distribution build by installing the required dependencies. A wrapper for

View file

@ -11,7 +11,7 @@ use platform_host::Platform;
use uv_cache::Cache; use uv_cache::Cache;
use uv_fs::Normalized; use uv_fs::Normalized;
use uv_installer::SitePackages; use uv_installer::SitePackages;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use crate::commands::ExitStatus; use crate::commands::ExitStatus;
use crate::printer::Printer; use crate::printer::Printer;
@ -26,12 +26,12 @@ pub(crate) fn pip_freeze(
// Detect the current Python interpreter. // Detect the current Python interpreter.
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = if let Some(python) = python { let venv = if let Some(python) = python {
Virtualenv::from_requested_python(python, &platform, cache)? PythonEnvironment::from_requested_python(python, &platform, cache)?
} else { } else {
match Virtualenv::from_env(platform.clone(), cache) { match PythonEnvironment::from_virtualenv(platform.clone(), cache) {
Ok(venv) => venv, Ok(venv) => venv,
Err(uv_interpreter::Error::VenvNotFound) => { Err(uv_interpreter::Error::VenvNotFound) => {
Virtualenv::from_default_python(&platform, cache)? PythonEnvironment::from_default_python(&platform, cache)?
} }
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
} }

View file

@ -26,7 +26,7 @@ use uv_fs::Normalized;
use uv_installer::{ use uv_installer::{
BuiltEditable, Downloader, NoBinary, Plan, Planner, Reinstall, ResolvedEditable, SitePackages, BuiltEditable, Downloader, NoBinary, Plan, Planner, Reinstall, ResolvedEditable, SitePackages,
}; };
use uv_interpreter::{Interpreter, Virtualenv}; use uv_interpreter::{Interpreter, PythonEnvironment};
use uv_normalize::PackageName; use uv_normalize::PackageName;
use uv_resolver::{ use uv_resolver::{
DependencyMode, InMemoryIndex, Manifest, Options, OptionsBuilder, PreReleaseMode, DependencyMode, InMemoryIndex, Manifest, Options, OptionsBuilder, PreReleaseMode,
@ -106,9 +106,9 @@ pub(crate) async fn pip_install(
// Detect the current Python interpreter. // Detect the current Python interpreter.
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = if let Some(python) = python.as_ref() { let venv = if let Some(python) = python.as_ref() {
Virtualenv::from_requested_python(python, &platform, &cache)? PythonEnvironment::from_requested_python(python, &platform, &cache)?
} else { } else {
Virtualenv::from_env(platform, &cache)? PythonEnvironment::from_virtualenv(platform, &cache)?
}; };
debug!( debug!(
"Using Python {} environment at {}", "Using Python {} environment at {}",
@ -509,7 +509,7 @@ async fn install(
in_flight: &InFlight, in_flight: &InFlight,
build_dispatch: &BuildDispatch<'_>, build_dispatch: &BuildDispatch<'_>,
cache: &Cache, cache: &Cache,
venv: &Virtualenv, venv: &PythonEnvironment,
mut printer: Printer, mut printer: Printer,
) -> Result<(), Error> { ) -> Result<(), Error> {
let start = std::time::Instant::now(); let start = std::time::Instant::now();
@ -707,7 +707,11 @@ async fn install(
} }
/// Validate the installed packages in the virtual environment. /// Validate the installed packages in the virtual environment.
fn validate(resolution: &Resolution, venv: &Virtualenv, mut printer: Printer) -> Result<(), Error> { fn validate(
resolution: &Resolution,
venv: &PythonEnvironment,
mut printer: Printer,
) -> Result<(), Error> {
let site_packages = SitePackages::from_executable(venv)?; let site_packages = SitePackages::from_executable(venv)?;
let diagnostics = site_packages.diagnostics()?; let diagnostics = site_packages.diagnostics()?;
for diagnostic in diagnostics { for diagnostic in diagnostics {

View file

@ -13,7 +13,7 @@ use platform_host::Platform;
use uv_cache::Cache; use uv_cache::Cache;
use uv_fs::Normalized; use uv_fs::Normalized;
use uv_installer::SitePackages; use uv_installer::SitePackages;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_normalize::PackageName; use uv_normalize::PackageName;
use crate::commands::ExitStatus; use crate::commands::ExitStatus;
@ -32,12 +32,12 @@ pub(crate) fn pip_list(
// Detect the current Python interpreter. // Detect the current Python interpreter.
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = if let Some(python) = python { let venv = if let Some(python) = python {
Virtualenv::from_requested_python(python, &platform, cache)? PythonEnvironment::from_requested_python(python, &platform, cache)?
} else { } else {
match Virtualenv::from_env(platform.clone(), cache) { match PythonEnvironment::from_virtualenv(platform.clone(), cache) {
Ok(venv) => venv, Ok(venv) => venv,
Err(uv_interpreter::Error::VenvNotFound) => { Err(uv_interpreter::Error::VenvNotFound) => {
Virtualenv::from_default_python(&platform, cache)? PythonEnvironment::from_default_python(&platform, cache)?
} }
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
} }

View file

@ -19,7 +19,7 @@ use uv_installer::{
is_dynamic, not_modified, Downloader, NoBinary, Plan, Planner, Reinstall, ResolvedEditable, is_dynamic, not_modified, Downloader, NoBinary, Plan, Planner, Reinstall, ResolvedEditable,
SitePackages, SitePackages,
}; };
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use uv_resolver::InMemoryIndex; use uv_resolver::InMemoryIndex;
use uv_traits::{ConfigSettings, InFlight, NoBuild, SetupPyStrategy}; use uv_traits::{ConfigSettings, InFlight, NoBuild, SetupPyStrategy};
@ -74,9 +74,9 @@ pub(crate) async fn pip_sync(
// Detect the current Python interpreter. // Detect the current Python interpreter.
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = if let Some(python) = python.as_ref() { let venv = if let Some(python) = python.as_ref() {
Virtualenv::from_requested_python(python, &platform, &cache)? PythonEnvironment::from_requested_python(python, &platform, &cache)?
} else { } else {
Virtualenv::from_env(platform, &cache)? PythonEnvironment::from_virtualenv(platform, &cache)?
}; };
debug!( debug!(
"Using Python {} environment at {}", "Using Python {} environment at {}",
@ -406,7 +406,7 @@ async fn resolve_editables(
editables: Vec<EditableRequirement>, editables: Vec<EditableRequirement>,
site_packages: &SitePackages<'_>, site_packages: &SitePackages<'_>,
reinstall: &Reinstall, reinstall: &Reinstall,
venv: &Virtualenv, venv: &PythonEnvironment,
tags: &Tags, tags: &Tags,
cache: &Cache, cache: &Cache,
client: &RegistryClient, client: &RegistryClient,

View file

@ -8,7 +8,7 @@ use distribution_types::{InstalledMetadata, Name};
use platform_host::Platform; use platform_host::Platform;
use uv_cache::Cache; use uv_cache::Cache;
use uv_fs::Normalized; use uv_fs::Normalized;
use uv_interpreter::Virtualenv; use uv_interpreter::PythonEnvironment;
use crate::commands::{elapsed, ExitStatus}; use crate::commands::{elapsed, ExitStatus};
use crate::printer::Printer; use crate::printer::Printer;
@ -40,9 +40,9 @@ pub(crate) async fn pip_uninstall(
// Detect the current Python interpreter. // Detect the current Python interpreter.
let platform = Platform::current()?; let platform = Platform::current()?;
let venv = if let Some(python) = python.as_ref() { let venv = if let Some(python) = python.as_ref() {
Virtualenv::from_requested_python(python, &platform, &cache)? PythonEnvironment::from_requested_python(python, &platform, &cache)?
} else { } else {
Virtualenv::from_env(platform, &cache)? PythonEnvironment::from_virtualenv(platform, &cache)?
}; };
debug!( debug!(
"Using Python {} environment at {}", "Using Python {} environment at {}",