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