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