Skip to main content

uv_python_managed/
managed.rs

1use core::fmt;
2use std::borrow::Cow;
3use std::cmp::{Ordering, Reverse};
4use std::ffi::OsStr;
5use std::io::{self, Write};
6#[cfg(windows)]
7use std::os::windows::fs::MetadataExt;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10
11use fs_err as fs;
12use indexmap::IndexMap;
13use itertools::Itertools;
14use thiserror::Error;
15use tracing::{debug, warn};
16#[cfg(windows)]
17use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
18
19use uv_fs::{
20    LockedFile, LockedFileError, LockedFileMode, Simplified, normalize_absolute_path,
21    replace_symlink, symlink_or_copy_file, verbatim_path,
22};
23use uv_platform::{Error as PlatformError, Os};
24use uv_platform::{LibcDetectionError, Platform};
25use uv_pypi_types::Digest;
26use uv_state::{StateBucket, StateStore};
27use uv_static::EnvVars;
28use uv_trampoline_builder::{Launcher, LauncherKind, WindowMode, windows_python_launcher};
29
30use crate::downloads::{Error as DownloadError, ManagedPythonDownload};
31use crate::macos_dylib;
32use crate::sysconfig;
33use uv_python_interpreter::Interpreter;
34use uv_python_types::{
35    ArchRequest, ImplementationError, ImplementationName, LenientImplementationName,
36    PythonDownloadRequest, PythonInstallationKey, PythonInstallationMinorVersionKey, PythonRequest,
37    PythonVariant, PythonVersion, VersionRequest,
38};
39
40#[derive(Error, Debug)]
41pub enum Error {
42    #[error(transparent)]
43    Io(#[from] io::Error),
44    #[error(transparent)]
45    LockedFile(#[from] LockedFileError),
46    #[error(transparent)]
47    Download(#[from] DownloadError),
48    #[error(transparent)]
49    PlatformError(#[from] PlatformError),
50    #[error(transparent)]
51    ImplementationError(#[from] ImplementationError),
52    #[error("Invalid python version: {0}")]
53    InvalidPythonVersion(String),
54    #[error(transparent)]
55    ExtractError(#[from] uv_extract::Error),
56    #[error(transparent)]
57    SysconfigError(#[from] sysconfig::Error),
58    #[error("Missing expected Python executable at `{}`", _0.user_display())]
59    MissingExecutable(PathBuf),
60    #[error("Missing expected target directory for Python minor version link at `{}`", _0.user_display())]
61    MissingPythonMinorVersionLinkTargetDirectory(PathBuf),
62    #[error("Failed to create canonical Python executable")]
63    CanonicalizeExecutable(#[source] io::Error),
64    #[error("Failed to create Python executable link")]
65    LinkExecutable(#[source] io::Error),
66    #[error("Failed to create Python minor version link directory")]
67    PythonMinorVersionLinkDirectory(#[source] io::Error),
68    #[error("Failed to create directory for Python executable link")]
69    ExecutableDirectory(#[source] io::Error),
70    #[error("Failed to read Python installation directory")]
71    ReadError(#[source] io::Error),
72    #[error("Failed to find a directory to install executables into")]
73    NoExecutableDirectory,
74    #[error(transparent)]
75    LauncherError(#[from] uv_trampoline_builder::Error),
76    #[error("Failed to read managed Python directory name: {0}")]
77    NameError(String),
78    #[error("Failed to construct absolute path to managed Python directory: {}", _0.user_display())]
79    AbsolutePath(PathBuf, #[source] io::Error),
80    #[error(transparent)]
81    NameParseError(#[from] uv_python_types::PythonInstallationKeyError),
82    #[error("Failed to determine the libc used on the current platform")]
83    LibcDetection(#[from] LibcDetectionError),
84    #[error(transparent)]
85    MacOsDylib(#[from] macos_dylib::Error),
86}
87
88/// Compare two build version strings.
89///
90/// Build versions are typically YYYYMMDD date strings. Comparison is done numerically
91/// if both values parse as integers, otherwise falls back to lexicographic comparison.
92pub fn compare_build_versions(a: &str, b: &str) -> Ordering {
93    match (a.parse::<u64>(), b.parse::<u64>()) {
94        (Ok(a_num), Ok(b_num)) => a_num.cmp(&b_num),
95        _ => a.cmp(b),
96    }
97}
98
99/// A collection of uv-managed Python installations installed on the current system.
100#[derive(Debug, Clone, Eq, PartialEq)]
101pub struct ManagedPythonInstallations {
102    /// The path to the top-level directory of the installed Python versions.
103    root: PathBuf,
104}
105
106impl ManagedPythonInstallations {
107    /// A directory for Python installations at `root`.
108    fn from_path(root: impl Into<PathBuf>) -> Self {
109        Self { root: root.into() }
110    }
111
112    /// Grab a file lock for the managed Python distribution directory to prevent concurrent access
113    /// across processes.
114    pub async fn lock(&self) -> Result<LockedFile, Error> {
115        Ok(LockedFile::acquire(
116            self.root.join(".lock"),
117            LockedFileMode::Exclusive,
118            self.root.user_display(),
119        )
120        .await?)
121    }
122
123    /// Prefer, in order:
124    ///
125    /// 1. The specific Python directory passed via the `install_dir` argument.
126    /// 2. The specific Python directory specified with the `UV_PYTHON_INSTALL_DIR` environment variable.
127    /// 3. A directory in the system-appropriate user-level data directory, e.g., `~/.local/uv/python`.
128    /// 4. A directory in the local data directory, e.g., `./.uv/python`.
129    pub fn from_settings(install_dir: Option<PathBuf>) -> Result<Self, Error> {
130        if let Some(install_dir) = install_dir {
131            Ok(Self::from_path(install_dir))
132        } else if let Some(install_dir) =
133            std::env::var_os(EnvVars::UV_PYTHON_INSTALL_DIR).filter(|s| !s.is_empty())
134        {
135            Ok(Self::from_path(install_dir))
136        } else {
137            Ok(Self::from_path(
138                StateStore::from_settings(None)?.bucket(StateBucket::ManagedPython),
139            ))
140        }
141    }
142
143    /// Return the location of the scratch directory for managed Python installations.
144    pub fn scratch(&self) -> PathBuf {
145        self.root.join(".temp")
146    }
147
148    /// Initialize the Python installation directory.
149    ///
150    /// Ensures the directory is created.
151    pub fn init(self) -> Result<Self, Error> {
152        let root = &self.root;
153
154        // Support `toolchains` -> `python` migration transparently.
155        if !root.exists()
156            && root
157                .parent()
158                .is_some_and(|parent| parent.join("toolchains").exists())
159        {
160            let deprecated = root.parent().unwrap().join("toolchains");
161            // Move the deprecated directory to the new location.
162            fs::rename(&deprecated, root)?;
163            // Create a link or junction to at the old location
164            uv_fs::replace_symlink(root, &deprecated)?;
165        } else {
166            fs::create_dir_all(root)?;
167        }
168
169        // Create the directory, if it doesn't exist.
170        fs::create_dir_all(root)?;
171
172        // Create the scratch directory, if it doesn't exist.
173        let scratch = self.scratch();
174        fs::create_dir_all(&scratch)?;
175
176        // Add a .gitignore.
177        match fs::OpenOptions::new()
178            .write(true)
179            .create_new(true)
180            .open(root.join(".gitignore"))
181        {
182            Ok(mut file) => file.write_all(b"*")?,
183            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
184            Err(err) => return Err(err.into()),
185        }
186
187        Ok(self)
188    }
189
190    /// Iterate over each Python installation in this directory.
191    ///
192    /// Pythons are sorted by [`PythonInstallationKey`], for the same implementation name, the newest versions come first.
193    /// This ensures a consistent ordering across all platforms.
194    pub fn find_all(
195        &self,
196    ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
197        let dirs = match fs_err::read_dir(&self.root) {
198            Ok(installation_dirs) => {
199                // Collect sorted directory paths; `read_dir` is not stable across platforms
200                let directories: Vec<_> = installation_dirs
201                    .filter_map(|read_dir| match read_dir {
202                        Ok(entry) => match entry.file_type() {
203                            Ok(file_type) => file_type.is_dir().then_some(Ok(entry.path())),
204                            Err(err) => Some(Err(err)),
205                        },
206                        Err(err) => Some(Err(err)),
207                    })
208                    .collect::<Result<_, io::Error>>()
209                    .map_err(Error::ReadError)?;
210                directories
211            }
212            Err(err) if err.kind() == io::ErrorKind::NotFound => vec![],
213            Err(err) => {
214                return Err(Error::ReadError(err));
215            }
216        };
217        let scratch = self.scratch();
218        Ok(dirs
219            .into_iter()
220            // Ignore the scratch directory
221            .filter(|path| *path != scratch)
222            // Ignore any `.` prefixed directories
223            .filter(|path| {
224                path.file_name()
225                    .and_then(OsStr::to_str)
226                    .is_none_or(|name| !name.starts_with('.'))
227            })
228            .filter_map(|path| {
229                ManagedPythonInstallation::from_path(path)
230                    .inspect_err(|err| {
231                        warn!("Ignoring malformed managed Python entry:\n    {err}");
232                    })
233                    .ok()
234            })
235            .sorted_unstable_by_key(|installation| Reverse(installation.key().clone())))
236    }
237
238    /// Iterate over Python installations that support the current platform.
239    pub fn find_matching_current_platform()
240    -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
241        let platform = Platform::from_env()?;
242
243        let iter = Self::from_settings(None)?
244            .find_all()?
245            .filter(move |installation| {
246                if !platform.supports(installation.platform()) {
247                    debug!("Skipping managed installation `{installation}`: not supported by current platform `{platform}`");
248                    return false;
249                }
250                true
251            });
252
253        Ok(iter)
254    }
255
256    /// Iterate over managed Python installations that satisfy the requested version on this platform.
257    ///
258    /// ## Errors
259    ///
260    /// - The platform metadata cannot be read
261    /// - A directory for the installation cannot be read
262    pub fn find_version<'a>(
263        &'a self,
264        version: &'a PythonVersion,
265    ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + 'a, Error> {
266        let request = VersionRequest::from(version);
267        Ok(Self::find_matching_current_platform()?
268            .filter(move |installation| request.matches_installation_key(installation.key())))
269    }
270
271    pub fn root(&self) -> &Path {
272        &self.root
273    }
274
275    fn absolute_root(&self) -> Result<PathBuf, Error> {
276        let root = if self.root.is_absolute() {
277            self.root.clone()
278        } else {
279            crate::current_dir()?.join(&self.root)
280        };
281
282        normalize_absolute_path(&root).map_err(|err| Error::AbsolutePath(self.root.clone(), err))
283    }
284
285    /// Return whether the interpreter's base prefix belongs to these managed installations.
286    pub fn contains(&self, interpreter: &Interpreter) -> bool {
287        self.installation_path(interpreter).is_some()
288    }
289
290    /// Locate an interpreter's installation by its base prefix and installation key.
291    fn installation_path(&self, interpreter: &Interpreter) -> Option<PathBuf> {
292        let root = self.absolute_root().ok()?;
293
294        // Canonicalize both paths to handle Windows path format differences
295        // (e.g., \\?\ prefix, different casing, junction vs actual path).
296        // Fall back to the original path if canonicalization fails (e.g., target doesn't exist).
297        let sys_base_prefix = dunce::canonicalize(interpreter.sys_base_prefix())
298            .unwrap_or_else(|_| interpreter.sys_base_prefix().to_path_buf());
299        let root = dunce::canonicalize(&root).unwrap_or(root);
300
301        // Verify the interpreter's base prefix is within the managed root
302        let suffix = sys_base_prefix.strip_prefix(&root).ok()?;
303
304        let first_component = suffix.components().next()?;
305        let name = first_component.as_os_str().to_str()?;
306
307        // Verify it's a valid installation key
308        PythonInstallationKey::from_str(name).ok()?;
309
310        Some(root.join(name))
311    }
312}
313
314static EXTERNALLY_MANAGED: &str = "[externally-managed]
315Error=This Python installation is managed by uv and should not be modified.
316";
317
318/// A uv-managed Python installation on the current system.
319#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
320pub struct ManagedPythonInstallation {
321    /// The path to the top-level directory of the installed Python.
322    path: PathBuf,
323    /// An install key for the Python version.
324    key: PythonInstallationKey,
325    /// The implementation recorded in the key. Managed installations require a known name.
326    implementation: ImplementationName,
327    /// The URL with the Python archive.
328    ///
329    /// Empty when self was constructed from a path.
330    url: Option<Cow<'static, str>>,
331    /// The SHA256 of the Python archive at the URL.
332    ///
333    /// Empty when self was constructed from a path.
334    sha256: Option<Digest<32>>,
335    /// The build version of the Python installation.
336    ///
337    /// Empty when self was constructed from a path without a BUILD file.
338    build: Option<Cow<'static, str>>,
339}
340
341impl ManagedPythonInstallation {
342    pub fn new(path: PathBuf, download: &ManagedPythonDownload) -> Result<Self, Error> {
343        let implementation = ImplementationName::try_from(&download.key().implementation)?;
344        Ok(Self {
345            path,
346            key: download.key().clone(),
347            implementation,
348            url: Some(download.url().clone()),
349            sha256: download.sha256().cloned(),
350            build: download.build().map(Cow::Borrowed),
351        })
352    }
353
354    fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
355        let path = path.as_ref();
356
357        let key = PythonInstallationKey::from_str(
358            path.file_name()
359                .ok_or(Error::NameError("name is empty".to_string()))?
360                .to_str()
361                .ok_or(Error::NameError("not a valid string".to_string()))?,
362        )?;
363
364        let implementation = ImplementationName::try_from(&key.implementation)?;
365
366        let path = std::path::absolute(path)
367            .map_err(|err| Error::AbsolutePath(path.to_path_buf(), err))?;
368
369        // Try to read the BUILD file if it exists
370        let build = match fs::read_to_string(path.join("BUILD")) {
371            Ok(content) => Some(Cow::Owned(content.trim().to_string())),
372            Err(err) if err.kind() == io::ErrorKind::NotFound => None,
373            Err(err) => return Err(err.into()),
374        };
375
376        Ok(Self {
377            path,
378            key,
379            implementation,
380            url: None,
381            sha256: None,
382            build,
383        })
384    }
385
386    /// Try to create a [`ManagedPythonInstallation`] from an [`Interpreter`].
387    ///
388    /// Returns `None` if the interpreter is not a managed installation.
389    pub fn try_from_interpreter(interpreter: &Interpreter) -> Option<Self> {
390        let installations = ManagedPythonInstallations::from_settings(None).ok()?;
391        let path = installations.installation_path(interpreter)?;
392        Self::from_path(path).ok()
393    }
394
395    /// The path to this managed installation's Python executable.
396    ///
397    /// If the installation has multiple executables i.e., `python`, `python3`, etc., this will
398    /// return the _canonical_ executable name which the other names link to. On Unix, this is
399    /// `python{major}.{minor}{variant}` and on Windows, this is `python{exe}`.
400    ///
401    /// If windowed is true, `pythonw.exe` is selected over `python.exe` on windows, with no changes
402    /// on non-windows.
403    pub fn executable(&self, windowed: bool) -> PathBuf {
404        let version = match self.implementation() {
405            ImplementationName::CPython => {
406                if cfg!(unix) {
407                    format!("{}.{}", self.key.major, self.key.minor)
408                } else {
409                    String::new()
410                }
411            }
412            // PyPy uses a full version number, even on Windows.
413            ImplementationName::PyPy => format!("{}.{}", self.key.major, self.key.minor),
414            // Pyodide and GraalPy do not have a version suffix.
415            ImplementationName::Pyodide => String::new(),
416            ImplementationName::GraalPy => String::new(),
417        };
418
419        // On Windows, the executable is just `python.exe` even for alternative variants
420        // GraalPy always uses `graalpy.exe` as the main executable
421        let variant = if self.implementation() == ImplementationName::GraalPy {
422            ""
423        } else if cfg!(unix) {
424            self.key.variant.executable_suffix()
425        } else if cfg!(windows) && windowed {
426            // Use windowed Python that doesn't open a terminal.
427            "w"
428        } else {
429            ""
430        };
431
432        let name = format!(
433            "{implementation}{version}{variant}{exe}",
434            implementation = self.implementation().executable_name(),
435            exe = std::env::consts::EXE_SUFFIX
436        );
437
438        let executable = executable_path_from_base(
439            self.python_dir().as_path(),
440            &name,
441            &LenientImplementationName::from(self.implementation()),
442            *self.key.os(),
443        );
444
445        // Workaround for python-build-standalone v20241016 which is missing the standard
446        // `python.exe` executable in free-threaded distributions on Windows.
447        //
448        // See https://github.com/astral-sh/uv/issues/8298
449        if cfg!(windows)
450            && matches!(self.key.variant, PythonVariant::Freethreaded)
451            && !executable.exists()
452        {
453            // This is the alternative executable name for the freethreaded variant
454            return self.python_dir().join(format!(
455                "python{}.{}t{}",
456                self.key.major,
457                self.key.minor,
458                std::env::consts::EXE_SUFFIX
459            ));
460        }
461
462        executable
463    }
464
465    fn python_dir(&self) -> PathBuf {
466        let install = self.path.join("install");
467        if install.is_dir() {
468            install
469        } else {
470            self.path.clone()
471        }
472    }
473
474    /// The [`PythonVersion`] of the toolchain.
475    pub fn version(&self) -> PythonVersion {
476        self.key.version()
477    }
478
479    /// Return the implementation in the key without interpreting Emscripten as Pyodide.
480    fn key_implementation(&self) -> ImplementationName {
481        self.implementation
482    }
483
484    pub fn implementation(&self) -> ImplementationName {
485        if self.key.os().is_emscripten() {
486            ImplementationName::Pyodide
487        } else {
488            self.implementation
489        }
490    }
491
492    pub fn path(&self) -> &Path {
493        &self.path
494    }
495
496    pub fn key(&self) -> &PythonInstallationKey {
497        &self.key
498    }
499
500    pub fn platform(&self) -> &Platform {
501        self.key.platform()
502    }
503
504    /// The build version of this installation, if available.
505    pub fn build(&self) -> Option<&str> {
506        self.build.as_deref()
507    }
508
509    pub fn minor_version_key(&self) -> &PythonInstallationMinorVersionKey {
510        PythonInstallationMinorVersionKey::ref_cast(&self.key)
511    }
512
513    /// Ensure the environment contains the canonical Python executable names.
514    pub fn ensure_canonical_executables(&self) -> Result<(), Error> {
515        let python = self.executable(false);
516
517        let canonical_names = &["python"];
518
519        for name in canonical_names {
520            let executable =
521                python.with_file_name(format!("{name}{exe}", exe = std::env::consts::EXE_SUFFIX));
522
523            // Do not attempt to perform same-file copies — this is fine on Unix but fails on
524            // Windows with a permission error instead of 'already exists'
525            if executable == python {
526                continue;
527            }
528
529            match symlink_or_copy_file(&python, &executable) {
530                Ok(()) => {
531                    debug!(
532                        "Created link `{}` -> `{}`",
533                        executable.user_display(),
534                        python.user_display(),
535                    );
536                }
537                Err(err) if err.kind() == io::ErrorKind::NotFound => {
538                    return Err(Error::MissingExecutable(python.clone()));
539                }
540                Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
541                Err(err) => {
542                    return Err(Error::CanonicalizeExecutable(err));
543                }
544            }
545        }
546
547        Ok(())
548    }
549
550    /// Ensure the environment contains the symlink directory (or junction on Windows)
551    /// pointing to the patch directory for this minor version.
552    pub fn ensure_minor_version_link(&self) -> Result<(), Error> {
553        if let Some(minor_version_link) = PythonMinorVersionLink::from_installation(self) {
554            minor_version_link.create_directory()?;
555        }
556        Ok(())
557    }
558
559    /// Ensure the environment is marked as externally managed with the
560    /// standard `EXTERNALLY-MANAGED` file.
561    pub fn ensure_externally_managed(&self) -> Result<(), Error> {
562        if self.key.os().is_emscripten() {
563            // Emscripten's stdlib is a zip file so we can't put an
564            // EXTERNALLY-MANAGED inside.
565            return Ok(());
566        }
567        // Construct the path to the `stdlib` directory.
568        let stdlib = if self.key.os().is_windows() {
569            self.python_dir().join("Lib")
570        } else {
571            let lib_suffix = self.key.variant.lib_suffix();
572            let python = if matches!(
573                self.key.implementation,
574                LenientImplementationName::Known(ImplementationName::PyPy)
575            ) {
576                format!("pypy{}", self.key.version().python_version())
577            } else {
578                format!("python{}{lib_suffix}", self.key.version().python_version())
579            };
580            self.python_dir().join("lib").join(python)
581        };
582
583        let file = stdlib.join("EXTERNALLY-MANAGED");
584        fs_err::write(file, EXTERNALLY_MANAGED)?;
585
586        Ok(())
587    }
588
589    /// Ensure that the `sysconfig` data is patched to match the installation path.
590    pub fn ensure_sysconfig_patched(&self) -> Result<(), Error> {
591        if cfg!(unix) && !self.key.os().is_windows() {
592            if self.key.os().is_emscripten() {
593                // Emscripten's stdlib is a zip file so we can't update the
594                // sysconfig directly
595                return Ok(());
596            }
597            if self.implementation() == ImplementationName::CPython {
598                sysconfig::update_sysconfig(
599                    self.path(),
600                    self.key.major,
601                    self.key.minor,
602                    self.key.variant.lib_suffix(),
603                )?;
604            }
605        }
606        Ok(())
607    }
608
609    /// On macOS, ensure that the `install_name` for the Python dylib is set
610    /// correctly, rather than pointing at `/install/lib/libpython{version}.dylib`.
611    /// This is necessary to ensure that native extensions written in Rust
612    /// link to the correct location for the Python library.
613    ///
614    /// See <https://github.com/astral-sh/uv/issues/10598> for more information.
615    pub fn ensure_dylib_patched(&self) -> Result<(), macos_dylib::Error> {
616        if cfg!(target_os = "macos") {
617            if self.key().os().is_like_darwin() {
618                if self.implementation() == ImplementationName::CPython {
619                    let dylib_path = self.python_dir().join("lib").join(format!(
620                        "{}python{}{}{}",
621                        std::env::consts::DLL_PREFIX,
622                        self.key.version().python_version(),
623                        self.key.variant().executable_suffix(),
624                        std::env::consts::DLL_SUFFIX
625                    ));
626                    macos_dylib::patch_dylib_install_name(dylib_path)?;
627                }
628            }
629        }
630        Ok(())
631    }
632
633    /// Ensure the build version is written to a BUILD file in the installation directory.
634    pub fn ensure_build_file(&self) -> Result<(), Error> {
635        if let Some(ref build) = self.build {
636            let build_file = self.path.join("BUILD");
637            fs::write(&build_file, build.as_ref())?;
638        }
639        Ok(())
640    }
641
642    /// Returns `true` if the path is a link to this installation's binary, e.g., as created by
643    /// [`create_link_to_executable`].
644    pub fn is_bin_link(&self, path: &Path) -> bool {
645        if cfg!(unix) {
646            same_file::is_same_file(path, self.executable(false)).unwrap_or_default()
647        } else if cfg!(windows) {
648            let Some(launcher) = Launcher::try_from_path(path).unwrap_or_default() else {
649                return false;
650            };
651            if !matches!(launcher.kind, LauncherKind::Python) {
652                return false;
653            }
654            // We canonicalize the target path of the launcher in case it includes a minor version
655            // junction directory. If canonicalization fails, we check against the launcher path
656            // directly.
657            dunce::canonicalize(&launcher.python_path).unwrap_or(launcher.python_path)
658                == self.executable(false)
659        } else {
660            unreachable!("Only Windows and Unix are supported")
661        }
662    }
663
664    /// Returns `true` if self is a suitable upgrade of other.
665    pub fn is_upgrade_of(&self, other: &Self) -> bool {
666        // Require matching implementation
667        if self.key.implementation != other.key.implementation {
668            return false;
669        }
670        // Require a matching variant
671        if self.key.variant != other.key.variant {
672            return false;
673        }
674        // Require matching minor version
675        if (self.key.major, self.key.minor) != (other.key.major, other.key.minor) {
676            return false;
677        }
678        // If the patch versions are the same, we're handling a pre-release upgrade
679        // or a build version upgrade
680        if self.key.patch == other.key.patch {
681            return match (self.key.prerelease, other.key.prerelease) {
682                // Require a newer pre-release, if present on both
683                (Some(self_pre), Some(other_pre)) => self_pre > other_pre,
684                // Allow upgrade from pre-release to stable
685                (None, Some(_)) => true,
686                // Do not upgrade from stable to pre-release
687                (Some(_), None) => false,
688                // For matching stable versions (same patch, no prerelease), check build version
689                (None, None) => match (self.build.as_deref(), other.build.as_deref()) {
690                    // Download has build, installation doesn't -> upgrade (legacy)
691                    (Some(_), None) => true,
692                    // Both have build, compare them
693                    (Some(self_build), Some(other_build)) => {
694                        compare_build_versions(self_build, other_build) == Ordering::Greater
695                    }
696                    // Download doesn't have build -> no upgrade
697                    (None, _) => false,
698                },
699            };
700        }
701        // Require a newer patch version
702        if self.key.patch < other.key.patch {
703            return false;
704        }
705        true
706    }
707
708    #[cfg(windows)]
709    pub(crate) fn url(&self) -> Option<&str> {
710        self.url.as_deref()
711    }
712
713    #[cfg(windows)]
714    pub(crate) fn sha256(&self) -> Option<&str> {
715        self.sha256.as_ref().map(Digest::as_str)
716    }
717
718    /// Takes an [`IntoIterator`] of [`ManagedPythonInstallation`]s and returns an [`IndexMap`] from
719    /// [`PythonInstallationMinorVersionKey`] to the installation with highest [`PythonInstallationKey`]
720    /// for that minor version key.
721    #[inline]
722    pub fn highest_by_minor_version_key<'a, I>(
723        installations: I,
724    ) -> IndexMap<PythonInstallationMinorVersionKey, Self>
725    where
726        I: IntoIterator<Item = &'a Self>,
727    {
728        let mut minor_versions = IndexMap::default();
729        for installation in installations {
730            minor_versions
731                .entry(installation.minor_version_key().clone())
732                .and_modify(|high_installation: &mut Self| {
733                    if installation.key() >= high_installation.key() {
734                        *high_installation = installation.clone();
735                    }
736                })
737                .or_insert_with(|| installation.clone());
738        }
739        minor_versions
740    }
741}
742
743/// Whether an environment may follow uv-managed Python patch upgrades.
744#[derive(Debug, Clone, Copy)]
745pub enum UpgradePolicy {
746    /// Use the selected interpreter's base executable without substituting a minor-version link.
747    Fixed,
748    /// Allow patch upgrades through a suitable uv-managed minor-version link.
749    Patch,
750}
751
752impl UpgradePolicy {
753    /// Derive the upgrade policy from the resolved request used to select the interpreter.
754    ///
755    /// Requests containing a patch version require the selected installation. Other requests may
756    /// follow patch upgrades when a suitable uv-managed minor-version link exists.
757    pub fn from_request(request: &PythonRequest) -> Self {
758        if request.includes_patch() {
759            Self::Fixed
760        } else {
761            Self::Patch
762        }
763    }
764}
765
766/// A representation of a minor version symlink directory (or junction on Windows)
767/// linking to the home directory of a Python installation.
768#[derive(Clone, Debug)]
769pub struct PythonMinorVersionLink {
770    /// The installation key shared by patch versions using this link.
771    key: PythonInstallationMinorVersionKey,
772    /// The symlink directory (or junction on Windows).
773    pub symlink_directory: PathBuf,
774    /// The full path to the executable including the symlink directory
775    /// (or junction on Windows).
776    pub symlink_executable: PathBuf,
777    /// The target directory for the symlink. This is the home directory for
778    /// a Python installation.
779    pub target_directory: PathBuf,
780}
781
782impl PythonMinorVersionLink {
783    /// Attempt to derive a path from an executable path that substitutes a minor
784    /// version symlink directory (or junction on Windows) for the patch version
785    /// directory.
786    ///
787    /// The implementation is expected to be CPython and, on Unix, the base Python is
788    /// expected to be in `<home>/bin/` on Unix. If either condition isn't true,
789    /// return [`None`].
790    ///
791    /// # Examples
792    ///
793    /// ## Unix
794    /// For a Python 3.10.8 installation in `/path/to/uv/python/cpython-3.10.8-macos-aarch64-none/bin/python3.10`,
795    /// the symlink directory would be `/path/to/uv/python/cpython-3.10-macos-aarch64-none` and the executable path including the
796    /// symlink directory would be `/path/to/uv/python/cpython-3.10-macos-aarch64-none/bin/python3.10`.
797    ///
798    /// ## Windows
799    /// For a Python 3.10.8 installation in `C:\path\to\uv\python\cpython-3.10.8-windows-x86_64-none\python.exe`,
800    /// the junction would be `C:\path\to\uv\python\cpython-3.10-windows-x86_64-none` and the executable path including the
801    /// junction would be `C:\path\to\uv\python\cpython-3.10-windows-x86_64-none\python.exe`.
802    fn from_executable(executable: &Path, key: &PythonInstallationKey) -> Option<Self> {
803        let implementation = key.implementation();
804        if !matches!(
805            implementation.as_ref(),
806            LenientImplementationName::Known(ImplementationName::CPython)
807        ) {
808            // We don't currently support transparent upgrades for PyPy or GraalPy.
809            return None;
810        }
811        let executable_name = executable
812            .file_name()
813            .expect("Executable file name should exist");
814        let symlink_directory_name = PythonInstallationMinorVersionKey::ref_cast(key).to_string();
815        let parent = executable
816            .parent()
817            .expect("Executable should have parent directory");
818
819        // The home directory of the Python installation
820        let target_directory = if cfg!(unix) {
821            if parent
822                .components()
823                .next_back()
824                .is_some_and(|c| c.as_os_str() == "bin")
825            {
826                parent.parent()?.to_path_buf()
827            } else {
828                return None;
829            }
830        } else if cfg!(windows) {
831            parent.to_path_buf()
832        } else {
833            unimplemented!("Only Windows and Unix systems are supported.")
834        };
835        let symlink_directory = target_directory.with_file_name(symlink_directory_name);
836        // If this would create a circular link, return `None`.
837        if target_directory == symlink_directory {
838            return None;
839        }
840        // The full executable path including the symlink directory (or junction).
841        let symlink_executable = executable_path_from_base(
842            symlink_directory.as_path(),
843            &executable_name.to_string_lossy(),
844            &implementation,
845            *key.os(),
846        );
847        let minor_version_link = Self {
848            key: PythonInstallationMinorVersionKey::ref_cast(key).clone(),
849            symlink_directory,
850            symlink_executable,
851            target_directory,
852        };
853        Some(minor_version_link)
854    }
855
856    pub fn from_installation(installation: &ManagedPythonInstallation) -> Option<Self> {
857        Self::from_executable(installation.executable(false).as_path(), installation.key())
858    }
859
860    /// Return an existing managed link when the environment's policy permits patch upgrades.
861    ///
862    /// The link must still point to the selected installation.
863    pub fn from_interpreter(interpreter: &Interpreter, policy: UpgradePolicy) -> Option<Self> {
864        match policy {
865            UpgradePolicy::Fixed => None,
866            UpgradePolicy::Patch => {
867                let installation = ManagedPythonInstallation::try_from_interpreter(interpreter)?;
868                Self::from_installation(&installation).filter(Self::exists)
869            }
870        }
871    }
872
873    /// Return the managed installation key shared by this link's patch versions.
874    pub fn key(&self) -> &PythonInstallationMinorVersionKey {
875        &self.key
876    }
877
878    fn create_directory(&self) -> Result<(), Error> {
879        match replace_symlink(
880            self.target_directory.as_path(),
881            self.symlink_directory.as_path(),
882        ) {
883            Ok(()) => {
884                debug!(
885                    "Created link `{}` -> `{}`",
886                    &self.symlink_directory.user_display(),
887                    &self.target_directory.user_display(),
888                );
889            }
890            Err(err) if err.kind() == io::ErrorKind::NotFound => {
891                return Err(Error::MissingPythonMinorVersionLinkTargetDirectory(
892                    self.target_directory.clone(),
893                ));
894            }
895            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
896            Err(err) => {
897                return Err(Error::PythonMinorVersionLinkDirectory(err));
898            }
899        }
900        Ok(())
901    }
902
903    /// Check if the minor version link exists and points to the expected target directory.
904    ///
905    /// This verifies both that the symlink/junction exists AND that it points to the
906    /// `target_directory` specified in this struct. This is important because the link
907    /// may exist but point to a different installation (e.g., after an upgrade), in which
908    /// case we should not use the link for the current installation.
909    pub fn exists(&self) -> bool {
910        let points_to_target = || {
911            fs_err::read_link(&self.symlink_directory)
912                .is_ok_and(|target| verbatim_path(&target) == verbatim_path(&self.target_directory))
913        };
914
915        cfg_select! {
916            unix => {
917                self.symlink_directory
918                    .symlink_metadata()
919                    .is_ok_and(|metadata| metadata.file_type().is_symlink())
920                    && points_to_target()
921            },
922            windows => {
923                self.symlink_directory
924                    .symlink_metadata()
925                    .is_ok_and(|metadata| {
926                        // Check that this is a reparse point, which indicates this
927                        // is a symlink or junction.
928                        (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0) != 0
929                    })
930                    && points_to_target()
931            },
932        }
933    }
934}
935
936/// Derive the full path to an executable from the given base path and executable
937/// name. On Unix, this is, e.g., `<base>/bin/python3.10`. On Windows, this is,
938/// e.g., `<base>\python.exe`.
939fn executable_path_from_base(
940    base: &Path,
941    executable_name: &str,
942    implementation: &LenientImplementationName,
943    os: Os,
944) -> PathBuf {
945    if matches!(
946        implementation,
947        &LenientImplementationName::Known(ImplementationName::GraalPy)
948    ) {
949        // GraalPy is always in `bin/` regardless of the os
950        base.join("bin").join(executable_name)
951    } else if os.is_emscripten()
952        || matches!(
953            implementation,
954            &LenientImplementationName::Known(ImplementationName::Pyodide)
955        )
956    {
957        // Emscripten's canonical executable is in the base directory
958        base.join(executable_name)
959    } else if os.is_windows() {
960        // On Windows, the executable is in the base directory
961        base.join(executable_name)
962    } else {
963        // On Unix, the executable is in `bin/`
964        base.join("bin").join(executable_name)
965    }
966}
967
968/// A Python executable and its window mode.
969///
970/// The [`WindowMode`] is used by Windows launchers and ignored for Unix symlinks.
971#[derive(Debug, Clone, Copy)]
972pub struct PythonExecutable<'a> {
973    path: &'a Path,
974    window_mode: WindowMode,
975}
976
977impl<'a> PythonExecutable<'a> {
978    /// Create a Python executable that runs attached to a console.
979    pub fn console(path: &'a Path) -> Self {
980        Self {
981            path,
982            window_mode: WindowMode::Console,
983        }
984    }
985
986    /// Create a Python executable that runs without opening a console window.
987    pub fn windowed(path: &'a Path) -> Self {
988        Self {
989            path,
990            window_mode: WindowMode::Windowed,
991        }
992    }
993}
994
995/// Create a link to a managed Python executable.
996///
997/// If the file already exists at the link path, an error will be returned.
998pub fn create_link_to_executable(
999    link: &Path,
1000    executable: PythonExecutable<'_>,
1001) -> Result<(), Error> {
1002    let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1003    fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1004
1005    if cfg!(unix) {
1006        // Note this will never copy on Unix — we use it here to allow compilation on Windows
1007        match symlink_or_copy_file(executable.path, link) {
1008            Ok(()) => Ok(()),
1009            Err(err) if err.kind() == io::ErrorKind::NotFound => {
1010                Err(Error::MissingExecutable(executable.path.to_path_buf()))
1011            }
1012            Err(err) => Err(Error::LinkExecutable(err)),
1013        }
1014    } else if cfg!(windows) {
1015        let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1016
1017        // OK to use `std::fs` here, `fs_err` does not support `File::create_new` and we attach
1018        // error context anyway
1019        #[expect(clippy::disallowed_types)]
1020        {
1021            std::fs::File::create_new(link)
1022                .and_then(|mut file| file.write_all(launcher.as_ref()))
1023                .map_err(Error::LinkExecutable)
1024        }
1025    } else {
1026        unimplemented!("Only Windows and Unix are supported.")
1027    }
1028}
1029
1030/// Create or replace a link to a managed Python executable.
1031///
1032/// If a file already exists at the link path, it will be atomically replaced.
1033///
1034/// See [`create_link_to_executable`] for a variant that errors if the link already exists.
1035pub fn replace_link_to_executable(
1036    link: &Path,
1037    executable: PythonExecutable<'_>,
1038) -> Result<(), Error> {
1039    let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1040    fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1041
1042    if cfg!(unix) {
1043        replace_symlink(executable.path, link).map_err(Error::LinkExecutable)
1044    } else if cfg!(windows) {
1045        let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1046
1047        uv_fs::write_atomic_sync(link, &*launcher).map_err(Error::LinkExecutable)
1048    } else {
1049        unimplemented!("Only Windows and Unix are supported.")
1050    }
1051}
1052
1053// TODO(zanieb): Only used in tests now.
1054/// Generate a platform portion of a key from the environment.
1055pub fn platform_key_from_env() -> Result<String, Error> {
1056    Ok(Platform::from_env()?.to_string().to_lowercase())
1057}
1058
1059impl fmt::Display for ManagedPythonInstallation {
1060    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1061        write!(
1062            f,
1063            "{}",
1064            self.path
1065                .file_name()
1066                .unwrap_or(self.path.as_os_str())
1067                .to_string_lossy()
1068        )
1069    }
1070}
1071
1072/// Find the directory to install Python executables into.
1073pub fn python_executable_dir() -> Result<PathBuf, Error> {
1074    uv_dirs::user_executable_directory(Some(EnvVars::UV_PYTHON_BIN_DIR))
1075        .ok_or(Error::NoExecutableDirectory)
1076}
1077
1078impl From<&ManagedPythonInstallation> for PythonDownloadRequest {
1079    fn from(installation: &ManagedPythonInstallation) -> Self {
1080        let key = installation.key();
1081        Self::new(
1082            Some(VersionRequest::from(&key.version())),
1083            Some(installation.key_implementation()),
1084            Some(ArchRequest::Explicit(*key.arch())),
1085            Some(*key.os()),
1086            Some(*key.libc()),
1087            Some(key.prerelease.is_some()),
1088        )
1089    }
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094    use super::*;
1095    use std::path::PathBuf;
1096    use std::str::FromStr;
1097    use uv_pep440::{Prerelease, PrereleaseKind};
1098    use uv_platform::Platform;
1099    use uv_python_types::{
1100        ImplementationName, LenientImplementationName, PythonInstallationKey, PythonVariant,
1101    };
1102
1103    fn create_test_installation(
1104        implementation: ImplementationName,
1105        major: u8,
1106        minor: u8,
1107        patch: u8,
1108        prerelease: Option<Prerelease>,
1109        variant: PythonVariant,
1110        build: Option<&str>,
1111    ) -> ManagedPythonInstallation {
1112        let platform = Platform::from_str("linux-x86_64-gnu").unwrap();
1113        let key = PythonInstallationKey::new(
1114            LenientImplementationName::Known(implementation),
1115            major,
1116            minor,
1117            patch,
1118            prerelease,
1119            platform,
1120            variant,
1121        );
1122        ManagedPythonInstallation {
1123            path: PathBuf::from("/test/path"),
1124            key,
1125            implementation,
1126            url: None,
1127            sha256: None,
1128            build: build.map(|s| Cow::Owned(s.to_owned())),
1129        }
1130    }
1131
1132    #[test]
1133    fn test_is_upgrade_of_same_version() {
1134        let installation = create_test_installation(
1135            ImplementationName::CPython,
1136            3,
1137            10,
1138            8,
1139            None,
1140            PythonVariant::Default,
1141            None,
1142        );
1143
1144        // Same patch version should not be an upgrade
1145        assert!(!installation.is_upgrade_of(&installation));
1146    }
1147
1148    #[test]
1149    fn test_is_upgrade_of_patch_version() {
1150        let older = create_test_installation(
1151            ImplementationName::CPython,
1152            3,
1153            10,
1154            8,
1155            None,
1156            PythonVariant::Default,
1157            None,
1158        );
1159        let newer = create_test_installation(
1160            ImplementationName::CPython,
1161            3,
1162            10,
1163            9,
1164            None,
1165            PythonVariant::Default,
1166            None,
1167        );
1168
1169        // Newer patch version should be an upgrade
1170        assert!(newer.is_upgrade_of(&older));
1171        // Older patch version should not be an upgrade
1172        assert!(!older.is_upgrade_of(&newer));
1173    }
1174
1175    #[test]
1176    fn test_is_upgrade_of_different_minor_version() {
1177        let py310 = create_test_installation(
1178            ImplementationName::CPython,
1179            3,
1180            10,
1181            8,
1182            None,
1183            PythonVariant::Default,
1184            None,
1185        );
1186        let py311 = create_test_installation(
1187            ImplementationName::CPython,
1188            3,
1189            11,
1190            0,
1191            None,
1192            PythonVariant::Default,
1193            None,
1194        );
1195
1196        // Different minor versions should not be upgrades
1197        assert!(!py311.is_upgrade_of(&py310));
1198        assert!(!py310.is_upgrade_of(&py311));
1199    }
1200
1201    #[test]
1202    fn test_is_upgrade_of_different_implementation() {
1203        let cpython = create_test_installation(
1204            ImplementationName::CPython,
1205            3,
1206            10,
1207            8,
1208            None,
1209            PythonVariant::Default,
1210            None,
1211        );
1212        let pypy = create_test_installation(
1213            ImplementationName::PyPy,
1214            3,
1215            10,
1216            9,
1217            None,
1218            PythonVariant::Default,
1219            None,
1220        );
1221
1222        // Different implementations should not be upgrades
1223        assert!(!pypy.is_upgrade_of(&cpython));
1224        assert!(!cpython.is_upgrade_of(&pypy));
1225    }
1226
1227    #[test]
1228    fn test_is_upgrade_of_different_variant() {
1229        let default = create_test_installation(
1230            ImplementationName::CPython,
1231            3,
1232            10,
1233            8,
1234            None,
1235            PythonVariant::Default,
1236            None,
1237        );
1238        let freethreaded = create_test_installation(
1239            ImplementationName::CPython,
1240            3,
1241            10,
1242            9,
1243            None,
1244            PythonVariant::Freethreaded,
1245            None,
1246        );
1247
1248        // Different variants should not be upgrades
1249        assert!(!freethreaded.is_upgrade_of(&default));
1250        assert!(!default.is_upgrade_of(&freethreaded));
1251    }
1252
1253    #[test]
1254    fn test_is_upgrade_of_prerelease() {
1255        let stable = create_test_installation(
1256            ImplementationName::CPython,
1257            3,
1258            10,
1259            8,
1260            None,
1261            PythonVariant::Default,
1262            None,
1263        );
1264        let prerelease = create_test_installation(
1265            ImplementationName::CPython,
1266            3,
1267            10,
1268            8,
1269            Some(Prerelease {
1270                kind: PrereleaseKind::Alpha,
1271                number: 1,
1272            }),
1273            PythonVariant::Default,
1274            None,
1275        );
1276
1277        // A stable version is an upgrade from prerelease
1278        assert!(stable.is_upgrade_of(&prerelease));
1279
1280        // Prerelease are not upgrades of stable versions
1281        assert!(!prerelease.is_upgrade_of(&stable));
1282    }
1283
1284    #[test]
1285    fn test_is_upgrade_of_prerelease_to_prerelease() {
1286        let alpha1 = create_test_installation(
1287            ImplementationName::CPython,
1288            3,
1289            10,
1290            8,
1291            Some(Prerelease {
1292                kind: PrereleaseKind::Alpha,
1293                number: 1,
1294            }),
1295            PythonVariant::Default,
1296            None,
1297        );
1298        let alpha2 = create_test_installation(
1299            ImplementationName::CPython,
1300            3,
1301            10,
1302            8,
1303            Some(Prerelease {
1304                kind: PrereleaseKind::Alpha,
1305                number: 2,
1306            }),
1307            PythonVariant::Default,
1308            None,
1309        );
1310
1311        // Later prerelease should be an upgrade
1312        assert!(alpha2.is_upgrade_of(&alpha1));
1313        // Earlier prerelease should not be an upgrade
1314        assert!(!alpha1.is_upgrade_of(&alpha2));
1315    }
1316
1317    #[test]
1318    fn test_is_upgrade_of_prerelease_same_patch() {
1319        let prerelease = create_test_installation(
1320            ImplementationName::CPython,
1321            3,
1322            10,
1323            8,
1324            Some(Prerelease {
1325                kind: PrereleaseKind::Alpha,
1326                number: 1,
1327            }),
1328            PythonVariant::Default,
1329            None,
1330        );
1331
1332        // Same prerelease should not be an upgrade
1333        assert!(!prerelease.is_upgrade_of(&prerelease));
1334    }
1335
1336    #[test]
1337    fn test_is_upgrade_of_build_version() {
1338        let older_build = create_test_installation(
1339            ImplementationName::CPython,
1340            3,
1341            10,
1342            8,
1343            None,
1344            PythonVariant::Default,
1345            Some("20240101"),
1346        );
1347        let newer_build = create_test_installation(
1348            ImplementationName::CPython,
1349            3,
1350            10,
1351            8,
1352            None,
1353            PythonVariant::Default,
1354            Some("20240201"),
1355        );
1356
1357        // Newer build version should be an upgrade
1358        assert!(newer_build.is_upgrade_of(&older_build));
1359        // Older build version should not be an upgrade
1360        assert!(!older_build.is_upgrade_of(&newer_build));
1361    }
1362
1363    #[test]
1364    fn test_is_upgrade_of_build_version_same() {
1365        let installation = create_test_installation(
1366            ImplementationName::CPython,
1367            3,
1368            10,
1369            8,
1370            None,
1371            PythonVariant::Default,
1372            Some("20240101"),
1373        );
1374
1375        // Same build version should not be an upgrade
1376        assert!(!installation.is_upgrade_of(&installation));
1377    }
1378
1379    #[test]
1380    fn test_is_upgrade_of_build_with_legacy_installation() {
1381        let legacy = create_test_installation(
1382            ImplementationName::CPython,
1383            3,
1384            10,
1385            8,
1386            None,
1387            PythonVariant::Default,
1388            None,
1389        );
1390        let with_build = create_test_installation(
1391            ImplementationName::CPython,
1392            3,
1393            10,
1394            8,
1395            None,
1396            PythonVariant::Default,
1397            Some("20240101"),
1398        );
1399
1400        // Installation with build should upgrade legacy installation without build
1401        assert!(with_build.is_upgrade_of(&legacy));
1402        // Legacy installation should not upgrade installation with build
1403        assert!(!legacy.is_upgrade_of(&with_build));
1404    }
1405
1406    #[test]
1407    fn test_is_upgrade_of_patch_takes_precedence_over_build() {
1408        let older_patch_newer_build = create_test_installation(
1409            ImplementationName::CPython,
1410            3,
1411            10,
1412            8,
1413            None,
1414            PythonVariant::Default,
1415            Some("20240201"),
1416        );
1417        let newer_patch_older_build = create_test_installation(
1418            ImplementationName::CPython,
1419            3,
1420            10,
1421            9,
1422            None,
1423            PythonVariant::Default,
1424            Some("20240101"),
1425        );
1426
1427        // Newer patch version should be an upgrade regardless of build
1428        assert!(newer_patch_older_build.is_upgrade_of(&older_patch_newer_build));
1429        // Older patch version should not be an upgrade even with newer build
1430        assert!(!older_patch_newer_build.is_upgrade_of(&newer_patch_older_build));
1431    }
1432
1433    #[test]
1434    fn test_find_version_matching() {
1435        use uv_python_types::PythonVersion;
1436
1437        let platform = Platform::from_env().unwrap();
1438        let temp_dir = tempfile::tempdir().unwrap();
1439
1440        // Create mock installation directories
1441        fs::create_dir(temp_dir.path().join(format!("cpython-3.10.0-{platform}"))).unwrap();
1442
1443        temp_env::with_var(
1444            uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1445            Some(temp_dir.path()),
1446            || {
1447                let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1448
1449                // Version 3.1 should NOT match 3.10
1450                let v3_1 = PythonVersion::from_str("3.1").unwrap();
1451                let matched: Vec<_> = installations.find_version(&v3_1).unwrap().collect();
1452                assert_eq!(matched.len(), 0);
1453
1454                // Check that 3.10 matches
1455                let v3_10 = PythonVersion::from_str("3.10").unwrap();
1456                let matched: Vec<_> = installations.find_version(&v3_10).unwrap().collect();
1457                assert_eq!(matched.len(), 1);
1458            },
1459        );
1460    }
1461
1462    #[test]
1463    fn test_relative_install_dir_resolves_against_pwd() {
1464        let temp_dir = tempfile::tempdir().unwrap();
1465        let workdir = temp_dir.path().join("workdir");
1466        fs::create_dir(&workdir).unwrap();
1467
1468        temp_env::with_vars(
1469            [
1470                (
1471                    uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1472                    Some(std::ffi::OsStr::new(".python-installs")),
1473                ),
1474                (uv_static::EnvVars::PWD, Some(workdir.as_os_str())),
1475            ],
1476            || {
1477                let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1478                assert_eq!(
1479                    installations.absolute_root().unwrap(),
1480                    workdir.join(".python-installs")
1481                );
1482            },
1483        );
1484    }
1485}