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 itertools::Itertools;
13use thiserror::Error;
14use tracing::{debug, warn};
15#[cfg(windows)]
16use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
17
18use uv_fs::{
19 LockedFile, LockedFileError, LockedFileMode, Simplified, normalize_absolute_path,
20 replace_symlink, symlink_or_copy_file, verbatim_path,
21};
22use uv_platform::{Error as PlatformError, Os};
23use uv_platform::{LibcDetectionError, Platform};
24use uv_state::{StateBucket, StateStore};
25use uv_static::EnvVars;
26use uv_trampoline_builder::{Launcher, LauncherKind};
27
28use crate::discovery::VersionRequest;
29use crate::downloads::{Error as DownloadError, ManagedPythonDownload};
30use crate::implementation::{
31 Error as ImplementationError, ImplementationName, LenientImplementationName,
32};
33use crate::installation::{self, PythonInstallationKey};
34use crate::interpreter::Interpreter;
35use crate::python_version::PythonVersion;
36use crate::{PythonInstallationMinorVersionKey, PythonVariant, macos_dylib, sysconfig};
37
38#[derive(Error, Debug)]
39pub enum Error {
40 #[error(transparent)]
41 Io(#[from] io::Error),
42 #[error(transparent)]
43 LockedFile(#[from] LockedFileError),
44 #[error(transparent)]
45 Download(#[from] DownloadError),
46 #[error(transparent)]
47 PlatformError(#[from] PlatformError),
48 #[error(transparent)]
49 ImplementationError(#[from] ImplementationError),
50 #[error("Invalid python version: {0}")]
51 InvalidPythonVersion(String),
52 #[error(transparent)]
53 ExtractError(#[from] uv_extract::Error),
54 #[error(transparent)]
55 SysconfigError(#[from] sysconfig::Error),
56 #[error("Missing expected Python executable at {}", _0.user_display())]
57 MissingExecutable(PathBuf),
58 #[error("Missing expected target directory for Python minor version link at {}", _0.user_display())]
59 MissingPythonMinorVersionLinkTargetDirectory(PathBuf),
60 #[error("Failed to create canonical Python executable")]
61 CanonicalizeExecutable(#[source] io::Error),
62 #[error("Failed to create Python executable link")]
63 LinkExecutable(#[source] io::Error),
64 #[error("Failed to create Python minor version link directory")]
65 PythonMinorVersionLinkDirectory(#[source] io::Error),
66 #[error("Failed to create directory for Python executable link")]
67 ExecutableDirectory(#[source] io::Error),
68 #[error("Failed to read Python installation directory")]
69 ReadError(#[source] io::Error),
70 #[error("Failed to find a directory to install executables into")]
71 NoExecutableDirectory,
72 #[error(transparent)]
73 LauncherError(#[from] uv_trampoline_builder::Error),
74 #[error("Failed to read managed Python directory name: {0}")]
75 NameError(String),
76 #[error("Failed to construct absolute path to managed Python directory: {}", _0.user_display())]
77 AbsolutePath(PathBuf, #[source] io::Error),
78 #[error(transparent)]
79 NameParseError(#[from] installation::PythonInstallationKeyError),
80 #[error("Failed to determine the libc used on the current platform")]
81 LibcDetection(#[from] LibcDetectionError),
82 #[error(transparent)]
83 MacOsDylib(#[from] macos_dylib::Error),
84}
85
86pub fn compare_build_versions(a: &str, b: &str) -> Ordering {
91 match (a.parse::<u64>(), b.parse::<u64>()) {
92 (Ok(a_num), Ok(b_num)) => a_num.cmp(&b_num),
93 _ => a.cmp(b),
94 }
95}
96
97#[derive(Debug, Clone, Eq, PartialEq)]
99pub struct ManagedPythonInstallations {
100 root: PathBuf,
102}
103
104impl ManagedPythonInstallations {
105 fn from_path(root: impl Into<PathBuf>) -> Self {
107 Self { root: root.into() }
108 }
109
110 pub async fn lock(&self) -> Result<LockedFile, Error> {
113 Ok(LockedFile::acquire(
114 self.root.join(".lock"),
115 LockedFileMode::Exclusive,
116 self.root.user_display(),
117 )
118 .await?)
119 }
120
121 pub fn from_settings(install_dir: Option<PathBuf>) -> Result<Self, Error> {
128 if let Some(install_dir) = install_dir {
129 Ok(Self::from_path(install_dir))
130 } else if let Some(install_dir) =
131 std::env::var_os(EnvVars::UV_PYTHON_INSTALL_DIR).filter(|s| !s.is_empty())
132 {
133 Ok(Self::from_path(install_dir))
134 } else {
135 Ok(Self::from_path(
136 StateStore::from_settings(None)?.bucket(StateBucket::ManagedPython),
137 ))
138 }
139 }
140
141 #[cfg(all(test, unix))]
143 pub(crate) fn temp() -> Result<Self, Error> {
144 Ok(Self::from_path(
145 StateStore::temp()?.bucket(StateBucket::ManagedPython),
146 ))
147 }
148
149 pub fn scratch(&self) -> PathBuf {
151 self.root.join(".temp")
152 }
153
154 pub fn init(self) -> Result<Self, Error> {
158 let root = &self.root;
159
160 if !root.exists()
162 && root
163 .parent()
164 .is_some_and(|parent| parent.join("toolchains").exists())
165 {
166 let deprecated = root.parent().unwrap().join("toolchains");
167 fs::rename(&deprecated, root)?;
169 uv_fs::replace_symlink(root, &deprecated)?;
171 } else {
172 fs::create_dir_all(root)?;
173 }
174
175 fs::create_dir_all(root)?;
177
178 let scratch = self.scratch();
180 fs::create_dir_all(&scratch)?;
181
182 match fs::OpenOptions::new()
184 .write(true)
185 .create_new(true)
186 .open(root.join(".gitignore"))
187 {
188 Ok(mut file) => file.write_all(b"*")?,
189 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
190 Err(err) => return Err(err.into()),
191 }
192
193 Ok(self)
194 }
195
196 pub fn find_all(
201 &self,
202 ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
203 let dirs = match fs_err::read_dir(&self.root) {
204 Ok(installation_dirs) => {
205 let directories: Vec<_> = installation_dirs
207 .filter_map(|read_dir| match read_dir {
208 Ok(entry) => match entry.file_type() {
209 Ok(file_type) => file_type.is_dir().then_some(Ok(entry.path())),
210 Err(err) => Some(Err(err)),
211 },
212 Err(err) => Some(Err(err)),
213 })
214 .collect::<Result<_, io::Error>>()
215 .map_err(Error::ReadError)?;
216 directories
217 }
218 Err(err) if err.kind() == io::ErrorKind::NotFound => vec![],
219 Err(err) => {
220 return Err(Error::ReadError(err));
221 }
222 };
223 let scratch = self.scratch();
224 Ok(dirs
225 .into_iter()
226 .filter(|path| *path != scratch)
228 .filter(|path| {
230 path.file_name()
231 .and_then(OsStr::to_str)
232 .is_none_or(|name| !name.starts_with('.'))
233 })
234 .filter_map(|path| {
235 ManagedPythonInstallation::from_path(path)
236 .inspect_err(|err| {
237 warn!("Ignoring malformed managed Python entry:\n {err}");
238 })
239 .ok()
240 })
241 .sorted_unstable_by_key(|installation| Reverse(installation.key().clone())))
242 }
243
244 pub(crate) fn find_matching_current_platform()
246 -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> {
247 let platform = Platform::from_env()?;
248
249 let iter = Self::from_settings(None)?
250 .find_all()?
251 .filter(move |installation| {
252 if !platform.supports(installation.platform()) {
253 debug!("Skipping managed installation `{installation}`: not supported by current platform `{platform}`");
254 return false;
255 }
256 true
257 });
258
259 Ok(iter)
260 }
261
262 pub fn find_version<'a>(
269 &'a self,
270 version: &'a PythonVersion,
271 ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + 'a, Error> {
272 let request = VersionRequest::from(version);
273 Ok(Self::find_matching_current_platform()?
274 .filter(move |installation| request.matches_installation_key(installation.key())))
275 }
276
277 pub fn root(&self) -> &Path {
278 &self.root
279 }
280
281 pub(crate) fn absolute_root(&self) -> Result<PathBuf, Error> {
282 let root = if self.root.is_absolute() {
283 self.root.clone()
284 } else {
285 crate::current_dir()?.join(&self.root)
286 };
287
288 normalize_absolute_path(&root).map_err(|err| Error::AbsolutePath(self.root.clone(), err))
289 }
290}
291
292static EXTERNALLY_MANAGED: &str = "[externally-managed]
293Error=This Python installation is managed by uv and should not be modified.
294";
295
296#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
298pub struct ManagedPythonInstallation {
299 path: PathBuf,
301 key: PythonInstallationKey,
303 url: Option<Cow<'static, str>>,
307 sha256: Option<Cow<'static, str>>,
311 build: Option<Cow<'static, str>>,
315}
316
317impl ManagedPythonInstallation {
318 pub fn new(path: PathBuf, download: &ManagedPythonDownload) -> Self {
319 Self {
320 path,
321 key: download.key().clone(),
322 url: Some(download.url().clone()),
323 sha256: download.sha256().cloned(),
324 build: download.build().map(Cow::Borrowed),
325 }
326 }
327
328 fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
329 let path = path.as_ref();
330
331 let key = PythonInstallationKey::from_str(
332 path.file_name()
333 .ok_or(Error::NameError("name is empty".to_string()))?
334 .to_str()
335 .ok_or(Error::NameError("not a valid string".to_string()))?,
336 )?;
337
338 let path = std::path::absolute(path)
339 .map_err(|err| Error::AbsolutePath(path.to_path_buf(), err))?;
340
341 let build = match fs::read_to_string(path.join("BUILD")) {
343 Ok(content) => Some(Cow::Owned(content.trim().to_string())),
344 Err(err) if err.kind() == io::ErrorKind::NotFound => None,
345 Err(err) => return Err(err.into()),
346 };
347
348 Ok(Self {
349 path,
350 key,
351 url: None,
352 sha256: None,
353 build,
354 })
355 }
356
357 pub fn try_from_interpreter(interpreter: &Interpreter) -> Option<Self> {
361 let managed_root = ManagedPythonInstallations::from_settings(None).ok()?;
362 let root = managed_root.absolute_root().ok()?;
363
364 let sys_base_prefix = dunce::canonicalize(interpreter.sys_base_prefix())
368 .unwrap_or_else(|_| interpreter.sys_base_prefix().to_path_buf());
369 let root = dunce::canonicalize(&root).unwrap_or(root);
370
371 let suffix = sys_base_prefix.strip_prefix(&root).ok()?;
373
374 let first_component = suffix.components().next()?;
375 let name = first_component.as_os_str().to_str()?;
376
377 PythonInstallationKey::from_str(name).ok()?;
379
380 let path = root.join(name);
382 Self::from_path(path).ok()
383 }
384
385 pub fn executable(&self, windowed: bool) -> PathBuf {
394 let version = match self.implementation() {
395 ImplementationName::CPython => {
396 if cfg!(unix) {
397 format!("{}.{}", self.key.major, self.key.minor)
398 } else {
399 String::new()
400 }
401 }
402 ImplementationName::PyPy => format!("{}.{}", self.key.major, self.key.minor),
404 ImplementationName::Pyodide => String::new(),
406 ImplementationName::GraalPy => String::new(),
407 };
408
409 let variant = if self.implementation() == ImplementationName::GraalPy {
412 ""
413 } else if cfg!(unix) {
414 self.key.variant.executable_suffix()
415 } else if cfg!(windows) && windowed {
416 "w"
418 } else {
419 ""
420 };
421
422 let name = format!(
423 "{implementation}{version}{variant}{exe}",
424 implementation = self.implementation().executable_name(),
425 exe = std::env::consts::EXE_SUFFIX
426 );
427
428 let executable = executable_path_from_base(
429 self.python_dir().as_path(),
430 &name,
431 &LenientImplementationName::from(self.implementation()),
432 *self.key.os(),
433 );
434
435 if cfg!(windows)
440 && matches!(self.key.variant, PythonVariant::Freethreaded)
441 && !executable.exists()
442 {
443 return self.python_dir().join(format!(
445 "python{}.{}t{}",
446 self.key.major,
447 self.key.minor,
448 std::env::consts::EXE_SUFFIX
449 ));
450 }
451
452 executable
453 }
454
455 fn python_dir(&self) -> PathBuf {
456 let install = self.path.join("install");
457 if install.is_dir() {
458 install
459 } else {
460 self.path.clone()
461 }
462 }
463
464 pub(crate) fn version(&self) -> PythonVersion {
466 self.key.version()
467 }
468
469 pub fn implementation(&self) -> ImplementationName {
470 match self.key.implementation().into_owned() {
471 LenientImplementationName::Known(implementation) => implementation,
472 LenientImplementationName::Unknown(_) => {
473 panic!("Managed Python installations should have a known implementation")
474 }
475 }
476 }
477
478 pub fn path(&self) -> &Path {
479 &self.path
480 }
481
482 pub fn key(&self) -> &PythonInstallationKey {
483 &self.key
484 }
485
486 pub(crate) fn platform(&self) -> &Platform {
487 self.key.platform()
488 }
489
490 pub fn build(&self) -> Option<&str> {
492 self.build.as_deref()
493 }
494
495 pub fn minor_version_key(&self) -> &PythonInstallationMinorVersionKey {
496 PythonInstallationMinorVersionKey::ref_cast(&self.key)
497 }
498
499 pub fn ensure_canonical_executables(&self) -> Result<(), Error> {
501 let python = self.executable(false);
502
503 let canonical_names = &["python"];
504
505 for name in canonical_names {
506 let executable =
507 python.with_file_name(format!("{name}{exe}", exe = std::env::consts::EXE_SUFFIX));
508
509 if executable == python {
512 continue;
513 }
514
515 match symlink_or_copy_file(&python, &executable) {
516 Ok(()) => {
517 debug!(
518 "Created link {} -> {}",
519 executable.user_display(),
520 python.user_display(),
521 );
522 }
523 Err(err) if err.kind() == io::ErrorKind::NotFound => {
524 return Err(Error::MissingExecutable(python.clone()));
525 }
526 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
527 Err(err) => {
528 return Err(Error::CanonicalizeExecutable(err));
529 }
530 }
531 }
532
533 Ok(())
534 }
535
536 pub fn ensure_minor_version_link(&self) -> Result<(), Error> {
539 if let Some(minor_version_link) = PythonMinorVersionLink::from_installation(self) {
540 minor_version_link.create_directory()?;
541 }
542 Ok(())
543 }
544
545 pub fn ensure_externally_managed(&self) -> Result<(), Error> {
548 if self.key.os().is_emscripten() {
549 return Ok(());
552 }
553 let stdlib = if self.key.os().is_windows() {
555 self.python_dir().join("Lib")
556 } else {
557 let lib_suffix = self.key.variant.lib_suffix();
558 let python = if matches!(
559 self.key.implementation,
560 LenientImplementationName::Known(ImplementationName::PyPy)
561 ) {
562 format!("pypy{}", self.key.version().python_version())
563 } else {
564 format!("python{}{lib_suffix}", self.key.version().python_version())
565 };
566 self.python_dir().join("lib").join(python)
567 };
568
569 let file = stdlib.join("EXTERNALLY-MANAGED");
570 fs_err::write(file, EXTERNALLY_MANAGED)?;
571
572 Ok(())
573 }
574
575 pub fn ensure_sysconfig_patched(&self) -> Result<(), Error> {
577 if cfg!(unix) && !self.key.os().is_windows() {
578 if self.key.os().is_emscripten() {
579 return Ok(());
582 }
583 if self.implementation() == ImplementationName::CPython {
584 sysconfig::update_sysconfig(
585 self.path(),
586 self.key.major,
587 self.key.minor,
588 self.key.variant.lib_suffix(),
589 )?;
590 }
591 }
592 Ok(())
593 }
594
595 pub fn ensure_dylib_patched(&self) -> Result<(), macos_dylib::Error> {
602 if cfg!(target_os = "macos") {
603 if self.key().os().is_like_darwin() {
604 if self.implementation() == ImplementationName::CPython {
605 let dylib_path = self.python_dir().join("lib").join(format!(
606 "{}python{}{}{}",
607 std::env::consts::DLL_PREFIX,
608 self.key.version().python_version(),
609 self.key.variant().executable_suffix(),
610 std::env::consts::DLL_SUFFIX
611 ));
612 macos_dylib::patch_dylib_install_name(dylib_path)?;
613 }
614 }
615 }
616 Ok(())
617 }
618
619 pub fn ensure_build_file(&self) -> Result<(), Error> {
621 if let Some(ref build) = self.build {
622 let build_file = self.path.join("BUILD");
623 fs::write(&build_file, build.as_ref())?;
624 }
625 Ok(())
626 }
627
628 pub fn is_bin_link(&self, path: &Path) -> bool {
631 if cfg!(unix) {
632 same_file::is_same_file(path, self.executable(false)).unwrap_or_default()
633 } else if cfg!(windows) {
634 let Some(launcher) = Launcher::try_from_path(path).unwrap_or_default() else {
635 return false;
636 };
637 if !matches!(launcher.kind, LauncherKind::Python) {
638 return false;
639 }
640 dunce::canonicalize(&launcher.python_path).unwrap_or(launcher.python_path)
644 == self.executable(false)
645 } else {
646 unreachable!("Only Windows and Unix are supported")
647 }
648 }
649
650 pub fn is_upgrade_of(&self, other: &Self) -> bool {
652 if self.key.implementation != other.key.implementation {
654 return false;
655 }
656 if self.key.variant != other.key.variant {
658 return false;
659 }
660 if (self.key.major, self.key.minor) != (other.key.major, other.key.minor) {
662 return false;
663 }
664 if self.key.patch == other.key.patch {
667 return match (self.key.prerelease, other.key.prerelease) {
668 (Some(self_pre), Some(other_pre)) => self_pre > other_pre,
670 (None, Some(_)) => true,
672 (Some(_), None) => false,
674 (None, None) => match (self.build.as_deref(), other.build.as_deref()) {
676 (Some(_), None) => true,
678 (Some(self_build), Some(other_build)) => {
680 compare_build_versions(self_build, other_build) == Ordering::Greater
681 }
682 (None, _) => false,
684 },
685 };
686 }
687 if self.key.patch < other.key.patch {
689 return false;
690 }
691 true
692 }
693
694 #[cfg(windows)]
695 pub(crate) fn url(&self) -> Option<&str> {
696 self.url.as_deref()
697 }
698
699 #[cfg(windows)]
700 pub(crate) fn sha256(&self) -> Option<&str> {
701 self.sha256.as_deref()
702 }
703}
704
705#[derive(Clone, Debug)]
708pub struct PythonMinorVersionLink {
709 pub symlink_directory: PathBuf,
711 pub symlink_executable: PathBuf,
714 pub target_directory: PathBuf,
717}
718
719impl PythonMinorVersionLink {
720 fn from_executable(executable: &Path, key: &PythonInstallationKey) -> Option<Self> {
740 let implementation = key.implementation();
741 if !matches!(
742 implementation.as_ref(),
743 LenientImplementationName::Known(ImplementationName::CPython)
744 ) {
745 return None;
747 }
748 let executable_name = executable
749 .file_name()
750 .expect("Executable file name should exist");
751 let symlink_directory_name = PythonInstallationMinorVersionKey::ref_cast(key).to_string();
752 let parent = executable
753 .parent()
754 .expect("Executable should have parent directory");
755
756 let target_directory = if cfg!(unix) {
758 if parent
759 .components()
760 .next_back()
761 .is_some_and(|c| c.as_os_str() == "bin")
762 {
763 parent.parent()?.to_path_buf()
764 } else {
765 return None;
766 }
767 } else if cfg!(windows) {
768 parent.to_path_buf()
769 } else {
770 unimplemented!("Only Windows and Unix systems are supported.")
771 };
772 let symlink_directory = target_directory.with_file_name(symlink_directory_name);
773 if target_directory == symlink_directory {
775 return None;
776 }
777 let symlink_executable = executable_path_from_base(
779 symlink_directory.as_path(),
780 &executable_name.to_string_lossy(),
781 &implementation,
782 *key.os(),
783 );
784 let minor_version_link = Self {
785 symlink_directory,
786 symlink_executable,
787 target_directory,
788 };
789 Some(minor_version_link)
790 }
791
792 pub fn from_installation(installation: &ManagedPythonInstallation) -> Option<Self> {
793 Self::from_executable(installation.executable(false).as_path(), installation.key())
794 }
795
796 fn create_directory(&self) -> Result<(), Error> {
797 match replace_symlink(
798 self.target_directory.as_path(),
799 self.symlink_directory.as_path(),
800 ) {
801 Ok(()) => {
802 debug!(
803 "Created link {} -> {}",
804 &self.symlink_directory.user_display(),
805 &self.target_directory.user_display(),
806 );
807 }
808 Err(err) if err.kind() == io::ErrorKind::NotFound => {
809 return Err(Error::MissingPythonMinorVersionLinkTargetDirectory(
810 self.target_directory.clone(),
811 ));
812 }
813 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
814 Err(err) => {
815 return Err(Error::PythonMinorVersionLinkDirectory(err));
816 }
817 }
818 Ok(())
819 }
820
821 pub fn exists(&self) -> bool {
828 let points_to_target = || {
829 fs_err::read_link(&self.symlink_directory)
830 .is_ok_and(|target| verbatim_path(&target) == verbatim_path(&self.target_directory))
831 };
832
833 #[cfg(unix)]
834 {
835 self.symlink_directory
836 .symlink_metadata()
837 .is_ok_and(|metadata| metadata.file_type().is_symlink())
838 && points_to_target()
839 }
840 #[cfg(windows)]
841 {
842 self.symlink_directory
843 .symlink_metadata()
844 .is_ok_and(|metadata| {
845 (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0) != 0
848 })
849 && points_to_target()
850 }
851 }
852}
853
854fn executable_path_from_base(
858 base: &Path,
859 executable_name: &str,
860 implementation: &LenientImplementationName,
861 os: Os,
862) -> PathBuf {
863 if matches!(
864 implementation,
865 &LenientImplementationName::Known(ImplementationName::GraalPy)
866 ) {
867 base.join("bin").join(executable_name)
869 } else if os.is_emscripten()
870 || matches!(
871 implementation,
872 &LenientImplementationName::Known(ImplementationName::Pyodide)
873 )
874 {
875 base.join(executable_name)
877 } else if os.is_windows() {
878 base.join(executable_name)
880 } else {
881 base.join("bin").join(executable_name)
883 }
884}
885
886pub fn create_link_to_executable(link: &Path, executable: &Path) -> Result<(), Error> {
890 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
891 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
892
893 if cfg!(unix) {
894 match symlink_or_copy_file(executable, link) {
896 Ok(()) => Ok(()),
897 Err(err) if err.kind() == io::ErrorKind::NotFound => {
898 Err(Error::MissingExecutable(executable.to_path_buf()))
899 }
900 Err(err) => Err(Error::LinkExecutable(err)),
901 }
902 } else if cfg!(windows) {
903 use uv_trampoline_builder::windows_python_launcher;
904
905 let launcher = windows_python_launcher(executable, false)?;
907
908 #[expect(clippy::disallowed_types)]
911 {
912 std::fs::File::create_new(link)
913 .and_then(|mut file| file.write_all(launcher.as_ref()))
914 .map_err(Error::LinkExecutable)
915 }
916 } else {
917 unimplemented!("Only Windows and Unix are supported.")
918 }
919}
920
921pub fn replace_link_to_executable(link: &Path, executable: &Path) -> Result<(), Error> {
927 let link_parent = link.parent().ok_or(Error::NoExecutableDirectory)?;
928 fs_err::create_dir_all(link_parent).map_err(Error::ExecutableDirectory)?;
929
930 if cfg!(unix) {
931 replace_symlink(executable, link).map_err(Error::LinkExecutable)
932 } else if cfg!(windows) {
933 use uv_trampoline_builder::windows_python_launcher;
934
935 let launcher = windows_python_launcher(executable, false)?;
936
937 uv_fs::write_atomic_sync(link, &*launcher).map_err(Error::LinkExecutable)
938 } else {
939 unimplemented!("Only Windows and Unix are supported.")
940 }
941}
942
943pub fn platform_key_from_env() -> Result<String, Error> {
946 Ok(Platform::from_env()?.to_string().to_lowercase())
947}
948
949impl fmt::Display for ManagedPythonInstallation {
950 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
951 write!(
952 f,
953 "{}",
954 self.path
955 .file_name()
956 .unwrap_or(self.path.as_os_str())
957 .to_string_lossy()
958 )
959 }
960}
961
962pub fn python_executable_dir() -> Result<PathBuf, Error> {
964 uv_dirs::user_executable_directory(Some(EnvVars::UV_PYTHON_BIN_DIR))
965 .ok_or(Error::NoExecutableDirectory)
966}
967
968#[cfg(test)]
969mod tests {
970 use super::*;
971 use crate::implementation::LenientImplementationName;
972 use crate::installation::PythonInstallationKey;
973 use crate::{ImplementationName, PythonVariant};
974 use std::path::PathBuf;
975 use std::str::FromStr;
976 use uv_pep440::{Prerelease, PrereleaseKind};
977 use uv_platform::Platform;
978
979 fn create_test_installation(
980 implementation: ImplementationName,
981 major: u8,
982 minor: u8,
983 patch: u8,
984 prerelease: Option<Prerelease>,
985 variant: PythonVariant,
986 build: Option<&str>,
987 ) -> ManagedPythonInstallation {
988 let platform = Platform::from_str("linux-x86_64-gnu").unwrap();
989 let key = PythonInstallationKey::new(
990 LenientImplementationName::Known(implementation),
991 major,
992 minor,
993 patch,
994 prerelease,
995 platform,
996 variant,
997 );
998 ManagedPythonInstallation {
999 path: PathBuf::from("/test/path"),
1000 key,
1001 url: None,
1002 sha256: None,
1003 build: build.map(|s| Cow::Owned(s.to_owned())),
1004 }
1005 }
1006
1007 #[test]
1008 fn test_is_upgrade_of_same_version() {
1009 let installation = create_test_installation(
1010 ImplementationName::CPython,
1011 3,
1012 10,
1013 8,
1014 None,
1015 PythonVariant::Default,
1016 None,
1017 );
1018
1019 assert!(!installation.is_upgrade_of(&installation));
1021 }
1022
1023 #[test]
1024 fn test_is_upgrade_of_patch_version() {
1025 let older = create_test_installation(
1026 ImplementationName::CPython,
1027 3,
1028 10,
1029 8,
1030 None,
1031 PythonVariant::Default,
1032 None,
1033 );
1034 let newer = create_test_installation(
1035 ImplementationName::CPython,
1036 3,
1037 10,
1038 9,
1039 None,
1040 PythonVariant::Default,
1041 None,
1042 );
1043
1044 assert!(newer.is_upgrade_of(&older));
1046 assert!(!older.is_upgrade_of(&newer));
1048 }
1049
1050 #[test]
1051 fn test_is_upgrade_of_different_minor_version() {
1052 let py310 = create_test_installation(
1053 ImplementationName::CPython,
1054 3,
1055 10,
1056 8,
1057 None,
1058 PythonVariant::Default,
1059 None,
1060 );
1061 let py311 = create_test_installation(
1062 ImplementationName::CPython,
1063 3,
1064 11,
1065 0,
1066 None,
1067 PythonVariant::Default,
1068 None,
1069 );
1070
1071 assert!(!py311.is_upgrade_of(&py310));
1073 assert!(!py310.is_upgrade_of(&py311));
1074 }
1075
1076 #[test]
1077 fn test_is_upgrade_of_different_implementation() {
1078 let cpython = create_test_installation(
1079 ImplementationName::CPython,
1080 3,
1081 10,
1082 8,
1083 None,
1084 PythonVariant::Default,
1085 None,
1086 );
1087 let pypy = create_test_installation(
1088 ImplementationName::PyPy,
1089 3,
1090 10,
1091 9,
1092 None,
1093 PythonVariant::Default,
1094 None,
1095 );
1096
1097 assert!(!pypy.is_upgrade_of(&cpython));
1099 assert!(!cpython.is_upgrade_of(&pypy));
1100 }
1101
1102 #[test]
1103 fn test_is_upgrade_of_different_variant() {
1104 let default = create_test_installation(
1105 ImplementationName::CPython,
1106 3,
1107 10,
1108 8,
1109 None,
1110 PythonVariant::Default,
1111 None,
1112 );
1113 let freethreaded = create_test_installation(
1114 ImplementationName::CPython,
1115 3,
1116 10,
1117 9,
1118 None,
1119 PythonVariant::Freethreaded,
1120 None,
1121 );
1122
1123 assert!(!freethreaded.is_upgrade_of(&default));
1125 assert!(!default.is_upgrade_of(&freethreaded));
1126 }
1127
1128 #[test]
1129 fn test_is_upgrade_of_prerelease() {
1130 let stable = create_test_installation(
1131 ImplementationName::CPython,
1132 3,
1133 10,
1134 8,
1135 None,
1136 PythonVariant::Default,
1137 None,
1138 );
1139 let prerelease = create_test_installation(
1140 ImplementationName::CPython,
1141 3,
1142 10,
1143 8,
1144 Some(Prerelease {
1145 kind: PrereleaseKind::Alpha,
1146 number: 1,
1147 }),
1148 PythonVariant::Default,
1149 None,
1150 );
1151
1152 assert!(stable.is_upgrade_of(&prerelease));
1154
1155 assert!(!prerelease.is_upgrade_of(&stable));
1157 }
1158
1159 #[test]
1160 fn test_is_upgrade_of_prerelease_to_prerelease() {
1161 let alpha1 = create_test_installation(
1162 ImplementationName::CPython,
1163 3,
1164 10,
1165 8,
1166 Some(Prerelease {
1167 kind: PrereleaseKind::Alpha,
1168 number: 1,
1169 }),
1170 PythonVariant::Default,
1171 None,
1172 );
1173 let alpha2 = create_test_installation(
1174 ImplementationName::CPython,
1175 3,
1176 10,
1177 8,
1178 Some(Prerelease {
1179 kind: PrereleaseKind::Alpha,
1180 number: 2,
1181 }),
1182 PythonVariant::Default,
1183 None,
1184 );
1185
1186 assert!(alpha2.is_upgrade_of(&alpha1));
1188 assert!(!alpha1.is_upgrade_of(&alpha2));
1190 }
1191
1192 #[test]
1193 fn test_is_upgrade_of_prerelease_same_patch() {
1194 let prerelease = create_test_installation(
1195 ImplementationName::CPython,
1196 3,
1197 10,
1198 8,
1199 Some(Prerelease {
1200 kind: PrereleaseKind::Alpha,
1201 number: 1,
1202 }),
1203 PythonVariant::Default,
1204 None,
1205 );
1206
1207 assert!(!prerelease.is_upgrade_of(&prerelease));
1209 }
1210
1211 #[test]
1212 fn test_is_upgrade_of_build_version() {
1213 let older_build = create_test_installation(
1214 ImplementationName::CPython,
1215 3,
1216 10,
1217 8,
1218 None,
1219 PythonVariant::Default,
1220 Some("20240101"),
1221 );
1222 let newer_build = create_test_installation(
1223 ImplementationName::CPython,
1224 3,
1225 10,
1226 8,
1227 None,
1228 PythonVariant::Default,
1229 Some("20240201"),
1230 );
1231
1232 assert!(newer_build.is_upgrade_of(&older_build));
1234 assert!(!older_build.is_upgrade_of(&newer_build));
1236 }
1237
1238 #[test]
1239 fn test_is_upgrade_of_build_version_same() {
1240 let installation = create_test_installation(
1241 ImplementationName::CPython,
1242 3,
1243 10,
1244 8,
1245 None,
1246 PythonVariant::Default,
1247 Some("20240101"),
1248 );
1249
1250 assert!(!installation.is_upgrade_of(&installation));
1252 }
1253
1254 #[test]
1255 fn test_is_upgrade_of_build_with_legacy_installation() {
1256 let legacy = create_test_installation(
1257 ImplementationName::CPython,
1258 3,
1259 10,
1260 8,
1261 None,
1262 PythonVariant::Default,
1263 None,
1264 );
1265 let with_build = create_test_installation(
1266 ImplementationName::CPython,
1267 3,
1268 10,
1269 8,
1270 None,
1271 PythonVariant::Default,
1272 Some("20240101"),
1273 );
1274
1275 assert!(with_build.is_upgrade_of(&legacy));
1277 assert!(!legacy.is_upgrade_of(&with_build));
1279 }
1280
1281 #[test]
1282 fn test_is_upgrade_of_patch_takes_precedence_over_build() {
1283 let older_patch_newer_build = create_test_installation(
1284 ImplementationName::CPython,
1285 3,
1286 10,
1287 8,
1288 None,
1289 PythonVariant::Default,
1290 Some("20240201"),
1291 );
1292 let newer_patch_older_build = create_test_installation(
1293 ImplementationName::CPython,
1294 3,
1295 10,
1296 9,
1297 None,
1298 PythonVariant::Default,
1299 Some("20240101"),
1300 );
1301
1302 assert!(newer_patch_older_build.is_upgrade_of(&older_patch_newer_build));
1304 assert!(!older_patch_newer_build.is_upgrade_of(&newer_patch_older_build));
1306 }
1307
1308 #[test]
1309 fn test_find_version_matching() {
1310 use crate::PythonVersion;
1311
1312 let platform = Platform::from_env().unwrap();
1313 let temp_dir = tempfile::tempdir().unwrap();
1314
1315 fs::create_dir(temp_dir.path().join(format!("cpython-3.10.0-{platform}"))).unwrap();
1317
1318 temp_env::with_var(
1319 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1320 Some(temp_dir.path()),
1321 || {
1322 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1323
1324 let v3_1 = PythonVersion::from_str("3.1").unwrap();
1326 let matched: Vec<_> = installations.find_version(&v3_1).unwrap().collect();
1327 assert_eq!(matched.len(), 0);
1328
1329 let v3_10 = PythonVersion::from_str("3.10").unwrap();
1331 let matched: Vec<_> = installations.find_version(&v3_10).unwrap().collect();
1332 assert_eq!(matched.len(), 1);
1333 },
1334 );
1335 }
1336
1337 #[test]
1338 fn test_relative_install_dir_resolves_against_pwd() {
1339 let temp_dir = tempfile::tempdir().unwrap();
1340 let workdir = temp_dir.path().join("workdir");
1341 fs::create_dir(&workdir).unwrap();
1342
1343 temp_env::with_vars(
1344 [
1345 (
1346 uv_static::EnvVars::UV_PYTHON_INSTALL_DIR,
1347 Some(std::ffi::OsStr::new(".python-installs")),
1348 ),
1349 (uv_static::EnvVars::PWD, Some(workdir.as_os_str())),
1350 ],
1351 || {
1352 let installations = ManagedPythonInstallations::from_settings(None).unwrap();
1353 assert_eq!(
1354 installations.absolute_root().unwrap(),
1355 workdir.join(".python-installs")
1356 );
1357 },
1358 );
1359 }
1360}