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