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};
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_exec_prefix: PathBuf,
53 sys_base_prefix: PathBuf,
54 sys_base_executable: Option<PathBuf>,
55 sys_executable: PathBuf,
56 sys_path: Vec<PathBuf>,
57 site_packages: Vec<PathBuf>,
58 stdlib: PathBuf,
59 standalone: bool,
60 tags: OnceLock<Tags>,
61 target: Option<Target>,
62 prefix: Option<Prefix>,
63 pointer_size: PointerSize,
64 gil_disabled: bool,
65 real_executable: PathBuf,
66 debug_enabled: bool,
67}
68
69impl Interpreter {
70 pub fn query(executable: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> {
72 let info = InterpreterInfo::query_cached(executable.as_ref(), cache)?;
73
74 debug_assert!(
75 info.sys_executable.is_absolute(),
76 "`sys.executable` is not an absolute Python; Python installation is broken: {}",
77 info.sys_executable.display()
78 );
79
80 Ok(Self {
81 platform: info.platform,
82 markers: Box::new(info.markers),
83 scheme: info.scheme,
84 virtualenv: info.virtualenv,
85 manylinux_compatible: info.manylinux_compatible,
86 sys_prefix: info.sys_prefix,
87 sys_base_exec_prefix: info.sys_base_exec_prefix,
88 pointer_size: info.pointer_size,
89 gil_disabled: info.gil_disabled,
90 debug_enabled: info.debug_enabled,
91 sys_base_prefix: info.sys_base_prefix,
92 sys_base_executable: info.sys_base_executable,
93 sys_executable: info.sys_executable,
94 sys_path: info.sys_path,
95 site_packages: info.site_packages,
96 stdlib: info.stdlib,
97 standalone: info.standalone,
98 tags: OnceLock::new(),
99 target: None,
100 prefix: None,
101 real_executable: executable.as_ref().to_path_buf(),
102 })
103 }
104
105 #[must_use]
107 pub fn with_virtualenv(self, virtualenv: VirtualEnvironment) -> Self {
108 Self {
109 scheme: virtualenv.scheme,
110 sys_base_executable: Some(virtualenv.base_executable),
111 sys_executable: virtualenv.executable,
112 sys_prefix: virtualenv.root,
113 target: None,
114 prefix: None,
115 site_packages: vec![],
116 ..self
117 }
118 }
119
120 pub fn with_target(self, target: Target) -> io::Result<Self> {
122 target.init()?;
123 Ok(Self {
124 target: Some(target),
125 ..self
126 })
127 }
128
129 pub fn with_prefix(self, prefix: Prefix) -> io::Result<Self> {
131 prefix.init(self.virtualenv())?;
132 Ok(Self {
133 prefix: Some(prefix),
134 ..self
135 })
136 }
137
138 pub fn to_base_python(&self) -> Result<PathBuf, io::Error> {
148 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
149 let base_python = std::path::absolute(base_executable)?;
150 Ok(base_python)
151 }
152
153 pub fn find_base_python(&self) -> Result<PathBuf, io::Error> {
164 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
165 let base_python = match find_base_python(
175 base_executable,
176 self.python_major(),
177 self.python_minor(),
178 self.variant().executable_suffix(),
179 ) {
180 Ok(path) => path,
181 Err(err) => {
182 warn!("Failed to find base Python executable: {err}");
183 canonicalize_executable(base_executable)?
184 }
185 };
186 Ok(base_python)
187 }
188
189 #[inline]
191 pub fn platform(&self) -> &Platform {
192 &self.platform
193 }
194
195 #[inline]
197 pub const fn markers(&self) -> &MarkerEnvironment {
198 &self.markers
199 }
200
201 pub fn resolver_marker_environment(&self) -> ResolverMarkerEnvironment {
203 ResolverMarkerEnvironment::from(self.markers().clone())
204 }
205
206 pub fn key(&self) -> PythonInstallationKey {
208 PythonInstallationKey::new(
209 LenientImplementationName::from(self.implementation_name()),
210 self.python_major(),
211 self.python_minor(),
212 self.python_patch(),
213 self.python_version().pre(),
214 uv_platform::Platform::new(self.os(), self.arch(), self.libc()),
215 self.variant(),
216 )
217 }
218
219 pub fn variant(&self) -> PythonVariant {
220 if self.gil_disabled() {
221 if self.debug_enabled() {
222 PythonVariant::FreethreadedDebug
223 } else {
224 PythonVariant::Freethreaded
225 }
226 } else if self.debug_enabled() {
227 PythonVariant::Debug
228 } else {
229 PythonVariant::default()
230 }
231 }
232
233 pub fn arch(&self) -> Arch {
235 Arch::from(&self.platform().arch())
236 }
237
238 pub fn libc(&self) -> Libc {
240 Libc::from(self.platform().os())
241 }
242
243 pub fn os(&self) -> Os {
245 Os::from(self.platform().os())
246 }
247
248 pub fn tags(&self) -> Result<&Tags, TagsError> {
250 if self.tags.get().is_none() {
251 let tags = Tags::from_env(
252 self.platform(),
253 self.python_tuple(),
254 self.implementation_name(),
255 self.implementation_tuple(),
256 self.manylinux_compatible,
257 self.gil_disabled,
258 false,
259 )?;
260 self.tags.set(tags).expect("tags should not be set");
261 }
262 Ok(self.tags.get().expect("tags should be set"))
263 }
264
265 pub fn is_virtualenv(&self) -> bool {
269 self.sys_prefix != self.sys_base_prefix
271 }
272
273 pub fn is_target(&self) -> bool {
275 self.target.is_some()
276 }
277
278 pub fn is_prefix(&self) -> bool {
280 self.prefix.is_some()
281 }
282
283 pub fn is_managed(&self) -> bool {
287 if let Ok(test_managed) =
288 std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED)
289 {
290 return test_managed.split_ascii_whitespace().any(|item| {
293 let version = <PythonVersion as std::str::FromStr>::from_str(item).expect(
294 "`UV_INTERNAL__TEST_PYTHON_MANAGED` items should be valid Python versions",
295 );
296 if version.patch().is_some() {
297 version.version() == self.python_version()
298 } else {
299 (version.major(), version.minor()) == self.python_tuple()
300 }
301 });
302 }
303
304 let Ok(installations) = ManagedPythonInstallations::from_settings(None) else {
305 return false;
306 };
307
308 let Ok(suffix) = self.sys_base_prefix.strip_prefix(installations.root()) else {
309 return false;
310 };
311
312 let Some(first_component) = suffix.components().next() else {
313 return false;
314 };
315
316 let Some(name) = first_component.as_os_str().to_str() else {
317 return false;
318 };
319
320 PythonInstallationKey::from_str(name).is_ok()
321 }
322
323 pub fn is_externally_managed(&self) -> Option<ExternallyManaged> {
328 if self.is_virtualenv() {
330 return None;
331 }
332
333 if self.is_target() || self.is_prefix() {
335 return None;
336 }
337
338 let Ok(contents) = fs::read_to_string(self.stdlib.join("EXTERNALLY-MANAGED")) else {
339 return None;
340 };
341
342 let mut ini = Ini::new_cs();
343 ini.set_multiline(true);
344
345 let Ok(mut sections) = ini.read(contents) else {
346 return Some(ExternallyManaged::default());
349 };
350
351 let Some(section) = sections.get_mut("externally-managed") else {
352 return Some(ExternallyManaged::default());
355 };
356
357 let Some(error) = section.remove("Error") else {
358 return Some(ExternallyManaged::default());
361 };
362
363 Some(ExternallyManaged { error })
364 }
365
366 #[inline]
368 pub fn python_full_version(&self) -> &StringVersion {
369 self.markers.python_full_version()
370 }
371
372 #[inline]
374 pub fn python_version(&self) -> &Version {
375 &self.markers.python_full_version().version
376 }
377
378 #[inline]
380 pub fn python_minor_version(&self) -> Version {
381 Version::new(self.python_version().release().iter().take(2).copied())
382 }
383
384 #[inline]
386 pub fn python_patch_version(&self) -> Version {
387 Version::new(self.python_version().release().iter().take(3).copied())
388 }
389
390 pub fn python_major(&self) -> u8 {
392 let major = self.markers.python_full_version().version.release()[0];
393 u8::try_from(major).expect("invalid major version")
394 }
395
396 pub fn python_minor(&self) -> u8 {
398 let minor = self.markers.python_full_version().version.release()[1];
399 u8::try_from(minor).expect("invalid minor version")
400 }
401
402 pub fn python_patch(&self) -> u8 {
404 let minor = self.markers.python_full_version().version.release()[2];
405 u8::try_from(minor).expect("invalid patch version")
406 }
407
408 pub fn python_tuple(&self) -> (u8, u8) {
410 (self.python_major(), self.python_minor())
411 }
412
413 pub fn implementation_major(&self) -> u8 {
415 let major = self.markers.implementation_version().version.release()[0];
416 u8::try_from(major).expect("invalid major version")
417 }
418
419 pub fn implementation_minor(&self) -> u8 {
421 let minor = self.markers.implementation_version().version.release()[1];
422 u8::try_from(minor).expect("invalid minor version")
423 }
424
425 pub fn implementation_tuple(&self) -> (u8, u8) {
427 (self.implementation_major(), self.implementation_minor())
428 }
429
430 pub fn implementation_name(&self) -> &str {
432 self.markers.implementation_name()
433 }
434
435 pub fn sys_base_exec_prefix(&self) -> &Path {
437 &self.sys_base_exec_prefix
438 }
439
440 pub fn sys_base_prefix(&self) -> &Path {
442 &self.sys_base_prefix
443 }
444
445 pub fn sys_prefix(&self) -> &Path {
447 &self.sys_prefix
448 }
449
450 pub fn sys_base_executable(&self) -> Option<&Path> {
453 self.sys_base_executable.as_deref()
454 }
455
456 pub fn sys_executable(&self) -> &Path {
458 &self.sys_executable
459 }
460
461 pub fn real_executable(&self) -> &Path {
463 &self.real_executable
464 }
465
466 pub fn sys_path(&self) -> &[PathBuf] {
468 &self.sys_path
469 }
470
471 pub fn runtime_site_packages(&self) -> &[PathBuf] {
479 &self.site_packages
480 }
481
482 pub fn stdlib(&self) -> &Path {
484 &self.stdlib
485 }
486
487 pub fn purelib(&self) -> &Path {
489 &self.scheme.purelib
490 }
491
492 pub fn platlib(&self) -> &Path {
494 &self.scheme.platlib
495 }
496
497 pub fn scripts(&self) -> &Path {
499 &self.scheme.scripts
500 }
501
502 pub fn data(&self) -> &Path {
504 &self.scheme.data
505 }
506
507 pub fn include(&self) -> &Path {
509 &self.scheme.include
510 }
511
512 pub fn virtualenv(&self) -> &Scheme {
514 &self.virtualenv
515 }
516
517 pub fn manylinux_compatible(&self) -> bool {
519 self.manylinux_compatible
520 }
521
522 pub fn pointer_size(&self) -> PointerSize {
524 self.pointer_size
525 }
526
527 pub fn gil_disabled(&self) -> bool {
533 self.gil_disabled
534 }
535
536 pub fn debug_enabled(&self) -> bool {
539 self.debug_enabled
540 }
541
542 pub fn target(&self) -> Option<&Target> {
544 self.target.as_ref()
545 }
546
547 pub fn prefix(&self) -> Option<&Prefix> {
549 self.prefix.as_ref()
550 }
551
552 #[cfg(unix)]
561 pub fn is_standalone(&self) -> bool {
562 self.standalone
563 }
564
565 #[cfg(windows)]
569 pub fn is_standalone(&self) -> bool {
570 self.standalone || (self.is_managed() && self.markers().implementation_name() == "cpython")
571 }
572
573 pub fn layout(&self) -> Layout {
575 Layout {
576 python_version: self.python_tuple(),
577 sys_executable: self.sys_executable().to_path_buf(),
578 os_name: self.markers.os_name().to_string(),
579 scheme: if let Some(target) = self.target.as_ref() {
580 target.scheme()
581 } else if let Some(prefix) = self.prefix.as_ref() {
582 prefix.scheme(&self.virtualenv)
583 } else {
584 Scheme {
585 purelib: self.purelib().to_path_buf(),
586 platlib: self.platlib().to_path_buf(),
587 scripts: self.scripts().to_path_buf(),
588 data: self.data().to_path_buf(),
589 include: if self.is_virtualenv() {
590 self.sys_prefix.join("include").join("site").join(format!(
593 "python{}.{}",
594 self.python_major(),
595 self.python_minor()
596 ))
597 } else {
598 self.include().to_path_buf()
599 },
600 }
601 },
602 }
603 }
604
605 pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> {
616 let target = self.target().map(Target::site_packages);
617
618 let prefix = self
619 .prefix()
620 .map(|prefix| prefix.site_packages(self.virtualenv()));
621
622 let interpreter = if target.is_none() && prefix.is_none() {
623 let purelib = self.purelib();
624 let platlib = self.platlib();
625 Some(std::iter::once(purelib).chain(
626 if purelib == platlib || is_same_file(purelib, platlib).unwrap_or(false) {
627 None
628 } else {
629 Some(platlib)
630 },
631 ))
632 } else {
633 None
634 };
635
636 target
637 .into_iter()
638 .flatten()
639 .map(Cow::Borrowed)
640 .chain(prefix.into_iter().flatten().map(Cow::Owned))
641 .chain(interpreter.into_iter().flatten().map(Cow::Borrowed))
642 }
643
644 pub fn satisfies(&self, version: &PythonVersion) -> bool {
649 if version.patch().is_some() {
650 version.version() == self.python_version()
651 } else {
652 (version.major(), version.minor()) == self.python_tuple()
653 }
654 }
655
656 pub(crate) fn has_default_executable_name(&self) -> bool {
659 let Some(file_name) = self.sys_executable().file_name() else {
660 return false;
661 };
662 let Some(name) = file_name.to_str() else {
663 return false;
664 };
665 VersionRequest::Default
666 .executable_names(None)
667 .into_iter()
668 .any(|default_name| name == default_name.to_string())
669 }
670
671 pub async fn lock(&self) -> Result<LockedFile, LockedFileError> {
673 if let Some(target) = self.target() {
674 LockedFile::acquire(
676 target.root().join(".lock"),
677 LockedFileMode::Exclusive,
678 target.root().user_display(),
679 )
680 .await
681 } else if let Some(prefix) = self.prefix() {
682 LockedFile::acquire(
684 prefix.root().join(".lock"),
685 LockedFileMode::Exclusive,
686 prefix.root().user_display(),
687 )
688 .await
689 } else if self.is_virtualenv() {
690 LockedFile::acquire(
692 self.sys_prefix.join(".lock"),
693 LockedFileMode::Exclusive,
694 self.sys_prefix.user_display(),
695 )
696 .await
697 } else {
698 LockedFile::acquire(
700 env::temp_dir().join(format!("uv-{}.lock", cache_digest(&self.sys_executable))),
701 LockedFileMode::Exclusive,
702 self.sys_prefix.user_display(),
703 )
704 .await
705 }
706 }
707}
708
709pub fn canonicalize_executable(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
712 let path = path.as_ref();
713 debug_assert!(
714 path.is_absolute(),
715 "path must be absolute: {}",
716 path.display()
717 );
718
719 #[cfg(windows)]
720 {
721 if let Ok(Some(launcher)) = uv_trampoline_builder::Launcher::try_from_path(path) {
722 Ok(dunce::canonicalize(launcher.python_path)?)
723 } else {
724 Ok(path.to_path_buf())
725 }
726 }
727
728 #[cfg(unix)]
729 fs_err::canonicalize(path)
730}
731
732#[derive(Debug, Default, Clone)]
736pub struct ExternallyManaged {
737 error: Option<String>,
738}
739
740impl ExternallyManaged {
741 pub fn into_error(self) -> Option<String> {
743 self.error
744 }
745}
746
747#[derive(Debug, Error)]
748pub struct UnexpectedResponseError {
749 #[source]
750 pub(super) err: serde_json::Error,
751 pub(super) stdout: String,
752 pub(super) stderr: String,
753 pub(super) path: PathBuf,
754}
755
756impl Display for UnexpectedResponseError {
757 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
758 write!(
759 f,
760 "Querying Python at `{}` returned an invalid response: {}",
761 self.path.display(),
762 self.err
763 )?;
764
765 let mut non_empty = false;
766
767 if !self.stdout.trim().is_empty() {
768 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
769 non_empty = true;
770 }
771
772 if !self.stderr.trim().is_empty() {
773 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
774 non_empty = true;
775 }
776
777 if non_empty {
778 writeln!(f)?;
779 }
780
781 Ok(())
782 }
783}
784
785#[derive(Debug, Error)]
786pub struct StatusCodeError {
787 pub(super) code: ExitStatus,
788 pub(super) stdout: String,
789 pub(super) stderr: String,
790 pub(super) path: PathBuf,
791}
792
793impl Display for StatusCodeError {
794 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
795 write!(
796 f,
797 "Querying Python at `{}` failed with exit status {}",
798 self.path.display(),
799 self.code
800 )?;
801
802 let mut non_empty = false;
803
804 if !self.stdout.trim().is_empty() {
805 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
806 non_empty = true;
807 }
808
809 if !self.stderr.trim().is_empty() {
810 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
811 non_empty = true;
812 }
813
814 if non_empty {
815 writeln!(f)?;
816 }
817
818 Ok(())
819 }
820}
821
822#[derive(Debug, Error)]
823pub enum Error {
824 #[error("Failed to query Python interpreter")]
825 Io(#[from] io::Error),
826 #[error(transparent)]
827 BrokenLink(BrokenLink),
828 #[error("Python interpreter not found at `{0}`")]
829 NotFound(PathBuf),
830 #[error("Failed to query Python interpreter at `{path}`")]
831 SpawnFailed {
832 path: PathBuf,
833 #[source]
834 err: io::Error,
835 },
836 #[cfg(windows)]
837 #[error("Failed to query Python interpreter at `{path}`")]
838 CorruptWindowsPackage {
839 path: PathBuf,
840 #[source]
841 err: io::Error,
842 },
843 #[error("Failed to query Python interpreter at `{path}`")]
844 PermissionDenied {
845 path: PathBuf,
846 #[source]
847 err: io::Error,
848 },
849 #[error("{0}")]
850 UnexpectedResponse(UnexpectedResponseError),
851 #[error("{0}")]
852 StatusCode(StatusCodeError),
853 #[error("Can't use Python at `{path}`")]
854 QueryScript {
855 #[source]
856 err: InterpreterInfoError,
857 path: PathBuf,
858 },
859 #[error("Failed to write to cache")]
860 Encode(#[from] rmp_serde::encode::Error),
861}
862
863#[derive(Debug, Error)]
864pub struct BrokenLink {
865 pub path: PathBuf,
866 pub unix: bool,
869 pub venv: bool,
871}
872
873impl Display for BrokenLink {
874 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
875 if self.unix {
876 write!(
877 f,
878 "Broken symlink at `{}`, was the underlying Python interpreter removed?",
879 self.path.user_display()
880 )?;
881 } else {
882 write!(
883 f,
884 "Broken Python trampoline at `{}`, was the underlying Python interpreter removed?",
885 self.path.user_display()
886 )?;
887 }
888 if self.venv {
889 write!(
890 f,
891 "\n\n{}{} Consider recreating the environment (e.g., with `{}`)",
892 "hint".bold().cyan(),
893 ":".bold(),
894 "uv venv".green()
895 )?;
896 }
897 Ok(())
898 }
899}
900
901#[derive(Debug, Deserialize, Serialize)]
902#[serde(tag = "result", rename_all = "lowercase")]
903enum InterpreterInfoResult {
904 Error(InterpreterInfoError),
905 Success(Box<InterpreterInfo>),
906}
907
908#[derive(Debug, Error, Deserialize, Serialize)]
909#[serde(tag = "kind", rename_all = "snake_case")]
910pub enum InterpreterInfoError {
911 #[error("Could not detect a glibc or a musl libc (while running on Linux)")]
912 LibcNotFound,
913 #[error(
914 "Broken Python installation, `platform.mac_ver()` returned an empty value, please reinstall Python"
915 )]
916 BrokenMacVer,
917 #[error("Unknown operating system: `{operating_system}`")]
918 UnknownOperatingSystem { operating_system: String },
919 #[error("Python {python_version} is not supported. Please use Python 3.8 or newer.")]
920 UnsupportedPythonVersion { python_version: String },
921 #[error("Python executable does not support `-I` flag. Please use Python 3.8 or newer.")]
922 UnsupportedPython,
923 #[error(
924 "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`."
925 )]
926 MissingRequiredDistutils {
927 python_major: usize,
928 python_minor: usize,
929 },
930 #[error("Only Pyodide is support for Emscripten Python")]
931 EmscriptenNotPyodide,
932}
933
934#[expect(clippy::struct_excessive_bools)]
935#[derive(Debug, Deserialize, Serialize, Clone)]
936struct InterpreterInfo {
937 platform: Platform,
938 markers: MarkerEnvironment,
939 scheme: Scheme,
940 virtualenv: Scheme,
941 manylinux_compatible: bool,
942 sys_prefix: PathBuf,
943 sys_base_exec_prefix: PathBuf,
944 sys_base_prefix: PathBuf,
945 sys_base_executable: Option<PathBuf>,
946 sys_executable: PathBuf,
947 sys_path: Vec<PathBuf>,
948 site_packages: Vec<PathBuf>,
949 stdlib: PathBuf,
950 standalone: bool,
951 pointer_size: PointerSize,
952 gil_disabled: bool,
953 debug_enabled: bool,
954}
955
956impl InterpreterInfo {
957 pub(crate) fn query(interpreter: &Path, cache: &Cache) -> Result<Self, Error> {
959 let tempdir = tempfile::tempdir_in(cache.root())?;
960 Self::setup_python_query_files(tempdir.path())?;
961
962 let script = format!(
966 r#"import sys; sys.path = ["{}"] + sys.path; from python.get_interpreter_info import main; main()"#,
967 tempdir.path().escape_for_python()
968 );
969 let output = Command::new(interpreter)
970 .arg("-I") .arg("-B") .arg("-c")
973 .arg(script)
974 .output()
975 .map_err(|err| {
976 match err.kind() {
977 io::ErrorKind::NotFound => return Error::NotFound(interpreter.to_path_buf()),
978 io::ErrorKind::PermissionDenied => {
979 return Error::PermissionDenied {
980 path: interpreter.to_path_buf(),
981 err,
982 };
983 }
984 _ => {}
985 }
986 #[cfg(windows)]
987 if let Some(APPMODEL_ERROR_NO_PACKAGE | ERROR_CANT_ACCESS_FILE) = err
988 .raw_os_error()
989 .and_then(|code| u32::try_from(code).ok())
990 .map(WIN32_ERROR)
991 {
992 return Error::CorruptWindowsPackage {
995 path: interpreter.to_path_buf(),
996 err,
997 };
998 }
999 Error::SpawnFailed {
1000 path: interpreter.to_path_buf(),
1001 err,
1002 }
1003 })?;
1004
1005 if !output.status.success() {
1006 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1007
1008 if python_home(interpreter).is_some_and(|home| !home.exists()) {
1014 return Err(Error::BrokenLink(BrokenLink {
1015 path: interpreter.to_path_buf(),
1016 unix: false,
1017 venv: uv_fs::is_virtualenv_executable(interpreter),
1018 }));
1019 }
1020
1021 if stderr.contains("Unknown option: -I") {
1023 return Err(Error::QueryScript {
1024 err: InterpreterInfoError::UnsupportedPython,
1025 path: interpreter.to_path_buf(),
1026 });
1027 }
1028
1029 return Err(Error::StatusCode(StatusCodeError {
1030 code: output.status,
1031 stderr,
1032 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1033 path: interpreter.to_path_buf(),
1034 }));
1035 }
1036
1037 let result: InterpreterInfoResult =
1038 serde_json::from_slice(&output.stdout).map_err(|err| {
1039 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1040
1041 if stderr.contains("Unknown option: -I") {
1043 Error::QueryScript {
1044 err: InterpreterInfoError::UnsupportedPython,
1045 path: interpreter.to_path_buf(),
1046 }
1047 } else {
1048 Error::UnexpectedResponse(UnexpectedResponseError {
1049 err,
1050 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1051 stderr,
1052 path: interpreter.to_path_buf(),
1053 })
1054 }
1055 })?;
1056
1057 match result {
1058 InterpreterInfoResult::Error(err) => Err(Error::QueryScript {
1059 err,
1060 path: interpreter.to_path_buf(),
1061 }),
1062 InterpreterInfoResult::Success(data) => Ok(*data),
1063 }
1064 }
1065
1066 fn setup_python_query_files(root: &Path) -> Result<(), Error> {
1069 let python_dir = root.join("python");
1070 fs_err::create_dir(&python_dir)?;
1071 fs_err::write(
1072 python_dir.join("get_interpreter_info.py"),
1073 include_str!("../python/get_interpreter_info.py"),
1074 )?;
1075 fs_err::write(
1076 python_dir.join("__init__.py"),
1077 include_str!("../python/__init__.py"),
1078 )?;
1079 let packaging_dir = python_dir.join("packaging");
1080 fs_err::create_dir(&packaging_dir)?;
1081 fs_err::write(
1082 packaging_dir.join("__init__.py"),
1083 include_str!("../python/packaging/__init__.py"),
1084 )?;
1085 fs_err::write(
1086 packaging_dir.join("_elffile.py"),
1087 include_str!("../python/packaging/_elffile.py"),
1088 )?;
1089 fs_err::write(
1090 packaging_dir.join("_manylinux.py"),
1091 include_str!("../python/packaging/_manylinux.py"),
1092 )?;
1093 fs_err::write(
1094 packaging_dir.join("_musllinux.py"),
1095 include_str!("../python/packaging/_musllinux.py"),
1096 )?;
1097 Ok(())
1098 }
1099
1100 pub(crate) fn query_cached(executable: &Path, cache: &Cache) -> Result<Self, Error> {
1106 let absolute = std::path::absolute(executable)?;
1107
1108 let handle_io_error = |err: io::Error| -> Error {
1112 if err.kind() == io::ErrorKind::NotFound {
1113 if absolute
1116 .symlink_metadata()
1117 .is_ok_and(|metadata| metadata.is_symlink())
1118 {
1119 Error::BrokenLink(BrokenLink {
1120 path: executable.to_path_buf(),
1121 unix: true,
1122 venv: uv_fs::is_virtualenv_executable(executable),
1123 })
1124 } else {
1125 Error::NotFound(executable.to_path_buf())
1126 }
1127 } else {
1128 err.into()
1129 }
1130 };
1131
1132 let canonical = canonicalize_executable(&absolute).map_err(handle_io_error)?;
1133
1134 let cache_entry = cache.entry(
1135 CacheBucket::Interpreter,
1136 cache_digest(&(
1139 ARCH,
1140 uv_platform::host::OsType::from_env()
1141 .map(|os_type| os_type.to_string())
1142 .unwrap_or_default(),
1143 uv_platform::host::OsRelease::from_env()
1144 .map(|os_release| os_release.to_string())
1145 .unwrap_or_default(),
1146 )),
1147 format!("{}.msgpack", cache_digest(&(&absolute, &canonical))),
1155 );
1156
1157 let modified = Timestamp::from_path(canonical).map_err(handle_io_error)?;
1160
1161 if cache
1163 .freshness(&cache_entry, None, None)
1164 .is_ok_and(Freshness::is_fresh)
1165 {
1166 if let Ok(data) = fs::read(cache_entry.path()) {
1167 match rmp_serde::from_slice::<CachedByTimestamp<Self>>(&data) {
1168 Ok(cached) => {
1169 if cached.timestamp == modified {
1170 trace!(
1171 "Found cached interpreter info for Python {}, skipping query of: {}",
1172 cached.data.markers.python_full_version(),
1173 executable.user_display()
1174 );
1175 return Ok(cached.data);
1176 }
1177
1178 trace!(
1179 "Ignoring stale interpreter markers for: {}",
1180 executable.user_display()
1181 );
1182 }
1183 Err(err) => {
1184 warn!(
1185 "Broken interpreter cache entry at {}, removing: {err}",
1186 cache_entry.path().user_display()
1187 );
1188 let _ = fs_err::remove_file(cache_entry.path());
1189 }
1190 }
1191 }
1192 }
1193
1194 trace!(
1196 "Querying interpreter executable at {}",
1197 executable.display()
1198 );
1199 let info = Self::query(executable, cache)?;
1200
1201 if is_same_file(executable, &info.sys_executable).unwrap_or(false) {
1204 fs::create_dir_all(cache_entry.dir())?;
1205 write_atomic_sync(
1206 cache_entry.path(),
1207 rmp_serde::to_vec(&CachedByTimestamp {
1208 timestamp: modified,
1209 data: info.clone(),
1210 })?,
1211 )?;
1212 }
1213
1214 Ok(info)
1215 }
1216}
1217
1218fn find_base_python(
1244 executable: &Path,
1245 major: u8,
1246 minor: u8,
1247 suffix: &str,
1248) -> Result<PathBuf, io::Error> {
1249 fn is_root(path: &Path) -> bool {
1251 let mut components = path.components();
1252 components.next() == Some(std::path::Component::RootDir) && components.next().is_none()
1253 }
1254
1255 fn is_prefix(dir: &Path, major: u8, minor: u8, suffix: &str) -> bool {
1259 if cfg!(windows) {
1260 dir.join("Lib").join("os.py").is_file()
1261 } else {
1262 dir.join("lib")
1263 .join(format!("python{major}.{minor}{suffix}"))
1264 .join("os.py")
1265 .is_file()
1266 }
1267 }
1268
1269 let mut executable = Cow::Borrowed(executable);
1270
1271 loop {
1272 debug!(
1273 "Assessing Python executable as base candidate: {}",
1274 executable.display()
1275 );
1276
1277 for prefix in executable.ancestors().take_while(|path| !is_root(path)) {
1279 if is_prefix(prefix, major, minor, suffix) {
1280 return Ok(executable.into_owned());
1281 }
1282 }
1283
1284 let resolved = fs_err::read_link(&executable)?;
1286
1287 let resolved = if resolved.is_relative() {
1289 if let Some(parent) = executable.parent() {
1290 parent.join(resolved)
1291 } else {
1292 return Err(io::Error::other("Symlink has no parent directory"));
1293 }
1294 } else {
1295 resolved
1296 };
1297
1298 let resolved = uv_fs::normalize_absolute_path(&resolved)?;
1300
1301 executable = Cow::Owned(resolved);
1302 }
1303}
1304
1305fn python_home(interpreter: &Path) -> Option<PathBuf> {
1307 let venv_root = interpreter.parent()?.parent()?;
1308 let pyvenv_cfg = PyVenvConfiguration::parse(venv_root.join("pyvenv.cfg")).ok()?;
1309 pyvenv_cfg.home
1310}
1311
1312#[cfg(unix)]
1313#[cfg(test)]
1314mod tests {
1315 use std::str::FromStr;
1316
1317 use fs_err as fs;
1318 use indoc::{formatdoc, indoc};
1319 use tempfile::tempdir;
1320
1321 use uv_cache::Cache;
1322 use uv_pep440::Version;
1323
1324 use crate::Interpreter;
1325
1326 #[tokio::test]
1327 async fn test_cache_invalidation() {
1328 let mock_dir = tempdir().unwrap();
1329 let mocked_interpreter = mock_dir.path().join("python");
1330 let json = indoc! {r##"
1331 {
1332 "result": "success",
1333 "platform": {
1334 "os": {
1335 "name": "manylinux",
1336 "major": 2,
1337 "minor": 38
1338 },
1339 "arch": "x86_64"
1340 },
1341 "manylinux_compatible": false,
1342 "standalone": false,
1343 "markers": {
1344 "implementation_name": "cpython",
1345 "implementation_version": "3.12.0",
1346 "os_name": "posix",
1347 "platform_machine": "x86_64",
1348 "platform_python_implementation": "CPython",
1349 "platform_release": "6.5.0-13-generic",
1350 "platform_system": "Linux",
1351 "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov 3 12:16:05 UTC 2023",
1352 "python_full_version": "3.12.0",
1353 "python_version": "3.12",
1354 "sys_platform": "linux"
1355 },
1356 "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1357 "sys_base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1358 "sys_prefix": "/home/ferris/projects/uv/.venv",
1359 "sys_executable": "/home/ferris/projects/uv/.venv/bin/python",
1360 "sys_path": [
1361 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/lib/python3.12",
1362 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1363 ],
1364 "site_packages": [
1365 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1366 ],
1367 "stdlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12",
1368 "scheme": {
1369 "data": "/home/ferris/.pyenv/versions/3.12.0",
1370 "include": "/home/ferris/.pyenv/versions/3.12.0/include",
1371 "platlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1372 "purelib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1373 "scripts": "/home/ferris/.pyenv/versions/3.12.0/bin"
1374 },
1375 "virtualenv": {
1376 "data": "",
1377 "include": "include",
1378 "platlib": "lib/python3.12/site-packages",
1379 "purelib": "lib/python3.12/site-packages",
1380 "scripts": "bin"
1381 },
1382 "pointer_size": "64",
1383 "gil_disabled": true,
1384 "debug_enabled": false
1385 }
1386 "##};
1387
1388 let cache = Cache::temp().unwrap().init().await.unwrap();
1389
1390 fs::write(
1391 &mocked_interpreter,
1392 formatdoc! {r"
1393 #!/bin/sh
1394 echo '{json}'
1395 "},
1396 )
1397 .unwrap();
1398
1399 fs::set_permissions(
1400 &mocked_interpreter,
1401 std::os::unix::fs::PermissionsExt::from_mode(0o770),
1402 )
1403 .unwrap();
1404 let interpreter = Interpreter::query(&mocked_interpreter, &cache).unwrap();
1405 assert_eq!(
1406 interpreter.markers.python_version().version,
1407 Version::from_str("3.12").unwrap()
1408 );
1409 fs::write(
1410 &mocked_interpreter,
1411 formatdoc! {r"
1412 #!/bin/sh
1413 echo '{}'
1414 ", json.replace("3.12", "3.13")},
1415 )
1416 .unwrap();
1417 let interpreter = Interpreter::query(&mocked_interpreter, &cache).unwrap();
1418 assert_eq!(
1419 interpreter.markers.python_version().version,
1420 Version::from_str("3.13").unwrap()
1421 );
1422 }
1423}