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