Skip to main content

uv_python_managed/
managed.rs

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