1use core::fmt;
2use std::borrow::Cow;
3use std::cmp::{Ordering, Reverse};
4use std::ffi::OsStr;
5use std::io::{self, Write};
6#[cfg(windows)]
7use std::os::windows::fs::MetadataExt;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10
11use fs_err as fs;
12use indexmap::IndexMap;
13use itertools::Itertools;
14use thiserror::Error;
15use tokio::task::{JoinError, spawn_blocking};
16use tracing::{debug, warn};
17#[cfg(windows)]
18use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
19
20use uv_fs::{
21 LockedFile, LockedFileError, LockedFileMode, Simplified, normalize_absolute_path,
22 replace_symlink, symlink_or_copy_file, verbatim_path,
23};
24use uv_macros::DebugNoInline;
25use uv_platform::{Error as PlatformError, Os};
26use uv_platform::{LibcDetectionError, Platform};
27use uv_pypi_types::Digest;
28use uv_state::{StateBucket, StateStore};
29use uv_static::EnvVars;
30use uv_trampoline_builder::{Launcher, LauncherKind, WindowMode, windows_python_launcher};
31
32use crate::downloads::{Error as DownloadError, ManagedPythonDownload};
33use crate::macos_dylib;
34use crate::sysconfig;
35use uv_python_interpreter::Interpreter;
36use uv_python_types::{
37 ArchRequest, ImplementationError, ImplementationName, LenientImplementationName,
38 PythonDownloadRequest, PythonInstallationKey, PythonInstallationMinorVersionKey, PythonRequest,
39 PythonVariant, PythonVersion, VersionRequest,
40};
41
42#[derive(Error, DebugNoInline)]
43pub enum Error {
44 #[error(transparent)]
45 Io(#[from] io::Error),
46 #[error(transparent)]
47 Join(#[from] JoinError),
48 #[error(transparent)]
49 LockedFile(#[from] LockedFileError),
50 #[error(transparent)]
51 Download(#[from] DownloadError),
52 #[error(transparent)]
53 PlatformError(#[from] PlatformError),
54 #[error(transparent)]
55 ImplementationError(#[from] ImplementationError),
56 #[error("Invalid python version: {0}")]
57 InvalidPythonVersion(String),
58 #[error(transparent)]
59 ExtractError(#[from] uv_extract::Error),
60 #[error(transparent)]
61 SysconfigError(#[from] sysconfig::Error),
62 #[error("Missing expected Python executable at `{}`", _0.user_display())]
63 MissingExecutable(PathBuf),
64 #[error("Missing expected target directory for Python minor version link at `{}`", _0.user_display())]
65 MissingPythonMinorVersionLinkTargetDirectory(PathBuf),
66 #[error("Failed to create canonical Python executable")]
67 CanonicalizeExecutable(#[source] io::Error),
68 #[error("Failed to create Python executable link")]
69 LinkExecutable(#[source] io::Error),
70 #[error("Failed to create Python minor version link directory")]
71 PythonMinorVersionLinkDirectory(#[source] io::Error),
72 #[error("Failed to create directory for Python executable link")]
73 ExecutableDirectory(#[source] io::Error),
74 #[error("Failed to read Python installation directory")]
75 ReadError(#[source] io::Error),
76 #[error("Failed to find a directory to install executables into")]
77 NoExecutableDirectory,
78 #[error(transparent)]
79 LauncherError(#[from] uv_trampoline_builder::Error),
80 #[error("Failed to read managed Python directory name: {0}")]
81 NameError(String),
82 #[error("Failed to construct absolute path to managed Python directory: {}", _0.user_display())]
83 AbsolutePath(PathBuf, #[source] io::Error),
84 #[error(transparent)]
85 NameParseError(#[from] uv_python_types::PythonInstallationKeyError),
86 #[error("Failed to determine the libc used on the current platform")]
87 LibcDetection(#[from] LibcDetectionError),
88 #[error(transparent)]
89 MacOsDylib(#[from] macos_dylib::Error),
90}
91
92pub fn compare_build_versions(a: &str, b: &str) -> Ordering {
97 match (a.parse::<u64>(), b.parse::<u64>()) {
98 (Ok(a_num), Ok(b_num)) => a_num.cmp(&b_num),
99 _ => a.cmp(b),
100 }
101}
102
103#[derive(Debug, Clone, Eq, PartialEq)]
105pub struct ManagedPythonInstallations {
106 root: PathBuf,
108}
109
110impl ManagedPythonInstallations {
111 fn from_path(root: impl Into<PathBuf>) -> Self {
113 Self { root: root.into() }
114 }
115
116 pub async fn lock(&self) -> Result<LockedFile, Error> {
119 Ok(LockedFile::acquire(
120 self.root.join(".lock"),
121 LockedFileMode::Exclusive,
122 self.root.user_display(),
123 )
124 .await?)
125 }
126
127 pub fn from_settings(install_dir: Option<PathBuf>) -> Result<Self, Error> {
134 if let Some(install_dir) = install_dir {
135 Ok(Self::from_path(install_dir))
136 } else if let Some(install_dir) =
137 std::env::var_os(EnvVars::UV_PYTHON_INSTALL_DIR).filter(|s| !s.is_empty())
138 {
139 Ok(Self::from_path(install_dir))
140 } else {
141 Ok(Self::from_path(
142 StateStore::from_settings(None)?.bucket(StateBucket::ManagedPython),
143 ))
144 }
145 }
146
147 pub fn scratch(&self) -> PathBuf {
149 self.root.join(".temp")
150 }
151
152 pub fn init(self) -> Result<Self, Error> {
156 let root = &self.root;
157
158 if !root.exists()
160 && root
161 .parent()
162 .is_some_and(|parent| parent.join("toolchains").exists())
163 {
164 let deprecated = root.parent().unwrap().join("toolchains");
165 fs::rename(&deprecated, root)?;
167 uv_fs::replace_symlink(root, &deprecated)?;
169 } else {
170 fs::create_dir_all(root)?;
171 }
172
173 fs::create_dir_all(root)?;
175
176 let scratch = self.scratch();
178 fs::create_dir_all(&scratch)?;
179
180 match fs::OpenOptions::new()
182 .write(true)
183 .create_new(true)
184 .open(root.join(".gitignore"))
185 {
186 Ok(mut file) => file.write_all(b"*")?,
187 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
188 Err(err) => return Err(err.into()),
189 }
190
191 Ok(self)
192 }
193
194 pub fn find_all(
199 &self,
200 ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
201 let dirs = match fs_err::read_dir(&self.root) {
202 Ok(installation_dirs) => {
203 let directories: Vec<_> = installation_dirs
205 .filter_map(|read_dir| match read_dir {
206 Ok(entry) => match entry.file_type() {
207 Ok(file_type) => file_type.is_dir().then_some(Ok(entry.path())),
208 Err(err) => Some(Err(err)),
209 },
210 Err(err) => Some(Err(err)),
211 })
212 .collect::<Result<_, io::Error>>()
213 .map_err(Error::ReadError)?;
214 directories
215 }
216 Err(err) if err.kind() == io::ErrorKind::NotFound => vec![],
217 Err(err) => {
218 return Err(Error::ReadError(err));
219 }
220 };
221 let scratch = self.scratch();
222 Ok(dirs
223 .into_iter()
224 .filter(|path| *path != scratch)
226 .filter(|path| {
228 path.file_name()
229 .and_then(OsStr::to_str)
230 .is_none_or(|name| !name.starts_with('.'))
231 })
232 .filter_map(|path| {
233 ManagedPythonInstallation::from_path(path)
234 .inspect_err(|err| {
235 warn!("Ignoring malformed managed Python entry:\n {err}");
236 })
237 .ok()
238 })
239 .sorted_unstable_by_key(|installation| Reverse(installation.key().clone())))
240 }
241
242 pub fn find_matching_current_platform()
244 -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
245 let platform = Platform::from_env()?;
246
247 let iter = Self::from_settings(None)?
248 .find_all()?
249 .filter(move |installation| {
250 if !platform.supports(installation.platform()) {
251 debug!("Skipping managed installation `{installation}`: not supported by current platform `{platform}`");
252 return false;
253 }
254 true
255 });
256
257 Ok(iter)
258 }
259
260 pub fn find_version<'a>(
268 &'a self,
269 version: &'a PythonVersion,
270 ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + 'a, Error> {
271 let request = VersionRequest::try_from(version)
272 .map_err(|_| Error::InvalidPythonVersion(version.to_string()))?;
273 Ok(Self::find_matching_current_platform()?
274 .filter(move |installation| request.matches_installation_key(installation.key())))
275 }
276
277 pub fn root(&self) -> &Path {
278 &self.root
279 }
280
281 fn absolute_root(&self) -> Result<PathBuf, Error> {
282 let root = if self.root.is_absolute() {
283 self.root.clone()
284 } else {
285 crate::current_dir()?.join(&self.root)
286 };
287
288 normalize_absolute_path(&root).map_err(|err| Error::AbsolutePath(self.root.clone(), err))
289 }
290
291 pub fn contains(&self, interpreter: &Interpreter) -> bool {
293 self.installation_path(interpreter).is_some()
294 }
295
296 fn installation_path(&self, interpreter: &Interpreter) -> Option<PathBuf> {
298 let root = self.absolute_root().ok()?;
299
300 let sys_base_prefix = dunce::canonicalize(interpreter.sys_base_prefix())
304 .unwrap_or_else(|_| interpreter.sys_base_prefix().to_path_buf());
305 let root = dunce::canonicalize(&root).unwrap_or(root);
306
307 let suffix = sys_base_prefix.strip_prefix(&root).ok()?;
309
310 let first_component = suffix.components().next()?;
311 let name = first_component.as_os_str().to_str()?;
312
313 PythonInstallationKey::from_str(name).ok()?;
315
316 Some(root.join(name))
317 }
318}
319
320static EXTERNALLY_MANAGED: &str = "[externally-managed]
321Error=This Python installation is managed by uv and should not be modified.
322";
323
324#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
326pub struct ManagedPythonInstallation {
327 path: PathBuf,
329 key: PythonInstallationKey,
331 implementation: ImplementationName,
333 url: Option<Cow<'static, str>>,
337 sha256: Option<Digest<32>>,
341 build: Option<Cow<'static, str>>,
345}
346
347impl ManagedPythonInstallation {
348 pub fn new(path: PathBuf, download: &ManagedPythonDownload) -> Result<Self, Error> {
349 let implementation = ImplementationName::try_from(&download.key().implementation)?;
350 let path = std::path::absolute(&path).map_err(|err| Error::AbsolutePath(path, err))?;
351 Ok(Self {
352 path,
353 key: download.key().clone(),
354 implementation,
355 url: Some(download.url().clone()),
356 sha256: download.sha256().cloned(),
357 build: download.build().map(Cow::Borrowed),
358 })
359 }
360
361 fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
362 let path = path.as_ref();
363
364 let key = PythonInstallationKey::from_str(
365 path.file_name()
366 .ok_or(Error::NameError("name is empty".to_string()))?
367 .to_str()
368 .ok_or(Error::NameError("not a valid string".to_string()))?,
369 )?;
370
371 let implementation = ImplementationName::try_from(&key.implementation)?;
372
373 let path = std::path::absolute(path)
374 .map_err(|err| Error::AbsolutePath(path.to_path_buf(), err))?;
375
376 let build = match fs::read_to_string(path.join("BUILD")) {
378 Ok(content) => Some(Cow::Owned(content.trim().to_string())),
379 Err(err) if err.kind() == io::ErrorKind::NotFound => None,
380 Err(err) => return Err(err.into()),
381 };
382
383 Ok(Self {
384 path,
385 key,
386 implementation,
387 url: None,
388 sha256: None,
389 build,
390 })
391 }
392
393 pub fn try_from_interpreter(interpreter: &Interpreter) -> Option<Self> {
397 let installations = ManagedPythonInstallations::from_settings(None).ok()?;
398 let path = installations.installation_path(interpreter)?;
399 Self::from_path(path).ok()
400 }
401
402 pub fn executable(&self, windowed: bool) -> PathBuf {
411 let version = match self.implementation() {
412 ImplementationName::CPython => {
413 if cfg!(unix) {
414 format!("{}.{}", self.key.major, self.key.minor)
415 } else {
416 String::new()
417 }
418 }
419 ImplementationName::PyPy => format!("{}.{}", self.key.major, self.key.minor),
421 ImplementationName::Pyodide => String::new(),
423 ImplementationName::GraalPy => String::new(),
424 };
425
426 let variant = if self.implementation() == ImplementationName::GraalPy {
429 ""
430 } else if cfg!(unix) {
431 self.key.variant.executable_suffix()
432 } else if cfg!(windows) && windowed {
433 "w"
435 } else {
436 ""
437 };
438
439 let name = format!(
440 "{implementation}{version}{variant}{exe}",
441 implementation = self.implementation().executable_name(),
442 exe = std::env::consts::EXE_SUFFIX
443 );
444
445 let executable = executable_path_from_base(
446 self.python_dir().as_path(),
447 &name,
448 &LenientImplementationName::from(self.implementation()),
449 *self.key.os(),
450 );
451
452 if cfg!(windows)
457 && matches!(self.key.variant, PythonVariant::Freethreaded)
458 && !executable.exists()
459 {
460 return self.python_dir().join(format!(
462 "python{}.{}t{}",
463 self.key.major,
464 self.key.minor,
465 std::env::consts::EXE_SUFFIX
466 ));
467 }
468
469 executable
470 }
471
472 fn python_dir(&self) -> PathBuf {
473 let install = self.path.join("install");
474 if install.is_dir() {
475 install
476 } else {
477 self.path.clone()
478 }
479 }
480
481 pub fn version(&self) -> PythonVersion {
483 self.key.version()
484 }
485
486 fn key_implementation(&self) -> ImplementationName {
488 self.implementation
489 }
490
491 pub fn implementation(&self) -> ImplementationName {
492 if self.key.os().is_emscripten() {
493 ImplementationName::Pyodide
494 } else {
495 self.implementation
496 }
497 }
498
499 pub fn path(&self) -> &Path {
500 &self.path
501 }
502
503 pub fn key(&self) -> &PythonInstallationKey {
504 &self.key
505 }
506
507 pub fn platform(&self) -> &Platform {
508 self.key.platform()
509 }
510
511 pub fn build(&self) -> Option<&str> {
513 self.build.as_deref()
514 }
515
516 pub fn minor_version_key(&self) -> &PythonInstallationMinorVersionKey {
517 PythonInstallationMinorVersionKey::ref_cast(&self.key)
518 }
519
520 pub async fn ensure_canonical_executables(&self) -> Result<(), Error> {
522 let installation = self.clone();
523 spawn_blocking(move || {
524 let python = installation.executable(false);
525 let executable =
526 python.with_file_name(format!("python{exe}", exe = std::env::consts::EXE_SUFFIX));
527
528 if executable == python {
531 return Ok(());
532 }
533
534 match symlink_or_copy_file(&python, &executable) {
535 Ok(()) => {
536 debug!(
537 "Created link `{}` -> `{}`",
538 executable.user_display(),
539 python.user_display(),
540 );
541 Ok(())
542 }
543 Err(err) if err.kind() == io::ErrorKind::NotFound => {
544 Err(Error::MissingExecutable(python))
545 }
546 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Ok(()),
547 Err(err) => Err(Error::CanonicalizeExecutable(err)),
548 }
549 })
550 .await?
551 }
552
553 pub async fn ensure_minor_version_link(&self) -> Result<(), Error> {
556 let installation = self.clone();
557 spawn_blocking(move || {
558 if let Some(minor_version_link) =
559 PythonMinorVersionLink::from_installation(&installation)
560 {
561 minor_version_link.create_directory()?;
562 }
563 Ok(())
564 })
565 .await?
566 }
567
568 pub async fn ensure_externally_managed(&self) -> Result<(), Error> {
571 if self.key.os().is_emscripten() {
572 return Ok(());
575 }
576 let installation = self.clone();
577 let python_dir = spawn_blocking(move || installation.python_dir()).await?;
578 let stdlib = if self.key.os().is_windows() {
580 python_dir.join("Lib")
581 } else {
582 let lib_suffix = self.key.variant.lib_suffix();
583 let python = if matches!(
584 self.key.implementation,
585 LenientImplementationName::Known(ImplementationName::PyPy)
586 ) {
587 format!("pypy{}", self.key.version().python_version())
588 } else {
589 format!("python{}{lib_suffix}", self.key.version().python_version())
590 };
591 python_dir.join("lib").join(python)
592 };
593
594 let file = stdlib.join("EXTERNALLY-MANAGED");
595 fs::tokio::write(file, EXTERNALLY_MANAGED).await?;
596
597 Ok(())
598 }
599
600 pub async fn ensure_sysconfig_patched(&self) -> Result<(), Error> {
602 if cfg!(unix) && !self.key.os().is_windows() {
603 if self.key.os().is_emscripten() {
604 return Ok(());
607 }
608 if self.implementation() == ImplementationName::CPython {
609 sysconfig::update_sysconfig(
610 self.path(),
611 self.key.major,
612 self.key.minor,
613 self.key.variant.lib_suffix(),
614 )
615 .await?;
616 }
617 }
618 Ok(())
619 }
620
621 pub fn ensure_dylib_patched(&self) -> Result<(), macos_dylib::Error> {
628 if cfg!(target_os = "macos") {
629 if self.key().os().is_like_darwin() {
630 if self.implementation() == ImplementationName::CPython {
631 let dylib_path = self.python_dir().join("lib").join(format!(
632 "{}python{}{}{}",
633 std::env::consts::DLL_PREFIX,
634 self.key.version().python_version(),
635 self.key.variant().executable_suffix(),
636 std::env::consts::DLL_SUFFIX
637 ));
638 macos_dylib::patch_dylib_install_name(dylib_path)?;
639 }
640 }
641 }
642 Ok(())
643 }
644
645 pub async fn ensure_build_file(&self) -> Result<(), Error> {
647 if let Some(ref build) = self.build {
648 let build_file = self.path.join("BUILD");
649 fs::tokio::write(&build_file, build.as_ref()).await?;
650 }
651 Ok(())
652 }
653
654 pub fn is_bin_link(&self, path: &Path) -> bool {
657 if cfg!(unix) {
658 same_file::is_same_file(path, self.executable(false)).unwrap_or_default()
659 } else if cfg!(windows) {
660 let Some(launcher) = Launcher::try_from_path(path).unwrap_or_default() else {
661 return false;
662 };
663 if !matches!(launcher.kind, LauncherKind::Python) {
664 return false;
665 }
666 dunce::canonicalize(&launcher.python_path).unwrap_or(launcher.python_path)
670 == self.executable(false)
671 } else {
672 unreachable!("Only Windows and Unix are supported")
673 }
674 }
675
676 pub fn is_upgrade_of(&self, other: &Self) -> bool {
678 if self.key.implementation != other.key.implementation {
680 return false;
681 }
682 if self.key.variant != other.key.variant {
684 return false;
685 }
686 if (self.key.major, self.key.minor) != (other.key.major, other.key.minor) {
688 return false;
689 }
690 if self.key.patch == other.key.patch {
693 return match (self.key.prerelease, other.key.prerelease) {
694 (Some(self_pre), Some(other_pre)) => self_pre > other_pre,
696 (None, Some(_)) => true,
698 (Some(_), None) => false,
700 (None, None) => match (self.build.as_deref(), other.build.as_deref()) {
702 (Some(_), None) => true,
704 (Some(self_build), Some(other_build)) => {
706 compare_build_versions(self_build, other_build) == Ordering::Greater
707 }
708 (None, _) => false,
710 },
711 };
712 }
713 if self.key.patch < other.key.patch {
715 return false;
716 }
717 true
718 }
719
720 #[cfg(windows)]
721 pub(crate) fn url(&self) -> Option<&str> {
722 self.url.as_deref()
723 }
724
725 #[cfg(windows)]
726 pub(crate) fn sha256(&self) -> Option<&str> {
727 self.sha256.as_ref().map(Digest::as_str)
728 }
729
730 #[inline]
734 pub fn highest_by_minor_version_key<'a, I>(
735 installations: I,
736 ) -> IndexMap<PythonInstallationMinorVersionKey, Self>
737 where
738 I: IntoIterator<Item = &'a Self>,
739 {
740 let mut minor_versions = IndexMap::default();
741 for installation in installations {
742 minor_versions
743 .entry(installation.minor_version_key().clone())
744 .and_modify(|high_installation: &mut Self| {
745 if installation.key() >= high_installation.key() {
746 *high_installation = installation.clone();
747 }
748 })
749 .or_insert_with(|| installation.clone());
750 }
751 minor_versions
752 }
753}
754
755#[derive(Debug, Clone, Copy)]
757pub enum UpgradePolicy {
758 Fixed,
760 Patch,
762}
763
764impl UpgradePolicy {
765 pub fn from_request(request: &PythonRequest) -> Self {
770 if request.includes_patch() {
771 Self::Fixed
772 } else {
773 Self::Patch
774 }
775 }
776}
777
778#[derive(Clone, Debug)]
781pub struct PythonMinorVersionLink {
782 key: PythonInstallationMinorVersionKey,
784 pub symlink_directory: PathBuf,
786 pub symlink_executable: PathBuf,
789 pub target_directory: PathBuf,
792}
793
794impl PythonMinorVersionLink {
795 fn from_executable(executable: &Path, key: &PythonInstallationKey) -> Option<Self> {
815 let implementation = key.implementation();
816 if !matches!(
817 implementation.as_ref(),
818 LenientImplementationName::Known(ImplementationName::CPython)
819 ) {
820 return None;
822 }
823 let executable_name = executable
824 .file_name()
825 .expect("Executable file name should exist");
826 let symlink_directory_name = PythonInstallationMinorVersionKey::ref_cast(key).to_string();
827 let parent = executable
828 .parent()
829 .expect("Executable should have parent directory");
830
831 let target_directory = if cfg!(unix) {
833 if parent
834 .components()
835 .next_back()
836 .is_some_and(|c| c.as_os_str() == "bin")
837 {
838 parent.parent()?.to_path_buf()
839 } else {
840 return None;
841 }
842 } else if cfg!(windows) {
843 parent.to_path_buf()
844 } else {
845 unimplemented!("Only Windows and Unix systems are supported.")
846 };
847 let symlink_directory = target_directory.with_file_name(symlink_directory_name);
848 if target_directory == symlink_directory {
850 return None;
851 }
852 let symlink_executable = executable_path_from_base(
854 symlink_directory.as_path(),
855 &executable_name.to_string_lossy(),
856 &implementation,
857 *key.os(),
858 );
859 let minor_version_link = Self {
860 key: PythonInstallationMinorVersionKey::ref_cast(key).clone(),
861 symlink_directory,
862 symlink_executable,
863 target_directory,
864 };
865 Some(minor_version_link)
866 }
867
868 pub fn from_installation(installation: &ManagedPythonInstallation) -> Option<Self> {
869 Self::from_executable(installation.executable(false).as_path(), installation.key())
870 }
871
872 pub fn from_interpreter(interpreter: &Interpreter, policy: UpgradePolicy) -> Option<Self> {
876 match policy {
877 UpgradePolicy::Fixed => None,
878 UpgradePolicy::Patch => {
879 let installation = ManagedPythonInstallation::try_from_interpreter(interpreter)?;
880 Self::from_installation(&installation).filter(Self::exists)
881 }
882 }
883 }
884
885 pub fn key(&self) -> &PythonInstallationMinorVersionKey {
887 &self.key
888 }
889
890 fn create_directory(&self) -> Result<(), Error> {
891 match replace_symlink(
892 self.target_directory.as_path(),
893 self.symlink_directory.as_path(),
894 ) {
895 Ok(()) => {
896 debug!(
897 "Created link `{}` -> `{}`",
898 &self.symlink_directory.user_display(),
899 &self.target_directory.user_display(),
900 );
901 }
902 Err(err) if err.kind() == io::ErrorKind::NotFound => {
903 return Err(Error::MissingPythonMinorVersionLinkTargetDirectory(
904 self.target_directory.clone(),
905 ));
906 }
907 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
908 Err(err) => {
909 return Err(Error::PythonMinorVersionLinkDirectory(err));
910 }
911 }
912 Ok(())
913 }
914
915 pub fn exists(&self) -> bool {
922 let points_to_target = || {
923 fs_err::read_link(&self.symlink_directory)
924 .is_ok_and(|target| verbatim_path(&target) == verbatim_path(&self.target_directory))
925 };
926
927 cfg_select! {
928 unix => {
929 self.symlink_directory
930 .symlink_metadata()
931 .is_ok_and(|metadata| metadata.file_type().is_symlink())
932 && points_to_target()
933 },
934 windows => {
935 self.symlink_directory
936 .symlink_metadata()
937 .is_ok_and(|metadata| {
938 (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0) != 0
941 })
942 && points_to_target()
943 },
944 }
945 }
946}
947
948fn executable_path_from_base(
952 base: &Path,
953 executable_name: &str,
954 implementation: &LenientImplementationName,
955 os: Os,
956) -> PathBuf {
957 if matches!(
958 implementation,
959 &LenientImplementationName::Known(ImplementationName::GraalPy)
960 ) {
961 base.join("bin").join(executable_name)
963 } else if os.is_emscripten()
964 || matches!(
965 implementation,
966 &LenientImplementationName::Known(ImplementationName::Pyodide)
967 )
968 {
969 base.join(executable_name)
971 } else if os.is_windows() {
972 base.join(executable_name)
974 } else {
975 base.join("bin").join(executable_name)
977 }
978}
979
980#[derive(Debug, Clone, Copy)]
984pub struct PythonExecutable<'a> {
985 path: &'a Path,
986 window_mode: WindowMode,
987}
988
989impl<'a> PythonExecutable<'a> {
990 pub fn console(path: &'a Path) -> Self {
992 Self {
993 path,
994 window_mode: WindowMode::Console,
995 }
996 }
997
998 pub fn windowed(path: &'a Path) -> Self {
1000 Self {
1001 path,
1002 window_mode: WindowMode::Windowed,
1003 }
1004 }
1005}
1006
1007pub fn create_link_to_executable(
1011 link: &Path,
1012 executable: PythonExecutable<'_>,
1013) -> Result<(), Error> {
1014 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1015 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1016
1017 if cfg!(unix) {
1018 match symlink_or_copy_file(executable.path, link) {
1020 Ok(()) => Ok(()),
1021 Err(err) if err.kind() == io::ErrorKind::NotFound => {
1022 Err(Error::MissingExecutable(executable.path.to_path_buf()))
1023 }
1024 Err(err) => Err(Error::LinkExecutable(err)),
1025 }
1026 } else if cfg!(windows) {
1027 let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1028
1029 #[expect(clippy::disallowed_types)]
1032 {
1033 std::fs::File::create_new(link)
1034 .and_then(|mut file| file.write_all(launcher.as_ref()))
1035 .map_err(Error::LinkExecutable)
1036 }
1037 } else {
1038 unimplemented!("Only Windows and Unix are supported.")
1039 }
1040}
1041
1042pub fn replace_link_to_executable(
1048 link: &Path,
1049 executable: PythonExecutable<'_>,
1050) -> Result<(), Error> {
1051 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1052 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1053
1054 if cfg!(unix) {
1055 replace_symlink(executable.path, link).map_err(Error::LinkExecutable)
1056 } else if cfg!(windows) {
1057 let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1058
1059 uv_fs::write_atomic_sync(link, &*launcher).map_err(Error::LinkExecutable)
1060 } else {
1061 unimplemented!("Only Windows and Unix are supported.")
1062 }
1063}
1064
1065pub fn platform_key_from_env() -> Result<String, Error> {
1068 Ok(Platform::from_env()?.to_string().to_lowercase())
1069}
1070
1071impl fmt::Display for ManagedPythonInstallation {
1072 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1073 write!(
1074 f,
1075 "{}",
1076 self.path
1077 .file_name()
1078 .unwrap_or(self.path.as_os_str())
1079 .to_string_lossy()
1080 )
1081 }
1082}
1083
1084pub fn python_executable_dir() -> Result<PathBuf, Error> {
1086 uv_dirs::user_executable_directory(Some(EnvVars::UV_PYTHON_BIN_DIR))
1087 .ok_or(Error::NoExecutableDirectory)
1088}
1089
1090impl From<&ManagedPythonInstallation> for PythonDownloadRequest {
1091 fn from(installation: &ManagedPythonInstallation) -> Self {
1092 let key = installation.key();
1093 Self::new(
1094 Some(VersionRequest::from_components(
1095 key.major,
1096 key.minor,
1097 key.patch,
1098 key.prerelease,
1099 PythonVariant::Default,
1100 )),
1101 Some(installation.key_implementation()),
1102 Some(ArchRequest::Explicit(*key.arch())),
1103 Some(*key.os()),
1104 Some(*key.libc()),
1105 Some(key.prerelease.is_some()),
1106 )
1107 }
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112 use super::*;
1113 use std::path::PathBuf;
1114 use std::str::FromStr;
1115 use uv_pep440::{Prerelease, PrereleaseKind};
1116 use uv_platform::Platform;
1117 use uv_python_types::{
1118 ImplementationName, LenientImplementationName, PythonInstallationKey, PythonVariant,
1119 };
1120
1121 fn create_test_installation(
1122 implementation: ImplementationName,
1123 major: u8,
1124 minor: u8,
1125 patch: u8,
1126 prerelease: Option<Prerelease>,
1127 variant: PythonVariant,
1128 build: Option<&str>,
1129 ) -> ManagedPythonInstallation {
1130 let platform = Platform::from_str("linux-x86_64-gnu").unwrap();
1131 let key = PythonInstallationKey::new(
1132 LenientImplementationName::Known(implementation),
1133 major,
1134 minor,
1135 patch,
1136 prerelease,
1137 platform,
1138 variant,
1139 );
1140 ManagedPythonInstallation {
1141 path: PathBuf::from("/test/path"),
1142 key,
1143 implementation,
1144 url: None,
1145 sha256: None,
1146 build: build.map(|s| Cow::Owned(s.to_owned())),
1147 }
1148 }
1149
1150 #[test]
1151 fn test_is_upgrade_of_same_version() {
1152 let installation = create_test_installation(
1153 ImplementationName::CPython,
1154 3,
1155 10,
1156 8,
1157 None,
1158 PythonVariant::Default,
1159 None,
1160 );
1161
1162 assert!(!installation.is_upgrade_of(&installation));
1164 }
1165
1166 #[test]
1167 fn test_is_upgrade_of_patch_version() {
1168 let older = create_test_installation(
1169 ImplementationName::CPython,
1170 3,
1171 10,
1172 8,
1173 None,
1174 PythonVariant::Default,
1175 None,
1176 );
1177 let newer = create_test_installation(
1178 ImplementationName::CPython,
1179 3,
1180 10,
1181 9,
1182 None,
1183 PythonVariant::Default,
1184 None,
1185 );
1186
1187 assert!(newer.is_upgrade_of(&older));
1189 assert!(!older.is_upgrade_of(&newer));
1191 }
1192
1193 #[test]
1194 fn test_is_upgrade_of_different_minor_version() {
1195 let py310 = create_test_installation(
1196 ImplementationName::CPython,
1197 3,
1198 10,
1199 8,
1200 None,
1201 PythonVariant::Default,
1202 None,
1203 );
1204 let py311 = create_test_installation(
1205 ImplementationName::CPython,
1206 3,
1207 11,
1208 0,
1209 None,
1210 PythonVariant::Default,
1211 None,
1212 );
1213
1214 assert!(!py311.is_upgrade_of(&py310));
1216 assert!(!py310.is_upgrade_of(&py311));
1217 }
1218
1219 #[test]
1220 fn test_is_upgrade_of_different_implementation() {
1221 let cpython = create_test_installation(
1222 ImplementationName::CPython,
1223 3,
1224 10,
1225 8,
1226 None,
1227 PythonVariant::Default,
1228 None,
1229 );
1230 let pypy = create_test_installation(
1231 ImplementationName::PyPy,
1232 3,
1233 10,
1234 9,
1235 None,
1236 PythonVariant::Default,
1237 None,
1238 );
1239
1240 assert!(!pypy.is_upgrade_of(&cpython));
1242 assert!(!cpython.is_upgrade_of(&pypy));
1243 }
1244
1245 #[test]
1246 fn test_is_upgrade_of_different_variant() {
1247 let default = create_test_installation(
1248 ImplementationName::CPython,
1249 3,
1250 10,
1251 8,
1252 None,
1253 PythonVariant::Default,
1254 None,
1255 );
1256 let freethreaded = create_test_installation(
1257 ImplementationName::CPython,
1258 3,
1259 10,
1260 9,
1261 None,
1262 PythonVariant::Freethreaded,
1263 None,
1264 );
1265
1266 assert!(!freethreaded.is_upgrade_of(&default));
1268 assert!(!default.is_upgrade_of(&freethreaded));
1269 }
1270
1271 #[test]
1272 fn test_is_upgrade_of_prerelease() {
1273 let stable = create_test_installation(
1274 ImplementationName::CPython,
1275 3,
1276 10,
1277 8,
1278 None,
1279 PythonVariant::Default,
1280 None,
1281 );
1282 let prerelease = create_test_installation(
1283 ImplementationName::CPython,
1284 3,
1285 10,
1286 8,
1287 Some(Prerelease {
1288 kind: PrereleaseKind::Alpha,
1289 number: 1,
1290 }),
1291 PythonVariant::Default,
1292 None,
1293 );
1294
1295 assert!(stable.is_upgrade_of(&prerelease));
1297
1298 assert!(!prerelease.is_upgrade_of(&stable));
1300 }
1301
1302 #[test]
1303 fn test_is_upgrade_of_prerelease_to_prerelease() {
1304 let alpha1 = create_test_installation(
1305 ImplementationName::CPython,
1306 3,
1307 10,
1308 8,
1309 Some(Prerelease {
1310 kind: PrereleaseKind::Alpha,
1311 number: 1,
1312 }),
1313 PythonVariant::Default,
1314 None,
1315 );
1316 let alpha2 = create_test_installation(
1317 ImplementationName::CPython,
1318 3,
1319 10,
1320 8,
1321 Some(Prerelease {
1322 kind: PrereleaseKind::Alpha,
1323 number: 2,
1324 }),
1325 PythonVariant::Default,
1326 None,
1327 );
1328
1329 assert!(alpha2.is_upgrade_of(&alpha1));
1331 assert!(!alpha1.is_upgrade_of(&alpha2));
1333 }
1334
1335 #[test]
1336 fn test_is_upgrade_of_prerelease_same_patch() {
1337 let prerelease = create_test_installation(
1338 ImplementationName::CPython,
1339 3,
1340 10,
1341 8,
1342 Some(Prerelease {
1343 kind: PrereleaseKind::Alpha,
1344 number: 1,
1345 }),
1346 PythonVariant::Default,
1347 None,
1348 );
1349
1350 assert!(!prerelease.is_upgrade_of(&prerelease));
1352 }
1353
1354 #[test]
1355 fn test_is_upgrade_of_build_version() {
1356 let older_build = create_test_installation(
1357 ImplementationName::CPython,
1358 3,
1359 10,
1360 8,
1361 None,
1362 PythonVariant::Default,
1363 Some("20240101"),
1364 );
1365 let newer_build = create_test_installation(
1366 ImplementationName::CPython,
1367 3,
1368 10,
1369 8,
1370 None,
1371 PythonVariant::Default,
1372 Some("20240201"),
1373 );
1374
1375 assert!(newer_build.is_upgrade_of(&older_build));
1377 assert!(!older_build.is_upgrade_of(&newer_build));
1379 }
1380
1381 #[test]
1382 fn test_is_upgrade_of_build_version_same() {
1383 let installation = create_test_installation(
1384 ImplementationName::CPython,
1385 3,
1386 10,
1387 8,
1388 None,
1389 PythonVariant::Default,
1390 Some("20240101"),
1391 );
1392
1393 assert!(!installation.is_upgrade_of(&installation));
1395 }
1396
1397 #[test]
1398 fn test_is_upgrade_of_build_with_legacy_installation() {
1399 let legacy = create_test_installation(
1400 ImplementationName::CPython,
1401 3,
1402 10,
1403 8,
1404 None,
1405 PythonVariant::Default,
1406 None,
1407 );
1408 let with_build = create_test_installation(
1409 ImplementationName::CPython,
1410 3,
1411 10,
1412 8,
1413 None,
1414 PythonVariant::Default,
1415 Some("20240101"),
1416 );
1417
1418 assert!(with_build.is_upgrade_of(&legacy));
1420 assert!(!legacy.is_upgrade_of(&with_build));
1422 }
1423
1424 #[test]
1425 fn test_is_upgrade_of_patch_takes_precedence_over_build() {
1426 let older_patch_newer_build = create_test_installation(
1427 ImplementationName::CPython,
1428 3,
1429 10,
1430 8,
1431 None,
1432 PythonVariant::Default,
1433 Some("20240201"),
1434 );
1435 let newer_patch_older_build = create_test_installation(
1436 ImplementationName::CPython,
1437 3,
1438 10,
1439 9,
1440 None,
1441 PythonVariant::Default,
1442 Some("20240101"),
1443 );
1444
1445 assert!(newer_patch_older_build.is_upgrade_of(&older_patch_newer_build));
1447 assert!(!older_patch_newer_build.is_upgrade_of(&newer_patch_older_build));
1449 }
1450
1451 #[test]
1452 fn test_find_version_matching() {
1453 use uv_python_types::PythonVersion;
1454
1455 let platform = Platform::from_env().unwrap();
1456 let temp_dir = tempfile::tempdir().unwrap();
1457
1458 fs::create_dir(temp_dir.path().join(format!("cpython-3.10.0-{platform}"))).unwrap();
1460
1461 temp_env::with_var(
1462 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1463 Some(temp_dir.path()),
1464 || {
1465 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1466
1467 let v3_1 = PythonVersion::from_str("3.1").unwrap();
1469 let matched: Vec<_> = installations.find_version(&v3_1).unwrap().collect();
1470 assert_eq!(matched.len(), 0);
1471
1472 let v3_10 = PythonVersion::from_str("3.10").unwrap();
1474 let matched: Vec<_> = installations.find_version(&v3_10).unwrap().collect();
1475 assert_eq!(matched.len(), 1);
1476 },
1477 );
1478 }
1479
1480 #[test]
1481 fn test_relative_install_dir_resolves_against_pwd() {
1482 let temp_dir = tempfile::tempdir().unwrap();
1483 let workdir = temp_dir.path().join("workdir");
1484 fs::create_dir(&workdir).unwrap();
1485
1486 temp_env::with_vars(
1487 [
1488 (
1489 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1490 Some(std::ffi::OsStr::new(".python-installs")),
1491 ),
1492 (uv_static::EnvVars::PWD, Some(workdir.as_os_str())),
1493 ],
1494 || {
1495 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1496 assert_eq!(
1497 installations.absolute_root().unwrap(),
1498 workdir.join(".python-installs")
1499 );
1500 },
1501 );
1502 }
1503}