1use std::borrow::Cow;
2use std::env::consts::ARCH;
3use std::fmt::{Display, Formatter};
4use std::path::{Path, PathBuf};
5use std::process::{Command, ExitStatus};
6use std::str::FromStr;
7use std::sync::OnceLock;
8use std::{env, io};
9
10use configparser::ini::Ini;
11use fs_err as fs;
12use owo_colors::OwoColorize;
13use same_file::is_same_file;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16use tracing::{debug, trace, warn};
17
18use uv_cache::{Cache, CacheBucket, CachedByTimestamp, Freshness};
19use uv_cache_info::Timestamp;
20use uv_cache_key::cache_digest;
21use uv_fs::{
22 LockedFile, LockedFileError, LockedFileMode, PythonExt, Simplified, write_atomic_sync,
23};
24use uv_install_wheel::Layout;
25use uv_pep440::Version;
26use uv_pep508::{MarkerEnvironment, StringVersion};
27use uv_platform::{Arch, Libc, Os};
28use uv_platform_tags::{Platform, Tags, TagsError, TagsOptions};
29use uv_pypi_types::{ResolverMarkerEnvironment, Scheme};
30
31use crate::implementation::LenientImplementationName;
32use crate::managed::ManagedPythonInstallations;
33use crate::pointer_size::PointerSize;
34use crate::{
35 Prefix, PyVenvConfiguration, PythonInstallationKey, PythonVariant, PythonVersion, Target,
36 VersionRequest, VirtualEnvironment,
37};
38
39#[cfg(windows)]
40use windows::Win32::Foundation::{APPMODEL_ERROR_NO_PACKAGE, ERROR_CANT_ACCESS_FILE, WIN32_ERROR};
41
42#[expect(clippy::struct_excessive_bools)]
44#[derive(Debug, Clone)]
45pub struct Interpreter {
46 platform: Platform,
47 markers: Box<MarkerEnvironment>,
48 scheme: Scheme,
49 virtualenv: Scheme,
50 manylinux_compatible: bool,
51 sys_prefix: PathBuf,
52 sys_base_prefix: PathBuf,
53 sys_base_executable: Option<PathBuf>,
54 sys_executable: PathBuf,
55 site_packages: Vec<PathBuf>,
56 stdlib: PathBuf,
57 extension_suffixes: Vec<Box<str>>,
58 standalone: bool,
59 tags: OnceLock<Tags>,
60 target: Option<Target>,
61 prefix: Option<Prefix>,
62 pointer_size: PointerSize,
63 gil_disabled: bool,
64 real_executable: PathBuf,
65 debug_enabled: bool,
66}
67
68impl Interpreter {
69 pub fn query(executable: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> {
71 let info = InterpreterInfo::query_cached(executable.as_ref(), cache)?;
72
73 debug_assert!(
74 info.sys_executable.is_absolute(),
75 "`sys.executable` is not an absolute Python; Python installation is broken: {}",
76 info.sys_executable.display()
77 );
78
79 Ok(Self {
80 platform: info.platform,
81 markers: Box::new(info.markers),
82 scheme: info.scheme,
83 virtualenv: info.virtualenv,
84 manylinux_compatible: info.manylinux_compatible,
85 sys_prefix: info.sys_prefix,
86 pointer_size: info.pointer_size,
87 gil_disabled: info.gil_disabled,
88 debug_enabled: info.debug_enabled,
89 sys_base_prefix: info.sys_base_prefix,
90 sys_base_executable: info.sys_base_executable,
91 sys_executable: info.sys_executable,
92 site_packages: info.site_packages,
93 stdlib: info.stdlib,
94 extension_suffixes: info.extension_suffixes,
95 standalone: info.standalone,
96 tags: OnceLock::new(),
97 target: None,
98 prefix: None,
99 real_executable: executable.as_ref().to_path_buf(),
100 })
101 }
102
103 #[must_use]
105 pub fn with_virtualenv(self, virtualenv: VirtualEnvironment) -> Self {
106 Self {
107 scheme: virtualenv.scheme,
108 sys_base_executable: Some(virtualenv.base_executable),
109 sys_executable: virtualenv.executable,
110 sys_prefix: virtualenv.root,
111 target: None,
112 prefix: None,
113 site_packages: vec![],
114 ..self
115 }
116 }
117
118 pub(crate) fn with_target(self, target: Target) -> io::Result<Self> {
120 target.init()?;
121 Ok(Self {
122 target: Some(target),
123 ..self
124 })
125 }
126
127 pub(crate) fn with_prefix(self, prefix: Prefix) -> io::Result<Self> {
129 prefix.init(self.virtualenv())?;
130 Ok(Self {
131 prefix: Some(prefix),
132 ..self
133 })
134 }
135
136 pub fn to_base_python(&self) -> Result<PathBuf, io::Error> {
146 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
147 let base_python = std::path::absolute(base_executable)?;
148 Ok(base_python)
149 }
150
151 pub fn find_base_python(&self) -> Result<PathBuf, io::Error> {
162 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
163 let base_python = match find_base_python(
173 base_executable,
174 self.python_major(),
175 self.python_minor(),
176 self.variant().executable_suffix(),
177 ) {
178 Ok(path) => path,
179 Err(err) => {
180 warn!("Failed to find base Python executable: {err}");
181 canonicalize_executable(base_executable)?
182 }
183 };
184 Ok(base_python)
185 }
186
187 #[inline]
189 pub fn platform(&self) -> &Platform {
190 &self.platform
191 }
192
193 #[inline]
195 pub const fn markers(&self) -> &MarkerEnvironment {
196 &self.markers
197 }
198
199 pub fn resolver_marker_environment(&self) -> ResolverMarkerEnvironment {
201 ResolverMarkerEnvironment::from(self.markers().clone())
202 }
203
204 pub(crate) fn key(&self) -> PythonInstallationKey {
206 PythonInstallationKey::new(
207 LenientImplementationName::from(self.implementation_name()),
208 self.python_major(),
209 self.python_minor(),
210 self.python_patch(),
211 self.python_version().pre(),
212 uv_platform::Platform::new(self.os(), self.arch(), self.libc()),
213 self.variant(),
214 )
215 }
216
217 pub fn variant(&self) -> PythonVariant {
218 if self.gil_disabled() {
219 if self.debug_enabled() {
220 PythonVariant::FreethreadedDebug
221 } else {
222 PythonVariant::Freethreaded
223 }
224 } else if self.debug_enabled() {
225 PythonVariant::Debug
226 } else {
227 PythonVariant::default()
228 }
229 }
230
231 pub(crate) fn arch(&self) -> Arch {
233 Arch::from(&self.platform().arch())
234 }
235
236 pub(crate) fn libc(&self) -> Libc {
238 Libc::from(self.platform().os())
239 }
240
241 pub(crate) fn os(&self) -> Os {
243 Os::from(self.platform().os())
244 }
245
246 pub fn tags(&self) -> Result<&Tags, TagsError> {
248 if self.tags.get().is_none() {
249 let tags = Tags::from_env(
250 self.platform(),
251 self.python_tuple(),
252 self.implementation_name(),
253 self.implementation_tuple(),
254 TagsOptions {
255 manylinux_compatible: self.manylinux_compatible,
256 gil_disabled: self.gil_disabled,
257 debug_enabled: self.debug_enabled,
258 is_cross: false,
259 },
260 )?;
261 self.tags.set(tags).expect("tags should not be set");
262 }
263 Ok(self.tags.get().expect("tags should be set"))
264 }
265
266 pub fn is_virtualenv(&self) -> bool {
270 self.sys_prefix != self.sys_base_prefix
272 }
273
274 fn is_target(&self) -> bool {
276 self.target.is_some()
277 }
278
279 fn is_prefix(&self) -> bool {
281 self.prefix.is_some()
282 }
283
284 pub(crate) fn is_managed(&self) -> bool {
288 if let Ok(test_managed) =
289 std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED)
290 {
291 return test_managed.split_ascii_whitespace().any(|item| {
294 let version = <PythonVersion as std::str::FromStr>::from_str(item).expect(
295 "`UV_INTERNAL__TEST_PYTHON_MANAGED` items should be valid Python versions",
296 );
297 if version.patch().is_some() {
298 version.version() == self.python_version()
299 } else {
300 (version.major(), version.minor()) == self.python_tuple()
301 }
302 });
303 }
304
305 let Ok(installations) = ManagedPythonInstallations::from_settings(None) else {
306 return false;
307 };
308 let Ok(root) = installations.absolute_root() else {
309 return false;
310 };
311 let sys_base_prefix = dunce::canonicalize(&self.sys_base_prefix)
312 .unwrap_or_else(|_| self.sys_base_prefix.clone());
313 let root = dunce::canonicalize(&root).unwrap_or(root);
314
315 let Ok(suffix) = sys_base_prefix.strip_prefix(&root) else {
316 return false;
317 };
318
319 let Some(first_component) = suffix.components().next() else {
320 return false;
321 };
322
323 let Some(name) = first_component.as_os_str().to_str() else {
324 return false;
325 };
326
327 PythonInstallationKey::from_str(name).is_ok()
328 }
329
330 pub fn is_externally_managed(&self) -> Option<ExternallyManaged> {
335 if self.is_virtualenv() {
337 return None;
338 }
339
340 if self.is_target() || self.is_prefix() {
342 return None;
343 }
344
345 let Ok(contents) = fs::read_to_string(self.stdlib.join("EXTERNALLY-MANAGED")) else {
346 return None;
347 };
348
349 let mut ini = Ini::new_cs();
350 ini.set_multiline(true);
351
352 let Ok(mut sections) = ini.read(contents) else {
353 return Some(ExternallyManaged::default());
356 };
357
358 let Some(section) = sections.get_mut("externally-managed") else {
359 return Some(ExternallyManaged::default());
362 };
363
364 let Some(error) = section.remove("Error") else {
365 return Some(ExternallyManaged::default());
368 };
369
370 Some(ExternallyManaged { error })
371 }
372
373 #[inline]
375 pub fn python_full_version(&self) -> &StringVersion {
376 self.markers.python_full_version()
377 }
378
379 #[inline]
381 pub fn python_version(&self) -> &Version {
382 &self.markers.python_full_version().version
383 }
384
385 #[inline]
387 pub fn python_minor_version(&self) -> Version {
388 Version::new(self.python_version().release().iter().take(2).copied())
389 }
390
391 #[inline]
393 pub(crate) fn python_patch_version(&self) -> Version {
394 Version::new(self.python_version().release().iter().take(3).copied())
395 }
396
397 pub fn python_major(&self) -> u8 {
399 let major = self.markers.python_full_version().version.release()[0];
400 u8::try_from(major).expect("invalid major version")
401 }
402
403 pub fn python_minor(&self) -> u8 {
405 let minor = self.markers.python_full_version().version.release()[1];
406 u8::try_from(minor).expect("invalid minor version")
407 }
408
409 pub(crate) fn python_patch(&self) -> u8 {
411 let minor = self.markers.python_full_version().version.release()[2];
412 u8::try_from(minor).expect("invalid patch version")
413 }
414
415 pub fn python_tuple(&self) -> (u8, u8) {
417 (self.python_major(), self.python_minor())
418 }
419
420 fn implementation_major(&self) -> u8 {
422 let major = self.markers.implementation_version().version.release()[0];
423 u8::try_from(major).expect("invalid major version")
424 }
425
426 fn implementation_minor(&self) -> u8 {
428 let minor = self.markers.implementation_version().version.release()[1];
429 u8::try_from(minor).expect("invalid minor version")
430 }
431
432 pub fn implementation_tuple(&self) -> (u8, u8) {
434 (self.implementation_major(), self.implementation_minor())
435 }
436
437 pub fn implementation_name(&self) -> &str {
439 self.markers.implementation_name()
440 }
441
442 pub fn sys_base_prefix(&self) -> &Path {
444 &self.sys_base_prefix
445 }
446
447 pub fn sys_prefix(&self) -> &Path {
449 &self.sys_prefix
450 }
451
452 pub(crate) fn sys_base_executable(&self) -> Option<&Path> {
455 self.sys_base_executable.as_deref()
456 }
457
458 pub fn sys_executable(&self) -> &Path {
460 &self.sys_executable
461 }
462
463 pub fn extension_suffixes(&self) -> &[Box<str>] {
465 &self.extension_suffixes
466 }
467
468 pub fn real_executable(&self) -> &Path {
470 &self.real_executable
471 }
472
473 pub fn runtime_site_packages(&self) -> &[PathBuf] {
481 &self.site_packages
482 }
483
484 pub fn stdlib(&self) -> &Path {
486 &self.stdlib
487 }
488
489 fn purelib(&self) -> &Path {
491 &self.scheme.purelib
492 }
493
494 fn platlib(&self) -> &Path {
496 &self.scheme.platlib
497 }
498
499 pub fn scripts(&self) -> &Path {
501 &self.scheme.scripts
502 }
503
504 fn data(&self) -> &Path {
506 &self.scheme.data
507 }
508
509 fn include(&self) -> &Path {
511 &self.scheme.include
512 }
513
514 pub fn virtualenv(&self) -> &Scheme {
516 &self.virtualenv
517 }
518
519 pub fn manylinux_compatible(&self) -> bool {
521 self.manylinux_compatible
522 }
523
524 pub fn pointer_size(&self) -> PointerSize {
526 self.pointer_size
527 }
528
529 pub fn gil_disabled(&self) -> bool {
535 self.gil_disabled
536 }
537
538 pub fn debug_enabled(&self) -> bool {
541 self.debug_enabled
542 }
543
544 fn target(&self) -> Option<&Target> {
546 self.target.as_ref()
547 }
548
549 fn prefix(&self) -> Option<&Prefix> {
551 self.prefix.as_ref()
552 }
553
554 #[cfg(unix)]
563 pub fn is_standalone(&self) -> bool {
564 self.standalone
565 }
566
567 #[cfg(windows)]
571 pub fn is_standalone(&self) -> bool {
572 self.standalone || (self.is_managed() && self.markers().implementation_name() == "cpython")
573 }
574
575 pub fn layout(&self) -> Layout {
577 Layout {
578 python_version: self.python_tuple(),
579 sys_executable: self.sys_executable().to_path_buf(),
580 os_name: self.markers.os_name().to_string(),
581 scheme: if let Some(target) = self.target.as_ref() {
582 target.scheme()
583 } else if let Some(prefix) = self.prefix.as_ref() {
584 prefix.scheme(&self.virtualenv)
585 } else {
586 Scheme {
587 purelib: self.purelib().to_path_buf(),
588 platlib: self.platlib().to_path_buf(),
589 scripts: self.scripts().to_path_buf(),
590 data: self.data().to_path_buf(),
591 include: if self.is_virtualenv() {
592 self.sys_prefix.join("include").join("site").join(format!(
595 "python{}.{}",
596 self.python_major(),
597 self.python_minor()
598 ))
599 } else {
600 self.include().to_path_buf()
601 },
602 }
603 },
604 }
605 }
606
607 pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> {
618 let target = self.target().map(Target::site_packages);
619
620 let prefix = self
621 .prefix()
622 .map(|prefix| prefix.site_packages(self.virtualenv()));
623
624 let interpreter = if target.is_none() && prefix.is_none() {
625 let purelib = self.purelib();
626 let platlib = self.platlib();
627 Some(std::iter::once(purelib).chain(
628 if purelib == platlib || is_same_file(purelib, platlib).unwrap_or(false) {
629 None
630 } else {
631 Some(platlib)
632 },
633 ))
634 } else {
635 None
636 };
637
638 target
639 .into_iter()
640 .flatten()
641 .map(Cow::Borrowed)
642 .chain(prefix.into_iter().flatten().map(Cow::Owned))
643 .chain(interpreter.into_iter().flatten().map(Cow::Borrowed))
644 }
645
646 pub(crate) fn has_default_executable_name(&self) -> bool {
649 let Some(file_name) = self.sys_executable().file_name() else {
650 return false;
651 };
652 let Some(name) = file_name.to_str() else {
653 return false;
654 };
655 VersionRequest::Default
656 .executable_names(None)
657 .into_iter()
658 .any(|default_name| name == default_name.to_string())
659 }
660
661 pub async fn lock(&self) -> Result<LockedFile, LockedFileError> {
663 if let Some(target) = self.target() {
664 LockedFile::acquire(
666 target.root().join(".lock"),
667 LockedFileMode::Exclusive,
668 target.root().user_display(),
669 )
670 .await
671 } else if let Some(prefix) = self.prefix() {
672 LockedFile::acquire(
674 prefix.root().join(".lock"),
675 LockedFileMode::Exclusive,
676 prefix.root().user_display(),
677 )
678 .await
679 } else if self.is_virtualenv() {
680 LockedFile::acquire(
682 self.sys_prefix.join(".lock"),
683 LockedFileMode::Exclusive,
684 self.sys_prefix.user_display(),
685 )
686 .await
687 } else {
688 LockedFile::acquire(
690 env::temp_dir().join(format!("uv-{}.lock", cache_digest(&self.sys_executable))),
691 LockedFileMode::Exclusive,
692 self.sys_prefix.user_display(),
693 )
694 .await
695 }
696 }
697}
698
699pub fn canonicalize_executable(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
702 let path = path.as_ref();
703 debug_assert!(
704 path.is_absolute(),
705 "path must be absolute: {}",
706 path.display()
707 );
708
709 #[cfg(windows)]
710 {
711 if let Ok(Some(launcher)) = uv_trampoline_builder::Launcher::try_from_path(path) {
712 Ok(dunce::canonicalize(launcher.python_path)?)
713 } else {
714 Ok(path.to_path_buf())
715 }
716 }
717
718 #[cfg(unix)]
719 fs_err::canonicalize(path)
720}
721
722#[derive(Debug, Default, Clone)]
726pub struct ExternallyManaged {
727 error: Option<String>,
728}
729
730impl ExternallyManaged {
731 pub fn into_error(self) -> Option<String> {
733 self.error
734 }
735}
736
737#[derive(Debug, Error)]
738pub struct UnexpectedResponseError {
739 #[source]
740 pub(super) err: serde_json::Error,
741 pub(super) stdout: String,
742 pub(super) stderr: String,
743 pub(super) path: PathBuf,
744}
745
746impl Display for UnexpectedResponseError {
747 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
748 write!(
749 f,
750 "Querying Python at `{}` returned an invalid response: {}",
751 self.path.display(),
752 self.err
753 )?;
754
755 let mut non_empty = false;
756
757 if !self.stdout.trim().is_empty() {
758 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
759 non_empty = true;
760 }
761
762 if !self.stderr.trim().is_empty() {
763 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
764 non_empty = true;
765 }
766
767 if non_empty {
768 writeln!(f)?;
769 }
770
771 Ok(())
772 }
773}
774
775#[derive(Debug, Error)]
776pub struct StatusCodeError {
777 pub(super) code: ExitStatus,
778 pub(super) stdout: String,
779 pub(super) stderr: String,
780 pub(super) path: PathBuf,
781}
782
783impl Display for StatusCodeError {
784 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
785 write!(
786 f,
787 "Querying Python at `{}` failed with exit status {}",
788 self.path.display(),
789 self.code
790 )?;
791
792 let mut non_empty = false;
793
794 if !self.stdout.trim().is_empty() {
795 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
796 non_empty = true;
797 }
798
799 if !self.stderr.trim().is_empty() {
800 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
801 non_empty = true;
802 }
803
804 if non_empty {
805 writeln!(f)?;
806 }
807
808 Ok(())
809 }
810}
811
812#[derive(Debug, Error)]
813pub enum Error {
814 #[error("Failed to query Python interpreter")]
815 Io(#[from] io::Error),
816 #[error(transparent)]
817 BrokenLink(BrokenLink),
818 #[error("Python interpreter not found at `{0}`")]
819 NotFound(PathBuf),
820 #[error("Failed to query Python interpreter at `{path}`")]
821 SpawnFailed {
822 path: PathBuf,
823 #[source]
824 err: io::Error,
825 },
826 #[cfg(windows)]
827 #[error("Failed to query Python interpreter at `{path}`")]
828 CorruptWindowsPackage {
829 path: PathBuf,
830 #[source]
831 err: io::Error,
832 },
833 #[error("Failed to query Python interpreter at `{path}`")]
834 PermissionDenied {
835 path: PathBuf,
836 #[source]
837 err: io::Error,
838 },
839 #[error("{0}")]
840 UnexpectedResponse(UnexpectedResponseError),
841 #[error("{0}")]
842 StatusCode(StatusCodeError),
843 #[error("Can't use Python at `{path}`")]
844 QueryScript {
845 #[source]
846 err: InterpreterInfoError,
847 path: PathBuf,
848 },
849 #[error("Failed to write to cache")]
850 Encode(#[from] rmp_serde::encode::Error),
851}
852
853impl uv_errors::Hint for Error {
854 fn hints(&self) -> uv_errors::Hints<'_> {
855 match self {
856 Self::BrokenLink(err) => err.hints(),
857 _ => uv_errors::Hints::none(),
858 }
859 }
860}
861
862#[derive(Debug, Error)]
863pub struct BrokenLink {
864 pub path: PathBuf,
865 pub unix: bool,
868 pub venv: bool,
870}
871
872impl Display for BrokenLink {
873 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
874 if self.unix {
875 write!(
876 f,
877 "Broken symlink at `{}`, was the underlying Python interpreter removed?",
878 self.path.user_display()
879 )
880 } else {
881 write!(
882 f,
883 "Broken Python trampoline at `{}`, was the underlying Python interpreter removed?",
884 self.path.user_display()
885 )
886 }
887 }
888}
889
890impl uv_errors::Hint for BrokenLink {
891 fn hints(&self) -> uv_errors::Hints<'_> {
892 if self.venv {
893 uv_errors::Hints::from(format!(
894 "Consider recreating the environment (e.g., with `{}`)",
895 "uv venv".green()
896 ))
897 } else {
898 uv_errors::Hints::none()
899 }
900 }
901}
902
903#[derive(Debug, Deserialize, Serialize)]
904#[serde(tag = "result", rename_all = "lowercase")]
905enum InterpreterInfoResult {
906 Error(InterpreterInfoError),
907 Success(Box<InterpreterInfo>),
908}
909
910#[derive(Debug, Error, Deserialize, Serialize)]
911#[serde(tag = "kind", rename_all = "snake_case")]
912pub enum InterpreterInfoError {
913 #[error("Could not detect a glibc or a musl libc (while running on Linux)")]
914 LibcNotFound,
915 #[error(
916 "Broken Python installation, `platform.mac_ver()` returned an empty value, please reinstall Python"
917 )]
918 BrokenMacVer,
919 #[error("Unknown operating system: `{operating_system}`")]
920 UnknownOperatingSystem { operating_system: String },
921 #[error("Python {python_version} is not supported. Please use Python 3.6 or newer.")]
922 UnsupportedPythonVersion { python_version: String },
923 #[error("Python executable does not support `-I` flag. Please use Python 3.6 or newer.")]
924 UnsupportedPython,
925 #[error(
926 "Python installation is missing `distutils`, which is required for packaging on older Python versions. Your system may package it separately, e.g., as `python{python_major}-distutils` or `python{python_major}.{python_minor}-distutils`."
927 )]
928 MissingRequiredDistutils {
929 python_major: usize,
930 python_minor: usize,
931 },
932 #[error("Only Pyodide is supported for Emscripten Python")]
933 EmscriptenNotPyodide,
934}
935
936#[expect(clippy::struct_excessive_bools)]
937#[derive(Debug, Deserialize, Serialize, Clone)]
938struct InterpreterInfo {
939 platform: Platform,
940 markers: MarkerEnvironment,
941 scheme: Scheme,
942 virtualenv: Scheme,
943 manylinux_compatible: bool,
944 sys_prefix: PathBuf,
945 sys_base_exec_prefix: PathBuf,
946 sys_base_prefix: PathBuf,
947 sys_base_executable: Option<PathBuf>,
948 sys_executable: PathBuf,
949 sys_path: Vec<PathBuf>,
950 site_packages: Vec<PathBuf>,
951 stdlib: PathBuf,
952 extension_suffixes: Vec<Box<str>>,
953 standalone: bool,
954 pointer_size: PointerSize,
955 gil_disabled: bool,
956 debug_enabled: bool,
957}
958
959impl InterpreterInfo {
960 fn query(interpreter: &Path, cache: &Cache) -> Result<Self, Error> {
962 let tempdir = tempfile::tempdir_in(cache.root())?;
963 Self::setup_python_query_files(tempdir.path())?;
964
965 let script = format!(
969 r#"import sys; sys.path = ["{}"] + sys.path; from python.get_interpreter_info import main; main()"#,
970 tempdir.path().escape_for_python()
971 );
972 let mut command = Command::new(interpreter);
973 command
974 .arg("-I") .arg("-B") .arg("-c")
977 .arg(script);
978
979 #[cfg(target_os = "macos")]
988 command.env("SYSTEM_VERSION_COMPAT", "0");
989
990 let output = command.output().map_err(|err| {
991 match err.kind() {
992 io::ErrorKind::NotFound => return Error::NotFound(interpreter.to_path_buf()),
993 io::ErrorKind::PermissionDenied => {
994 return Error::PermissionDenied {
995 path: interpreter.to_path_buf(),
996 err,
997 };
998 }
999 _ => {}
1000 }
1001 #[cfg(windows)]
1002 if let Some(APPMODEL_ERROR_NO_PACKAGE | ERROR_CANT_ACCESS_FILE) = err
1003 .raw_os_error()
1004 .and_then(|code| u32::try_from(code).ok())
1005 .map(WIN32_ERROR)
1006 {
1007 return Error::CorruptWindowsPackage {
1010 path: interpreter.to_path_buf(),
1011 err,
1012 };
1013 }
1014 Error::SpawnFailed {
1015 path: interpreter.to_path_buf(),
1016 err,
1017 }
1018 })?;
1019
1020 if !output.status.success() {
1021 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1022
1023 if python_home(interpreter).is_some_and(|home| !home.exists()) {
1029 return Err(Error::BrokenLink(BrokenLink {
1030 path: interpreter.to_path_buf(),
1031 unix: false,
1032 venv: uv_fs::is_virtualenv_executable(interpreter),
1033 }));
1034 }
1035
1036 if stderr.contains("Unknown option: -I") {
1038 return Err(Error::QueryScript {
1039 err: InterpreterInfoError::UnsupportedPython,
1040 path: interpreter.to_path_buf(),
1041 });
1042 }
1043
1044 return Err(Error::StatusCode(StatusCodeError {
1045 code: output.status,
1046 stderr,
1047 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1048 path: interpreter.to_path_buf(),
1049 }));
1050 }
1051
1052 let result: InterpreterInfoResult =
1053 serde_json::from_slice(&output.stdout).map_err(|err| {
1054 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1055
1056 if stderr.contains("Unknown option: -I") {
1058 Error::QueryScript {
1059 err: InterpreterInfoError::UnsupportedPython,
1060 path: interpreter.to_path_buf(),
1061 }
1062 } else {
1063 Error::UnexpectedResponse(UnexpectedResponseError {
1064 err,
1065 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1066 stderr,
1067 path: interpreter.to_path_buf(),
1068 })
1069 }
1070 })?;
1071
1072 match result {
1073 InterpreterInfoResult::Error(err) => Err(Error::QueryScript {
1074 err,
1075 path: interpreter.to_path_buf(),
1076 }),
1077 InterpreterInfoResult::Success(data) => Ok(*data),
1078 }
1079 }
1080
1081 fn setup_python_query_files(root: &Path) -> Result<(), Error> {
1084 let python_dir = root.join("python");
1085 fs_err::create_dir(&python_dir)?;
1086 fs_err::write(
1087 python_dir.join("get_interpreter_info.py"),
1088 include_str!("../python/get_interpreter_info.py"),
1089 )?;
1090 fs_err::write(
1091 python_dir.join("__init__.py"),
1092 include_str!("../python/__init__.py"),
1093 )?;
1094 let packaging_dir = python_dir.join("packaging");
1095 fs_err::create_dir(&packaging_dir)?;
1096 fs_err::write(
1097 packaging_dir.join("__init__.py"),
1098 include_str!("../python/packaging/__init__.py"),
1099 )?;
1100 fs_err::write(
1101 packaging_dir.join("_elffile.py"),
1102 include_str!("../python/packaging/_elffile.py"),
1103 )?;
1104 fs_err::write(
1105 packaging_dir.join("_manylinux.py"),
1106 include_str!("../python/packaging/_manylinux.py"),
1107 )?;
1108 fs_err::write(
1109 packaging_dir.join("_musllinux.py"),
1110 include_str!("../python/packaging/_musllinux.py"),
1111 )?;
1112 Ok(())
1113 }
1114
1115 fn query_cached(executable: &Path, cache: &Cache) -> Result<Self, Error> {
1121 let absolute = std::path::absolute(executable)?;
1122
1123 let handle_io_error = |err: io::Error| -> Error {
1127 if err.kind() == io::ErrorKind::NotFound {
1128 if absolute
1131 .symlink_metadata()
1132 .is_ok_and(|metadata| metadata.is_symlink())
1133 {
1134 Error::BrokenLink(BrokenLink {
1135 path: executable.to_path_buf(),
1136 unix: true,
1137 venv: uv_fs::is_virtualenv_executable(executable),
1138 })
1139 } else {
1140 Error::NotFound(executable.to_path_buf())
1141 }
1142 } else {
1143 err.into()
1144 }
1145 };
1146
1147 let canonical = canonicalize_executable(&absolute).map_err(handle_io_error)?;
1148
1149 let cache_entry = cache.entry(
1150 CacheBucket::Interpreter,
1151 cache_digest(&(
1154 ARCH,
1155 uv_platform::OsType::from_env()
1156 .map(|os_type| os_type.to_string())
1157 .unwrap_or_default(),
1158 uv_platform::OsRelease::from_env()
1159 .map(|os_release| os_release.to_string())
1160 .unwrap_or_default(),
1161 )),
1162 format!("{}.msgpack", cache_digest(&(&absolute, &canonical))),
1170 );
1171
1172 let modified = Timestamp::from_path(canonical).map_err(handle_io_error)?;
1175
1176 if cache
1178 .freshness(&cache_entry, None, None)
1179 .is_ok_and(Freshness::is_fresh)
1180 {
1181 if let Ok(data) = fs::read(cache_entry.path()) {
1182 match rmp_serde::from_slice::<CachedByTimestamp<Self>>(&data) {
1183 Ok(cached) => {
1184 if cached.timestamp == modified {
1185 trace!(
1186 "Found cached interpreter info for Python {}, skipping query of: {}",
1187 cached.data.markers.python_full_version(),
1188 executable.user_display()
1189 );
1190 return Ok(cached.data);
1191 }
1192
1193 trace!(
1194 "Ignoring stale interpreter markers for: {}",
1195 executable.user_display()
1196 );
1197 }
1198 Err(err) => {
1199 warn!(
1200 "Broken interpreter cache entry at {}, removing: {err}",
1201 cache_entry.path().user_display()
1202 );
1203 let _ = fs_err::remove_file(cache_entry.path());
1204 }
1205 }
1206 }
1207 }
1208
1209 trace!(
1211 "Querying interpreter executable at {}",
1212 executable.display()
1213 );
1214 let info = Self::query(executable, cache)?;
1215
1216 if is_same_file(executable, &info.sys_executable).unwrap_or(false) {
1219 fs::create_dir_all(cache_entry.dir())?;
1220 write_atomic_sync(
1221 cache_entry.path(),
1222 rmp_serde::to_vec(&CachedByTimestamp {
1223 timestamp: modified,
1224 data: info.clone(),
1225 })?,
1226 )?;
1227 }
1228
1229 Ok(info)
1230 }
1231}
1232
1233fn find_base_python(
1259 executable: &Path,
1260 major: u8,
1261 minor: u8,
1262 suffix: &str,
1263) -> Result<PathBuf, io::Error> {
1264 fn is_root(path: &Path) -> bool {
1266 let mut components = path.components();
1267 components.next() == Some(std::path::Component::RootDir) && components.next().is_none()
1268 }
1269
1270 fn is_prefix(dir: &Path, major: u8, minor: u8, suffix: &str) -> bool {
1274 if cfg!(windows) {
1275 dir.join("Lib").join("os.py").is_file()
1276 } else {
1277 dir.join("lib")
1278 .join(format!("python{major}.{minor}{suffix}"))
1279 .join("os.py")
1280 .is_file()
1281 }
1282 }
1283
1284 let mut executable = Cow::Borrowed(executable);
1285
1286 loop {
1287 debug!(
1288 "Assessing Python executable as base candidate: {}",
1289 executable.display()
1290 );
1291
1292 for prefix in executable.ancestors().take_while(|path| !is_root(path)) {
1294 if is_prefix(prefix, major, minor, suffix) {
1295 return Ok(executable.into_owned());
1296 }
1297 }
1298
1299 let resolved = fs_err::read_link(&executable)?;
1301
1302 let resolved = if resolved.is_relative() {
1304 if let Some(parent) = executable.parent() {
1305 parent.join(resolved)
1306 } else {
1307 return Err(io::Error::other("Symlink has no parent directory"));
1308 }
1309 } else {
1310 resolved
1311 };
1312
1313 let resolved = uv_fs::normalize_absolute_path(&resolved)?;
1315
1316 executable = Cow::Owned(resolved);
1317 }
1318}
1319
1320fn python_home(interpreter: &Path) -> Option<PathBuf> {
1322 let venv_root = interpreter.parent()?.parent()?;
1323 let pyvenv_cfg = PyVenvConfiguration::parse(venv_root.join("pyvenv.cfg")).ok()?;
1324 pyvenv_cfg.home
1325}
1326
1327#[cfg(unix)]
1328#[cfg(test)]
1329mod tests {
1330 use std::str::FromStr;
1331
1332 use fs_err as fs;
1333 use indoc::{formatdoc, indoc};
1334 use tempfile::tempdir;
1335
1336 use uv_cache::Cache;
1337 use uv_pep440::Version;
1338
1339 use crate::Interpreter;
1340
1341 #[tokio::test]
1342 async fn test_cache_invalidation() {
1343 let mock_dir = tempdir().unwrap();
1344 let mocked_interpreter = mock_dir.path().join("python");
1345 let json = indoc! {r##"
1346 {
1347 "result": "success",
1348 "platform": {
1349 "os": {
1350 "name": "manylinux",
1351 "major": 2,
1352 "minor": 38
1353 },
1354 "arch": "x86_64"
1355 },
1356 "manylinux_compatible": false,
1357 "standalone": false,
1358 "markers": {
1359 "implementation_name": "cpython",
1360 "implementation_version": "3.12.0",
1361 "os_name": "posix",
1362 "platform_machine": "x86_64",
1363 "platform_python_implementation": "CPython",
1364 "platform_release": "6.5.0-13-generic",
1365 "platform_system": "Linux",
1366 "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov 3 12:16:05 UTC 2023",
1367 "python_full_version": "3.12.0",
1368 "python_version": "3.12",
1369 "sys_platform": "linux"
1370 },
1371 "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1372 "sys_base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1373 "sys_prefix": "/home/ferris/projects/uv/.venv",
1374 "sys_executable": "/home/ferris/projects/uv/.venv/bin/python",
1375 "sys_path": [
1376 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/lib/python3.12",
1377 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1378 ],
1379 "site_packages": [
1380 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1381 ],
1382 "stdlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12",
1383 "extension_suffixes": [".cpython-312-x86_64-linux-gnu.so", ".abi3.so", ".so"],
1384 "scheme": {
1385 "data": "/home/ferris/.pyenv/versions/3.12.0",
1386 "include": "/home/ferris/.pyenv/versions/3.12.0/include",
1387 "platlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1388 "purelib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1389 "scripts": "/home/ferris/.pyenv/versions/3.12.0/bin"
1390 },
1391 "virtualenv": {
1392 "data": "",
1393 "include": "include",
1394 "platlib": "lib/python3.12/site-packages",
1395 "purelib": "lib/python3.12/site-packages",
1396 "scripts": "bin"
1397 },
1398 "pointer_size": "64",
1399 "gil_disabled": true,
1400 "debug_enabled": false
1401 }
1402 "##};
1403
1404 let cache = Cache::temp().unwrap().init().await.unwrap();
1405
1406 fs::write(
1407 &mocked_interpreter,
1408 formatdoc! {r"
1409 #!/bin/sh
1410 echo '{json}'
1411 "},
1412 )
1413 .unwrap();
1414
1415 fs::set_permissions(
1416 &mocked_interpreter,
1417 std::os::unix::fs::PermissionsExt::from_mode(0o770),
1418 )
1419 .unwrap();
1420 let interpreter = Interpreter::query(&mocked_interpreter, &cache).unwrap();
1421 assert_eq!(
1422 interpreter.markers.python_version().version,
1423 Version::from_str("3.12").unwrap()
1424 );
1425 fs::write(
1426 &mocked_interpreter,
1427 formatdoc! {r"
1428 #!/bin/sh
1429 echo '{}'
1430 ", json.replace("3.12", "3.13")},
1431 )
1432 .unwrap();
1433 let interpreter = Interpreter::query(&mocked_interpreter, &cache).unwrap();
1434 assert_eq!(
1435 interpreter.markers.python_version().version,
1436 Version::from_str("3.13").unwrap()
1437 );
1438 }
1439}