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