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>(
266 &'a self,
267 version: &'a PythonVersion,
268 ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + 'a, Error> {
269 let request = VersionRequest::from(version);
270 Ok(Self::find_matching_current_platform()?
271 .filter(move |installation| request.matches_installation_key(installation.key())))
272 }
273
274 pub fn root(&self) -> &Path {
275 &self.root
276 }
277
278 fn absolute_root(&self) -> Result<PathBuf, Error> {
279 let root = if self.root.is_absolute() {
280 self.root.clone()
281 } else {
282 crate::current_dir()?.join(&self.root)
283 };
284
285 normalize_absolute_path(&root).map_err(|err| Error::AbsolutePath(self.root.clone(), err))
286 }
287
288 pub fn contains(&self, interpreter: &Interpreter) -> bool {
290 self.installation_path(interpreter).is_some()
291 }
292
293 fn installation_path(&self, interpreter: &Interpreter) -> Option<PathBuf> {
295 let root = self.absolute_root().ok()?;
296
297 let sys_base_prefix = dunce::canonicalize(interpreter.sys_base_prefix())
301 .unwrap_or_else(|_| interpreter.sys_base_prefix().to_path_buf());
302 let root = dunce::canonicalize(&root).unwrap_or(root);
303
304 let suffix = sys_base_prefix.strip_prefix(&root).ok()?;
306
307 let first_component = suffix.components().next()?;
308 let name = first_component.as_os_str().to_str()?;
309
310 PythonInstallationKey::from_str(name).ok()?;
312
313 Some(root.join(name))
314 }
315}
316
317static EXTERNALLY_MANAGED: &str = "[externally-managed]
318Error=This Python installation is managed by uv and should not be modified.
319";
320
321#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
323pub struct ManagedPythonInstallation {
324 path: PathBuf,
326 key: PythonInstallationKey,
328 implementation: ImplementationName,
330 url: Option<Cow<'static, str>>,
334 sha256: Option<Digest<32>>,
338 build: Option<Cow<'static, str>>,
342}
343
344impl ManagedPythonInstallation {
345 pub fn new(path: PathBuf, download: &ManagedPythonDownload) -> Result<Self, Error> {
346 let implementation = ImplementationName::try_from(&download.key().implementation)?;
347 Ok(Self {
348 path,
349 key: download.key().clone(),
350 implementation,
351 url: Some(download.url().clone()),
352 sha256: download.sha256().cloned(),
353 build: download.build().map(Cow::Borrowed),
354 })
355 }
356
357 fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
358 let path = path.as_ref();
359
360 let key = PythonInstallationKey::from_str(
361 path.file_name()
362 .ok_or(Error::NameError("name is empty".to_string()))?
363 .to_str()
364 .ok_or(Error::NameError("not a valid string".to_string()))?,
365 )?;
366
367 let implementation = ImplementationName::try_from(&key.implementation)?;
368
369 let path = std::path::absolute(path)
370 .map_err(|err| Error::AbsolutePath(path.to_path_buf(), err))?;
371
372 let build = match fs::read_to_string(path.join("BUILD")) {
374 Ok(content) => Some(Cow::Owned(content.trim().to_string())),
375 Err(err) if err.kind() == io::ErrorKind::NotFound => None,
376 Err(err) => return Err(err.into()),
377 };
378
379 Ok(Self {
380 path,
381 key,
382 implementation,
383 url: None,
384 sha256: None,
385 build,
386 })
387 }
388
389 pub fn try_from_interpreter(interpreter: &Interpreter) -> Option<Self> {
393 let installations = ManagedPythonInstallations::from_settings(None).ok()?;
394 let path = installations.installation_path(interpreter)?;
395 Self::from_path(path).ok()
396 }
397
398 pub fn executable(&self, windowed: bool) -> PathBuf {
407 let version = match self.implementation() {
408 ImplementationName::CPython => {
409 if cfg!(unix) {
410 format!("{}.{}", self.key.major, self.key.minor)
411 } else {
412 String::new()
413 }
414 }
415 ImplementationName::PyPy => format!("{}.{}", self.key.major, self.key.minor),
417 ImplementationName::Pyodide => String::new(),
419 ImplementationName::GraalPy => String::new(),
420 };
421
422 let variant = if self.implementation() == ImplementationName::GraalPy {
425 ""
426 } else if cfg!(unix) {
427 self.key.variant.executable_suffix()
428 } else if cfg!(windows) && windowed {
429 "w"
431 } else {
432 ""
433 };
434
435 let name = format!(
436 "{implementation}{version}{variant}{exe}",
437 implementation = self.implementation().executable_name(),
438 exe = std::env::consts::EXE_SUFFIX
439 );
440
441 let executable = executable_path_from_base(
442 self.python_dir().as_path(),
443 &name,
444 &LenientImplementationName::from(self.implementation()),
445 *self.key.os(),
446 );
447
448 if cfg!(windows)
453 && matches!(self.key.variant, PythonVariant::Freethreaded)
454 && !executable.exists()
455 {
456 return self.python_dir().join(format!(
458 "python{}.{}t{}",
459 self.key.major,
460 self.key.minor,
461 std::env::consts::EXE_SUFFIX
462 ));
463 }
464
465 executable
466 }
467
468 fn python_dir(&self) -> PathBuf {
469 let install = self.path.join("install");
470 if install.is_dir() {
471 install
472 } else {
473 self.path.clone()
474 }
475 }
476
477 pub fn version(&self) -> PythonVersion {
479 self.key.version()
480 }
481
482 fn key_implementation(&self) -> ImplementationName {
484 self.implementation
485 }
486
487 pub fn implementation(&self) -> ImplementationName {
488 if self.key.os().is_emscripten() {
489 ImplementationName::Pyodide
490 } else {
491 self.implementation
492 }
493 }
494
495 pub fn path(&self) -> &Path {
496 &self.path
497 }
498
499 pub fn key(&self) -> &PythonInstallationKey {
500 &self.key
501 }
502
503 pub fn platform(&self) -> &Platform {
504 self.key.platform()
505 }
506
507 pub fn build(&self) -> Option<&str> {
509 self.build.as_deref()
510 }
511
512 pub fn minor_version_key(&self) -> &PythonInstallationMinorVersionKey {
513 PythonInstallationMinorVersionKey::ref_cast(&self.key)
514 }
515
516 pub async fn ensure_canonical_executables(&self) -> Result<(), Error> {
518 let installation = self.clone();
519 spawn_blocking(move || {
520 let python = installation.executable(false);
521 let executable =
522 python.with_file_name(format!("python{exe}", exe = std::env::consts::EXE_SUFFIX));
523
524 if executable == python {
527 return Ok(());
528 }
529
530 match symlink_or_copy_file(&python, &executable) {
531 Ok(()) => {
532 debug!(
533 "Created link `{}` -> `{}`",
534 executable.user_display(),
535 python.user_display(),
536 );
537 Ok(())
538 }
539 Err(err) if err.kind() == io::ErrorKind::NotFound => {
540 Err(Error::MissingExecutable(python))
541 }
542 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Ok(()),
543 Err(err) => Err(Error::CanonicalizeExecutable(err)),
544 }
545 })
546 .await?
547 }
548
549 pub async fn ensure_minor_version_link(&self) -> Result<(), Error> {
552 let installation = self.clone();
553 spawn_blocking(move || {
554 if let Some(minor_version_link) =
555 PythonMinorVersionLink::from_installation(&installation)
556 {
557 minor_version_link.create_directory()?;
558 }
559 Ok(())
560 })
561 .await?
562 }
563
564 pub async fn ensure_externally_managed(&self) -> Result<(), Error> {
567 if self.key.os().is_emscripten() {
568 return Ok(());
571 }
572 let installation = self.clone();
573 let python_dir = spawn_blocking(move || installation.python_dir()).await?;
574 let stdlib = if self.key.os().is_windows() {
576 python_dir.join("Lib")
577 } else {
578 let lib_suffix = self.key.variant.lib_suffix();
579 let python = if matches!(
580 self.key.implementation,
581 LenientImplementationName::Known(ImplementationName::PyPy)
582 ) {
583 format!("pypy{}", self.key.version().python_version())
584 } else {
585 format!("python{}{lib_suffix}", self.key.version().python_version())
586 };
587 python_dir.join("lib").join(python)
588 };
589
590 let file = stdlib.join("EXTERNALLY-MANAGED");
591 fs::tokio::write(file, EXTERNALLY_MANAGED).await?;
592
593 Ok(())
594 }
595
596 pub async fn ensure_sysconfig_patched(&self) -> Result<(), Error> {
598 if cfg!(unix) && !self.key.os().is_windows() {
599 if self.key.os().is_emscripten() {
600 return Ok(());
603 }
604 if self.implementation() == ImplementationName::CPython {
605 sysconfig::update_sysconfig(
606 self.path(),
607 self.key.major,
608 self.key.minor,
609 self.key.variant.lib_suffix(),
610 )
611 .await?;
612 }
613 }
614 Ok(())
615 }
616
617 pub fn ensure_dylib_patched(&self) -> Result<(), macos_dylib::Error> {
624 if cfg!(target_os = "macos") {
625 if self.key().os().is_like_darwin() {
626 if self.implementation() == ImplementationName::CPython {
627 let dylib_path = self.python_dir().join("lib").join(format!(
628 "{}python{}{}{}",
629 std::env::consts::DLL_PREFIX,
630 self.key.version().python_version(),
631 self.key.variant().executable_suffix(),
632 std::env::consts::DLL_SUFFIX
633 ));
634 macos_dylib::patch_dylib_install_name(dylib_path)?;
635 }
636 }
637 }
638 Ok(())
639 }
640
641 pub async fn ensure_build_file(&self) -> Result<(), Error> {
643 if let Some(ref build) = self.build {
644 let build_file = self.path.join("BUILD");
645 fs::tokio::write(&build_file, build.as_ref()).await?;
646 }
647 Ok(())
648 }
649
650 pub fn is_bin_link(&self, path: &Path) -> bool {
653 if cfg!(unix) {
654 same_file::is_same_file(path, self.executable(false)).unwrap_or_default()
655 } else if cfg!(windows) {
656 let Some(launcher) = Launcher::try_from_path(path).unwrap_or_default() else {
657 return false;
658 };
659 if !matches!(launcher.kind, LauncherKind::Python) {
660 return false;
661 }
662 dunce::canonicalize(&launcher.python_path).unwrap_or(launcher.python_path)
666 == self.executable(false)
667 } else {
668 unreachable!("Only Windows and Unix are supported")
669 }
670 }
671
672 pub fn is_upgrade_of(&self, other: &Self) -> bool {
674 if self.key.implementation != other.key.implementation {
676 return false;
677 }
678 if self.key.variant != other.key.variant {
680 return false;
681 }
682 if (self.key.major, self.key.minor) != (other.key.major, other.key.minor) {
684 return false;
685 }
686 if self.key.patch == other.key.patch {
689 return match (self.key.prerelease, other.key.prerelease) {
690 (Some(self_pre), Some(other_pre)) => self_pre > other_pre,
692 (None, Some(_)) => true,
694 (Some(_), None) => false,
696 (None, None) => match (self.build.as_deref(), other.build.as_deref()) {
698 (Some(_), None) => true,
700 (Some(self_build), Some(other_build)) => {
702 compare_build_versions(self_build, other_build) == Ordering::Greater
703 }
704 (None, _) => false,
706 },
707 };
708 }
709 if self.key.patch < other.key.patch {
711 return false;
712 }
713 true
714 }
715
716 #[cfg(windows)]
717 pub(crate) fn url(&self) -> Option<&str> {
718 self.url.as_deref()
719 }
720
721 #[cfg(windows)]
722 pub(crate) fn sha256(&self) -> Option<&str> {
723 self.sha256.as_ref().map(Digest::as_str)
724 }
725
726 #[inline]
730 pub fn highest_by_minor_version_key<'a, I>(
731 installations: I,
732 ) -> IndexMap<PythonInstallationMinorVersionKey, Self>
733 where
734 I: IntoIterator<Item = &'a Self>,
735 {
736 let mut minor_versions = IndexMap::default();
737 for installation in installations {
738 minor_versions
739 .entry(installation.minor_version_key().clone())
740 .and_modify(|high_installation: &mut Self| {
741 if installation.key() >= high_installation.key() {
742 *high_installation = installation.clone();
743 }
744 })
745 .or_insert_with(|| installation.clone());
746 }
747 minor_versions
748 }
749}
750
751#[derive(Debug, Clone, Copy)]
753pub enum UpgradePolicy {
754 Fixed,
756 Patch,
758}
759
760impl UpgradePolicy {
761 pub fn from_request(request: &PythonRequest) -> Self {
766 if request.includes_patch() {
767 Self::Fixed
768 } else {
769 Self::Patch
770 }
771 }
772}
773
774#[derive(Clone, Debug)]
777pub struct PythonMinorVersionLink {
778 key: PythonInstallationMinorVersionKey,
780 pub symlink_directory: PathBuf,
782 pub symlink_executable: PathBuf,
785 pub target_directory: PathBuf,
788}
789
790impl PythonMinorVersionLink {
791 fn from_executable(executable: &Path, key: &PythonInstallationKey) -> Option<Self> {
811 let implementation = key.implementation();
812 if !matches!(
813 implementation.as_ref(),
814 LenientImplementationName::Known(ImplementationName::CPython)
815 ) {
816 return None;
818 }
819 let executable_name = executable
820 .file_name()
821 .expect("Executable file name should exist");
822 let symlink_directory_name = PythonInstallationMinorVersionKey::ref_cast(key).to_string();
823 let parent = executable
824 .parent()
825 .expect("Executable should have parent directory");
826
827 let target_directory = if cfg!(unix) {
829 if parent
830 .components()
831 .next_back()
832 .is_some_and(|c| c.as_os_str() == "bin")
833 {
834 parent.parent()?.to_path_buf()
835 } else {
836 return None;
837 }
838 } else if cfg!(windows) {
839 parent.to_path_buf()
840 } else {
841 unimplemented!("Only Windows and Unix systems are supported.")
842 };
843 let symlink_directory = target_directory.with_file_name(symlink_directory_name);
844 if target_directory == symlink_directory {
846 return None;
847 }
848 let symlink_executable = executable_path_from_base(
850 symlink_directory.as_path(),
851 &executable_name.to_string_lossy(),
852 &implementation,
853 *key.os(),
854 );
855 let minor_version_link = Self {
856 key: PythonInstallationMinorVersionKey::ref_cast(key).clone(),
857 symlink_directory,
858 symlink_executable,
859 target_directory,
860 };
861 Some(minor_version_link)
862 }
863
864 pub fn from_installation(installation: &ManagedPythonInstallation) -> Option<Self> {
865 Self::from_executable(installation.executable(false).as_path(), installation.key())
866 }
867
868 pub fn from_interpreter(interpreter: &Interpreter, policy: UpgradePolicy) -> Option<Self> {
872 match policy {
873 UpgradePolicy::Fixed => None,
874 UpgradePolicy::Patch => {
875 let installation = ManagedPythonInstallation::try_from_interpreter(interpreter)?;
876 Self::from_installation(&installation).filter(Self::exists)
877 }
878 }
879 }
880
881 pub fn key(&self) -> &PythonInstallationMinorVersionKey {
883 &self.key
884 }
885
886 fn create_directory(&self) -> Result<(), Error> {
887 match replace_symlink(
888 self.target_directory.as_path(),
889 self.symlink_directory.as_path(),
890 ) {
891 Ok(()) => {
892 debug!(
893 "Created link `{}` -> `{}`",
894 &self.symlink_directory.user_display(),
895 &self.target_directory.user_display(),
896 );
897 }
898 Err(err) if err.kind() == io::ErrorKind::NotFound => {
899 return Err(Error::MissingPythonMinorVersionLinkTargetDirectory(
900 self.target_directory.clone(),
901 ));
902 }
903 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
904 Err(err) => {
905 return Err(Error::PythonMinorVersionLinkDirectory(err));
906 }
907 }
908 Ok(())
909 }
910
911 pub fn exists(&self) -> bool {
918 let points_to_target = || {
919 fs_err::read_link(&self.symlink_directory)
920 .is_ok_and(|target| verbatim_path(&target) == verbatim_path(&self.target_directory))
921 };
922
923 cfg_select! {
924 unix => {
925 self.symlink_directory
926 .symlink_metadata()
927 .is_ok_and(|metadata| metadata.file_type().is_symlink())
928 && points_to_target()
929 },
930 windows => {
931 self.symlink_directory
932 .symlink_metadata()
933 .is_ok_and(|metadata| {
934 (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0) != 0
937 })
938 && points_to_target()
939 },
940 }
941 }
942}
943
944fn executable_path_from_base(
948 base: &Path,
949 executable_name: &str,
950 implementation: &LenientImplementationName,
951 os: Os,
952) -> PathBuf {
953 if matches!(
954 implementation,
955 &LenientImplementationName::Known(ImplementationName::GraalPy)
956 ) {
957 base.join("bin").join(executable_name)
959 } else if os.is_emscripten()
960 || matches!(
961 implementation,
962 &LenientImplementationName::Known(ImplementationName::Pyodide)
963 )
964 {
965 base.join(executable_name)
967 } else if os.is_windows() {
968 base.join(executable_name)
970 } else {
971 base.join("bin").join(executable_name)
973 }
974}
975
976#[derive(Debug, Clone, Copy)]
980pub struct PythonExecutable<'a> {
981 path: &'a Path,
982 window_mode: WindowMode,
983}
984
985impl<'a> PythonExecutable<'a> {
986 pub fn console(path: &'a Path) -> Self {
988 Self {
989 path,
990 window_mode: WindowMode::Console,
991 }
992 }
993
994 pub fn windowed(path: &'a Path) -> Self {
996 Self {
997 path,
998 window_mode: WindowMode::Windowed,
999 }
1000 }
1001}
1002
1003pub fn create_link_to_executable(
1007 link: &Path,
1008 executable: PythonExecutable<'_>,
1009) -> Result<(), Error> {
1010 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1011 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1012
1013 if cfg!(unix) {
1014 match symlink_or_copy_file(executable.path, link) {
1016 Ok(()) => Ok(()),
1017 Err(err) if err.kind() == io::ErrorKind::NotFound => {
1018 Err(Error::MissingExecutable(executable.path.to_path_buf()))
1019 }
1020 Err(err) => Err(Error::LinkExecutable(err)),
1021 }
1022 } else if cfg!(windows) {
1023 let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1024
1025 #[expect(clippy::disallowed_types)]
1028 {
1029 std::fs::File::create_new(link)
1030 .and_then(|mut file| file.write_all(launcher.as_ref()))
1031 .map_err(Error::LinkExecutable)
1032 }
1033 } else {
1034 unimplemented!("Only Windows and Unix are supported.")
1035 }
1036}
1037
1038pub fn replace_link_to_executable(
1044 link: &Path,
1045 executable: PythonExecutable<'_>,
1046) -> Result<(), Error> {
1047 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
1048 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
1049
1050 if cfg!(unix) {
1051 replace_symlink(executable.path, link).map_err(Error::LinkExecutable)
1052 } else if cfg!(windows) {
1053 let launcher = windows_python_launcher(executable.path, executable.window_mode)?;
1054
1055 uv_fs::write_atomic_sync(link, &*launcher).map_err(Error::LinkExecutable)
1056 } else {
1057 unimplemented!("Only Windows and Unix are supported.")
1058 }
1059}
1060
1061pub fn platform_key_from_env() -> Result<String, Error> {
1064 Ok(Platform::from_env()?.to_string().to_lowercase())
1065}
1066
1067impl fmt::Display for ManagedPythonInstallation {
1068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069 write!(
1070 f,
1071 "{}",
1072 self.path
1073 .file_name()
1074 .unwrap_or(self.path.as_os_str())
1075 .to_string_lossy()
1076 )
1077 }
1078}
1079
1080pub fn python_executable_dir() -> Result<PathBuf, Error> {
1082 uv_dirs::user_executable_directory(Some(EnvVars::UV_PYTHON_BIN_DIR))
1083 .ok_or(Error::NoExecutableDirectory)
1084}
1085
1086impl From<&ManagedPythonInstallation> for PythonDownloadRequest {
1087 fn from(installation: &ManagedPythonInstallation) -> Self {
1088 let key = installation.key();
1089 Self::new(
1090 Some(VersionRequest::from(&key.version())),
1091 Some(installation.key_implementation()),
1092 Some(ArchRequest::Explicit(*key.arch())),
1093 Some(*key.os()),
1094 Some(*key.libc()),
1095 Some(key.prerelease.is_some()),
1096 )
1097 }
1098}
1099
1100#[cfg(test)]
1101mod tests {
1102 use super::*;
1103 use std::path::PathBuf;
1104 use std::str::FromStr;
1105 use uv_pep440::{Prerelease, PrereleaseKind};
1106 use uv_platform::Platform;
1107 use uv_python_types::{
1108 ImplementationName, LenientImplementationName, PythonInstallationKey, PythonVariant,
1109 };
1110
1111 fn create_test_installation(
1112 implementation: ImplementationName,
1113 major: u8,
1114 minor: u8,
1115 patch: u8,
1116 prerelease: Option<Prerelease>,
1117 variant: PythonVariant,
1118 build: Option<&str>,
1119 ) -> ManagedPythonInstallation {
1120 let platform = Platform::from_str("linux-x86_64-gnu").unwrap();
1121 let key = PythonInstallationKey::new(
1122 LenientImplementationName::Known(implementation),
1123 major,
1124 minor,
1125 patch,
1126 prerelease,
1127 platform,
1128 variant,
1129 );
1130 ManagedPythonInstallation {
1131 path: PathBuf::from("/test/path"),
1132 key,
1133 implementation,
1134 url: None,
1135 sha256: None,
1136 build: build.map(|s| Cow::Owned(s.to_owned())),
1137 }
1138 }
1139
1140 #[test]
1141 fn test_is_upgrade_of_same_version() {
1142 let installation = create_test_installation(
1143 ImplementationName::CPython,
1144 3,
1145 10,
1146 8,
1147 None,
1148 PythonVariant::Default,
1149 None,
1150 );
1151
1152 assert!(!installation.is_upgrade_of(&installation));
1154 }
1155
1156 #[test]
1157 fn test_is_upgrade_of_patch_version() {
1158 let older = create_test_installation(
1159 ImplementationName::CPython,
1160 3,
1161 10,
1162 8,
1163 None,
1164 PythonVariant::Default,
1165 None,
1166 );
1167 let newer = create_test_installation(
1168 ImplementationName::CPython,
1169 3,
1170 10,
1171 9,
1172 None,
1173 PythonVariant::Default,
1174 None,
1175 );
1176
1177 assert!(newer.is_upgrade_of(&older));
1179 assert!(!older.is_upgrade_of(&newer));
1181 }
1182
1183 #[test]
1184 fn test_is_upgrade_of_different_minor_version() {
1185 let py310 = create_test_installation(
1186 ImplementationName::CPython,
1187 3,
1188 10,
1189 8,
1190 None,
1191 PythonVariant::Default,
1192 None,
1193 );
1194 let py311 = create_test_installation(
1195 ImplementationName::CPython,
1196 3,
1197 11,
1198 0,
1199 None,
1200 PythonVariant::Default,
1201 None,
1202 );
1203
1204 assert!(!py311.is_upgrade_of(&py310));
1206 assert!(!py310.is_upgrade_of(&py311));
1207 }
1208
1209 #[test]
1210 fn test_is_upgrade_of_different_implementation() {
1211 let cpython = create_test_installation(
1212 ImplementationName::CPython,
1213 3,
1214 10,
1215 8,
1216 None,
1217 PythonVariant::Default,
1218 None,
1219 );
1220 let pypy = create_test_installation(
1221 ImplementationName::PyPy,
1222 3,
1223 10,
1224 9,
1225 None,
1226 PythonVariant::Default,
1227 None,
1228 );
1229
1230 assert!(!pypy.is_upgrade_of(&cpython));
1232 assert!(!cpython.is_upgrade_of(&pypy));
1233 }
1234
1235 #[test]
1236 fn test_is_upgrade_of_different_variant() {
1237 let default = create_test_installation(
1238 ImplementationName::CPython,
1239 3,
1240 10,
1241 8,
1242 None,
1243 PythonVariant::Default,
1244 None,
1245 );
1246 let freethreaded = create_test_installation(
1247 ImplementationName::CPython,
1248 3,
1249 10,
1250 9,
1251 None,
1252 PythonVariant::Freethreaded,
1253 None,
1254 );
1255
1256 assert!(!freethreaded.is_upgrade_of(&default));
1258 assert!(!default.is_upgrade_of(&freethreaded));
1259 }
1260
1261 #[test]
1262 fn test_is_upgrade_of_prerelease() {
1263 let stable = create_test_installation(
1264 ImplementationName::CPython,
1265 3,
1266 10,
1267 8,
1268 None,
1269 PythonVariant::Default,
1270 None,
1271 );
1272 let prerelease = create_test_installation(
1273 ImplementationName::CPython,
1274 3,
1275 10,
1276 8,
1277 Some(Prerelease {
1278 kind: PrereleaseKind::Alpha,
1279 number: 1,
1280 }),
1281 PythonVariant::Default,
1282 None,
1283 );
1284
1285 assert!(stable.is_upgrade_of(&prerelease));
1287
1288 assert!(!prerelease.is_upgrade_of(&stable));
1290 }
1291
1292 #[test]
1293 fn test_is_upgrade_of_prerelease_to_prerelease() {
1294 let alpha1 = create_test_installation(
1295 ImplementationName::CPython,
1296 3,
1297 10,
1298 8,
1299 Some(Prerelease {
1300 kind: PrereleaseKind::Alpha,
1301 number: 1,
1302 }),
1303 PythonVariant::Default,
1304 None,
1305 );
1306 let alpha2 = create_test_installation(
1307 ImplementationName::CPython,
1308 3,
1309 10,
1310 8,
1311 Some(Prerelease {
1312 kind: PrereleaseKind::Alpha,
1313 number: 2,
1314 }),
1315 PythonVariant::Default,
1316 None,
1317 );
1318
1319 assert!(alpha2.is_upgrade_of(&alpha1));
1321 assert!(!alpha1.is_upgrade_of(&alpha2));
1323 }
1324
1325 #[test]
1326 fn test_is_upgrade_of_prerelease_same_patch() {
1327 let prerelease = create_test_installation(
1328 ImplementationName::CPython,
1329 3,
1330 10,
1331 8,
1332 Some(Prerelease {
1333 kind: PrereleaseKind::Alpha,
1334 number: 1,
1335 }),
1336 PythonVariant::Default,
1337 None,
1338 );
1339
1340 assert!(!prerelease.is_upgrade_of(&prerelease));
1342 }
1343
1344 #[test]
1345 fn test_is_upgrade_of_build_version() {
1346 let older_build = create_test_installation(
1347 ImplementationName::CPython,
1348 3,
1349 10,
1350 8,
1351 None,
1352 PythonVariant::Default,
1353 Some("20240101"),
1354 );
1355 let newer_build = create_test_installation(
1356 ImplementationName::CPython,
1357 3,
1358 10,
1359 8,
1360 None,
1361 PythonVariant::Default,
1362 Some("20240201"),
1363 );
1364
1365 assert!(newer_build.is_upgrade_of(&older_build));
1367 assert!(!older_build.is_upgrade_of(&newer_build));
1369 }
1370
1371 #[test]
1372 fn test_is_upgrade_of_build_version_same() {
1373 let installation = create_test_installation(
1374 ImplementationName::CPython,
1375 3,
1376 10,
1377 8,
1378 None,
1379 PythonVariant::Default,
1380 Some("20240101"),
1381 );
1382
1383 assert!(!installation.is_upgrade_of(&installation));
1385 }
1386
1387 #[test]
1388 fn test_is_upgrade_of_build_with_legacy_installation() {
1389 let legacy = create_test_installation(
1390 ImplementationName::CPython,
1391 3,
1392 10,
1393 8,
1394 None,
1395 PythonVariant::Default,
1396 None,
1397 );
1398 let with_build = create_test_installation(
1399 ImplementationName::CPython,
1400 3,
1401 10,
1402 8,
1403 None,
1404 PythonVariant::Default,
1405 Some("20240101"),
1406 );
1407
1408 assert!(with_build.is_upgrade_of(&legacy));
1410 assert!(!legacy.is_upgrade_of(&with_build));
1412 }
1413
1414 #[test]
1415 fn test_is_upgrade_of_patch_takes_precedence_over_build() {
1416 let older_patch_newer_build = create_test_installation(
1417 ImplementationName::CPython,
1418 3,
1419 10,
1420 8,
1421 None,
1422 PythonVariant::Default,
1423 Some("20240201"),
1424 );
1425 let newer_patch_older_build = create_test_installation(
1426 ImplementationName::CPython,
1427 3,
1428 10,
1429 9,
1430 None,
1431 PythonVariant::Default,
1432 Some("20240101"),
1433 );
1434
1435 assert!(newer_patch_older_build.is_upgrade_of(&older_patch_newer_build));
1437 assert!(!older_patch_newer_build.is_upgrade_of(&newer_patch_older_build));
1439 }
1440
1441 #[test]
1442 fn test_find_version_matching() {
1443 use uv_python_types::PythonVersion;
1444
1445 let platform = Platform::from_env().unwrap();
1446 let temp_dir = tempfile::tempdir().unwrap();
1447
1448 fs::create_dir(temp_dir.path().join(format!("cpython-3.10.0-{platform}"))).unwrap();
1450
1451 temp_env::with_var(
1452 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1453 Some(temp_dir.path()),
1454 || {
1455 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1456
1457 let v3_1 = PythonVersion::from_str("3.1").unwrap();
1459 let matched: Vec<_> = installations.find_version(&v3_1).unwrap().collect();
1460 assert_eq!(matched.len(), 0);
1461
1462 let v3_10 = PythonVersion::from_str("3.10").unwrap();
1464 let matched: Vec<_> = installations.find_version(&v3_10).unwrap().collect();
1465 assert_eq!(matched.len(), 1);
1466 },
1467 );
1468 }
1469
1470 #[test]
1471 fn test_relative_install_dir_resolves_against_pwd() {
1472 let temp_dir = tempfile::tempdir().unwrap();
1473 let workdir = temp_dir.path().join("workdir");
1474 fs::create_dir(&workdir).unwrap();
1475
1476 temp_env::with_vars(
1477 [
1478 (
1479 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1480 Some(std::ffi::OsStr::new(".python-installs")),
1481 ),
1482 (uv_static::EnvVars::PWD, Some(workdir.as_os_str())),
1483 ],
1484 || {
1485 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1486 assert_eq!(
1487 installations.absolute_root().unwrap(),
1488 workdir.join(".python-installs")
1489 );
1490 },
1491 );
1492 }
1493}