1use std::borrow::Cow;
2use std::collections::{BTreeSet, HashMap};
3use std::env::consts::ARCH;
4use std::fmt::{Display, Formatter};
5use std::path::{Path, PathBuf};
6use std::process::{Command, ExitStatus};
7use std::sync::OnceLock;
8use std::{env, io};
9
10use astral_ini::Options;
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, CacheEntry, Freshness};
19use uv_cache_info::Timestamp;
20use uv_cache_key::cache_digest;
21use uv_errors::Hints;
22use uv_fs::{
23 LockedFile, LockedFileError, LockedFileMode, PythonExt, Simplified, write_atomic_sync,
24};
25use uv_install_wheel::Layout;
26use uv_pep440::Version;
27use uv_pep508::{MarkerEnvironment, StringVersion};
28use uv_platform::{Arch, Libc, Os};
29use uv_platform_tags::{CpuInfo, Platform, Tags, TagsError, TagsOptions};
30use uv_preview::PreviewFeature;
31use uv_pypi_types::{ResolverMarkerEnvironment, Scheme};
32use uv_static::EnvVars;
33use uv_warnings::warn_user_once_with_chain;
34
35use crate::PointerSize;
36use crate::PyVenvConfiguration;
37use crate::VirtualEnvironment;
38use crate::virtualenv::virtualenv_python_executable;
39use uv_python_types::{
40 ImplementationName, LenientImplementationName, Prefix, PythonDownloadRequest,
41 PythonInstallationKey, PythonRequest, PythonVariant, Target, VersionRequest,
42};
43use which::which;
44
45#[cfg(windows)]
46use windows::Win32::Foundation::{APPMODEL_ERROR_NO_PACKAGE, ERROR_CANT_ACCESS_FILE, WIN32_ERROR};
47
48#[cfg_attr(unix, expect(clippy::struct_excessive_bools))]
50#[derive(Debug, Clone)]
51pub struct Interpreter {
52 platform: Platform,
53 markers: Box<MarkerEnvironment>,
54 scheme: Scheme,
55 virtualenv: Scheme,
56 manylinux_compatible: bool,
57 sys_prefix: PathBuf,
58 sys_base_prefix: PathBuf,
59 sys_base_executable: Option<PathBuf>,
60 sys_executable: PathBuf,
61 site_packages: Vec<PathBuf>,
62 stdlib: PathBuf,
63 extension_suffixes: Vec<Box<str>>,
64 #[cfg(unix)]
65 standalone: bool,
66 tags: OnceLock<Tags>,
67 target: Option<Target>,
68 prefix: Option<Prefix>,
69 pointer_size: PointerSize,
70 gil_disabled: bool,
71 real_executable: PathBuf,
72 debug_enabled: bool,
73}
74
75impl Interpreter {
76 pub fn query(executable: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> {
78 let executable = executable.as_ref();
79 let InterpreterInfo {
80 platform,
81 metadata: info,
82 ..
83 } = InterpreterInfo::query_cached(executable, cache, || {
84 InterpreterInfo::query(executable, cache)
85 })?;
86
87 debug_assert!(
88 info.sys_executable.is_absolute(),
89 "`sys.executable` is not an absolute Python; Python installation is broken: {}",
90 info.sys_executable.display()
91 );
92
93 Ok(Self {
94 platform,
95 markers: Box::new(info.markers),
96 scheme: info.scheme,
97 virtualenv: info.virtualenv,
98 manylinux_compatible: info.manylinux_compatible,
99 sys_prefix: info.sys_prefix,
100 pointer_size: info.pointer_size,
101 gil_disabled: info.gil_disabled,
102 debug_enabled: info.debug_enabled,
103 sys_base_prefix: info.sys_base_prefix,
104 sys_base_executable: info.sys_base_executable,
105 sys_executable: info.sys_executable,
106 site_packages: info.site_packages,
107 stdlib: info.stdlib,
108 extension_suffixes: info.extension_suffixes,
109 #[cfg(unix)]
110 standalone: info.standalone,
111 tags: OnceLock::new(),
112 target: None,
113 prefix: None,
114 real_executable: executable.to_path_buf(),
115 })
116 }
117
118 pub fn clear_cache(executable: impl AsRef<Path>, cache: &Cache) -> Result<(), Error> {
120 let absolute = std::path::absolute(executable.as_ref())?;
121 let canonical = canonicalize_executable(&absolute)?;
122 let cache_entry = InterpreterInfo::cache_entry(&absolute, &canonical, cache);
123
124 match fs::remove_file(cache_entry.path()) {
125 Ok(()) => Ok(()),
126 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
127 Err(err) => Err(err.into()),
128 }
129 }
130
131 #[must_use]
133 pub fn with_virtualenv(self, virtualenv: VirtualEnvironment) -> Self {
134 Self {
135 scheme: virtualenv.scheme,
136 sys_base_executable: Some(virtualenv.base_executable),
137 sys_executable: virtualenv.executable,
138 sys_prefix: virtualenv.root,
139 target: None,
140 prefix: None,
141 site_packages: vec![],
142 ..self
143 }
144 }
145
146 pub(crate) fn with_target(self, target: Target) -> io::Result<Self> {
148 fs::create_dir_all(target.root())?;
149 Ok(Self {
150 target: Some(target),
151 ..self
152 })
153 }
154
155 pub(crate) fn with_prefix(self, prefix: Prefix) -> io::Result<Self> {
157 fs::create_dir_all(prefix.root().join(&self.virtualenv.purelib))?;
158 Ok(Self {
159 prefix: Some(prefix),
160 ..self
161 })
162 }
163
164 pub fn to_base_python(&self) -> Result<PathBuf, io::Error> {
174 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
175 let base_python = std::path::absolute(base_executable)?;
176 Ok(base_python)
177 }
178
179 pub fn find_base_python(&self) -> Result<PathBuf, io::Error> {
190 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
191 let base_python = match find_base_python(
201 base_executable,
202 self.python_major(),
203 self.python_minor(),
204 self.variant().executable_suffix(),
205 ) {
206 Ok(path) => path,
207 Err(err) => {
208 warn!("Failed to find base Python executable: {err}");
209 canonicalize_executable(base_executable)?
210 }
211 };
212 Ok(base_python)
213 }
214
215 #[inline]
217 pub fn platform(&self) -> &Platform {
218 &self.platform
219 }
220
221 #[inline]
223 pub const fn markers(&self) -> &MarkerEnvironment {
224 &self.markers
225 }
226
227 pub fn to_resolver_marker_environment(&self) -> ResolverMarkerEnvironment {
229 ResolverMarkerEnvironment::from(self.markers().clone())
230 }
231
232 pub fn key(&self) -> PythonInstallationKey {
234 PythonInstallationKey::new(
235 LenientImplementationName::from(self.implementation_name()),
236 self.python_major(),
237 self.python_minor(),
238 self.python_patch(),
239 self.python_version().pre(),
240 uv_platform::Platform::new(self.os(), self.arch(), self.libc()),
241 self.variant(),
242 )
243 }
244
245 pub fn variant(&self) -> PythonVariant {
246 if self.gil_disabled() {
247 if self.debug_enabled() {
248 PythonVariant::FreethreadedDebug
249 } else {
250 PythonVariant::Freethreaded
251 }
252 } else if self.debug_enabled() {
253 PythonVariant::Debug
254 } else {
255 PythonVariant::default()
256 }
257 }
258
259 pub fn arch(&self) -> Arch {
261 Arch::from(&self.platform().arch())
262 }
263
264 pub fn libc(&self) -> Libc {
266 Libc::from(self.platform().os())
267 }
268
269 pub fn os(&self) -> Os {
271 Os::from(self.platform().os())
272 }
273
274 pub fn tags(&self) -> Result<&Tags, TagsError> {
276 if self.tags.get().is_none() {
277 let tags = Tags::from_env(
278 self.platform().clone(),
279 self.python_tuple(),
280 self.implementation_name(),
281 self.implementation_tuple(),
282 TagsOptions {
283 manylinux_compatible: self.manylinux_compatible,
284 gil_disabled: self.gil_disabled,
285 debug_enabled: self.debug_enabled,
286 is_cross: false,
287 },
288 )?;
289 self.tags.set(tags).expect("tags should not be set");
290 }
291 Ok(self.tags.get().expect("tags should be set"))
292 }
293
294 pub fn is_virtualenv(&self) -> bool {
298 self.sys_prefix != self.sys_base_prefix
300 }
301
302 fn is_target(&self) -> bool {
304 self.target.is_some()
305 }
306
307 fn is_prefix(&self) -> bool {
309 self.prefix.is_some()
310 }
311
312 pub fn is_externally_managed(&self) -> Option<ExternallyManaged> {
317 if self.is_virtualenv() {
319 return None;
320 }
321
322 if self.is_target() || self.is_prefix() {
324 return None;
325 }
326
327 let Ok(contents) = fs::read_to_string(self.stdlib.join("EXTERNALLY-MANAGED")) else {
328 return None;
329 };
330
331 let Ok(ini) = Options::default().case_sensitive(true).parse(&contents) else {
332 return Some(ExternallyManaged::default());
335 };
336
337 Some(ExternallyManaged {
338 error: ini.get("externally-managed", "Error").map(str::to_owned),
339 })
340 }
341
342 #[inline]
344 pub fn python_full_version(&self) -> &StringVersion {
345 self.markers.python_full_version()
346 }
347
348 #[inline]
350 pub fn python_version(&self) -> &Version {
351 &self.markers.python_full_version().version
352 }
353
354 #[inline]
356 pub fn python_minor_version(&self) -> Version {
357 Version::new(self.python_version().release().iter().take(2).copied())
358 }
359
360 #[inline]
362 pub(crate) fn python_patch_version(&self) -> Version {
363 Version::new(self.python_version().release().iter().take(3).copied())
364 }
365
366 pub fn python_major(&self) -> u8 {
368 let major = self.markers.python_full_version().version.release()[0];
369 u8::try_from(major).expect("invalid major version")
370 }
371
372 pub fn python_minor(&self) -> u8 {
374 let minor = self.markers.python_full_version().version.release()[1];
375 u8::try_from(minor).expect("invalid minor version")
376 }
377
378 fn python_patch(&self) -> u8 {
380 let minor = self.markers.python_full_version().version.release()[2];
381 u8::try_from(minor).expect("invalid patch version")
382 }
383
384 pub fn python_tuple(&self) -> (u8, u8) {
386 (self.python_major(), self.python_minor())
387 }
388
389 fn implementation_major(&self) -> u8 {
391 let major = self.markers.implementation_version().version.release()[0];
392 u8::try_from(major).expect("invalid major version")
393 }
394
395 fn implementation_minor(&self) -> u8 {
397 let minor = self.markers.implementation_version().version.release()[1];
398 u8::try_from(minor).expect("invalid minor version")
399 }
400
401 pub fn implementation_tuple(&self) -> (u8, u8) {
403 (self.implementation_major(), self.implementation_minor())
404 }
405
406 pub fn implementation_name(&self) -> &str {
408 self.markers.implementation_name()
409 }
410
411 pub fn sys_base_prefix(&self) -> &Path {
413 &self.sys_base_prefix
414 }
415
416 pub fn sys_prefix(&self) -> &Path {
418 &self.sys_prefix
419 }
420
421 fn sys_base_executable(&self) -> Option<&Path> {
424 self.sys_base_executable.as_deref()
425 }
426
427 pub fn sys_executable(&self) -> &Path {
429 &self.sys_executable
430 }
431
432 pub fn extension_suffixes(&self) -> &[Box<str>] {
434 &self.extension_suffixes
435 }
436
437 pub fn real_executable(&self) -> &Path {
439 &self.real_executable
440 }
441
442 pub fn runtime_site_packages(&self) -> &[PathBuf] {
450 &self.site_packages
451 }
452
453 pub fn stdlib(&self) -> &Path {
455 &self.stdlib
456 }
457
458 fn purelib(&self) -> &Path {
460 &self.scheme.purelib
461 }
462
463 fn platlib(&self) -> &Path {
465 &self.scheme.platlib
466 }
467
468 pub fn scripts(&self) -> &Path {
470 &self.scheme.scripts
471 }
472
473 fn data(&self) -> &Path {
475 &self.scheme.data
476 }
477
478 fn include(&self) -> &Path {
480 &self.scheme.include
481 }
482
483 pub fn virtualenv(&self) -> &Scheme {
485 &self.virtualenv
486 }
487
488 pub fn manylinux_compatible(&self) -> bool {
490 self.manylinux_compatible
491 }
492
493 pub fn pointer_size(&self) -> PointerSize {
495 self.pointer_size
496 }
497
498 pub fn gil_disabled(&self) -> bool {
504 self.gil_disabled
505 }
506
507 pub fn debug_enabled(&self) -> bool {
510 self.debug_enabled
511 }
512
513 fn target(&self) -> Option<&Target> {
515 self.target.as_ref()
516 }
517
518 fn prefix(&self) -> Option<&Prefix> {
520 self.prefix.as_ref()
521 }
522
523 #[cfg(unix)]
532 pub fn is_standalone(&self) -> bool {
533 self.standalone
534 }
535
536 pub fn layout(&self) -> Layout {
538 Layout {
539 python_version: self.python_tuple(),
540 sys_executable: self.sys_executable().to_path_buf(),
541 os_name: self.markers.os_name().to_string(),
542 scheme: if let Some(target) = self.target.as_ref() {
543 Scheme {
544 purelib: target.root().to_path_buf(),
545 platlib: target.root().to_path_buf(),
546 scripts: target.root().join("bin"),
547 data: target.root().to_path_buf(),
548 include: target.root().join("include"),
549 }
550 } else if let Some(prefix) = self.prefix.as_ref() {
551 Scheme {
552 purelib: prefix.root().join(&self.virtualenv.purelib),
553 platlib: prefix.root().join(&self.virtualenv.platlib),
554 scripts: prefix.root().join(&self.virtualenv.scripts),
555 data: prefix.root().join(&self.virtualenv.data),
556 include: prefix.root().join(&self.virtualenv.include),
557 }
558 } else {
559 Scheme {
560 purelib: self.purelib().to_path_buf(),
561 platlib: self.platlib().to_path_buf(),
562 scripts: self.scripts().to_path_buf(),
563 data: self.data().to_path_buf(),
564 include: if self.is_virtualenv() {
565 self.sys_prefix.join("include").join("site").join(format!(
568 "python{}.{}",
569 self.python_major(),
570 self.python_minor()
571 ))
572 } else {
573 self.include().to_path_buf()
574 },
575 }
576 },
577 }
578 }
579
580 pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> {
591 let target = self.target().map(Target::root);
592
593 let prefix = self
594 .prefix()
595 .map(|prefix| prefix.root().join(&self.virtualenv.purelib));
596
597 let interpreter = if target.is_none() && prefix.is_none() {
598 let purelib = self.purelib();
599 let platlib = self.platlib();
600 Some(std::iter::once(purelib).chain(
601 if purelib == platlib || is_same_file(purelib, platlib).unwrap_or(false) {
602 None
603 } else {
604 Some(platlib)
605 },
606 ))
607 } else {
608 None
609 };
610
611 target
612 .into_iter()
613 .map(Cow::Borrowed)
614 .chain(prefix.into_iter().map(Cow::Owned))
615 .chain(interpreter.into_iter().flatten().map(Cow::Borrowed))
616 }
617
618 pub fn has_default_executable_name(&self) -> bool {
621 let Some(file_name) = self.sys_executable().file_name() else {
622 return false;
623 };
624 let Some(name) = file_name.to_str() else {
625 return false;
626 };
627 VersionRequest::Default
628 .executable_names(None)
629 .into_iter()
630 .any(|default_name| name == default_name.to_string())
631 }
632
633 pub async fn lock(&self) -> Result<LockedFile, LockedFileError> {
635 if let Some(target) = self.target() {
636 LockedFile::acquire(
638 target.root().join(".lock"),
639 LockedFileMode::Exclusive,
640 target.root().user_display(),
641 )
642 .await
643 } else if let Some(prefix) = self.prefix() {
644 LockedFile::acquire(
646 prefix.root().join(".lock"),
647 LockedFileMode::Exclusive,
648 prefix.root().user_display(),
649 )
650 .await
651 } else if self.is_virtualenv() {
652 LockedFile::acquire(
654 self.sys_prefix.join(".lock"),
655 LockedFileMode::Exclusive,
656 self.sys_prefix.user_display(),
657 )
658 .await
659 } else {
660 LockedFile::acquire(
662 env::temp_dir().join(format!("uv-{}.lock", cache_digest(&self.sys_executable))),
663 LockedFileMode::Exclusive,
664 self.sys_prefix.user_display(),
665 )
666 .await
667 }
668 }
669
670 fn matches_variant(&self, variant: PythonVariant) -> bool {
672 match variant {
673 PythonVariant::Default => {
674 if (self.python_major(), self.python_minor()) >= (3, 14) {
677 true
680 } else {
681 !self.gil_disabled()
684 }
685 }
686 PythonVariant::Debug => self.debug_enabled(),
687 PythonVariant::Freethreaded => self.gil_disabled(),
688 PythonVariant::FreethreadedDebug => self.gil_disabled() && self.debug_enabled(),
689 PythonVariant::Gil => !self.gil_disabled(),
690 PythonVariant::GilDebug => !self.gil_disabled() && self.debug_enabled(),
691 }
692 }
693
694 pub fn matches_implementation(&self, implementation: ImplementationName) -> bool {
696 match implementation {
697 ImplementationName::Pyodide => self.os().is_emscripten(),
698 _ => self
699 .implementation_name()
700 .eq_ignore_ascii_case(implementation.long_name()),
701 }
702 }
703
704 pub fn matches_version_request(&self, request: &VersionRequest) -> bool {
706 match request {
707 VersionRequest::Any => true,
708 VersionRequest::Default => self.matches_variant(PythonVariant::Default),
710 VersionRequest::Major(major, variant) => {
711 self.python_major() == *major && self.matches_variant(*variant)
712 }
713 VersionRequest::MajorMinor(major, minor, variant) => {
714 (self.python_major(), self.python_minor()) == (*major, *minor)
715 && self.matches_variant(*variant)
716 }
717 VersionRequest::MajorMinorPatch(major, minor, patch, variant) => {
718 (
719 self.python_major(),
720 self.python_minor(),
721 self.python_patch(),
722 ) == (*major, *minor, *patch)
723 && self.python_version().pre().is_none()
726 && self.matches_variant(*variant)
727 }
728 VersionRequest::Range(specifiers, variant) => {
729 let version = if specifiers
732 .iter()
733 .any(uv_pep440::VersionSpecifier::any_prerelease)
734 {
735 Cow::Borrowed(self.python_version())
736 } else {
737 Cow::Owned(self.python_version().only_release())
738 };
739 specifiers.contains(&version) && self.matches_variant(*variant)
740 }
741 VersionRequest::MajorMinorPrerelease(major, minor, prerelease, variant) => {
742 let version = self.python_version();
743 let Some(interpreter_prerelease) = version.pre() else {
744 return false;
745 };
746 (
747 self.python_major(),
748 self.python_minor(),
749 interpreter_prerelease,
750 ) == (*major, *minor, *prerelease)
751 && self.matches_variant(*variant)
752 }
753 VersionRequest::MajorMinorPatchPrerelease(major, minor, patch, prerelease, variant) => {
754 let version = self.python_version();
755 let Some(interpreter_prerelease) = version.pre() else {
756 return false;
757 };
758 (
759 self.python_major(),
760 self.python_minor(),
761 self.python_patch(),
762 interpreter_prerelease,
763 ) == (*major, *minor, *patch, *prerelease)
764 && self.matches_variant(*variant)
765 }
766 }
767 }
768
769 pub fn matches_download_request(&self, request: &PythonDownloadRequest) -> bool {
771 let executable = self.sys_executable().display();
772 if let Some(version) = request.version()
773 && !self.matches_version_request(version)
774 {
775 let interpreter_version = self.python_version();
776 debug!(
777 "Skipping interpreter at `{executable}`: version `{interpreter_version}` does not match request `{version}`"
778 );
779 return false;
780 }
781 let platform = request.platform();
782 let interpreter_platform = uv_platform::Platform::from(self.platform());
783 if !platform.matches(&interpreter_platform) {
784 debug!(
785 "Skipping interpreter at `{executable}`: platform `{interpreter_platform}` does not match request `{platform}`",
786 );
787 return false;
788 }
789 if let Some(implementation) = request.implementation()
790 && !self.matches_implementation(*implementation)
791 {
792 debug!(
793 "Skipping interpreter at `{executable}`: implementation `{}` does not match request `{implementation}`",
794 self.implementation_name(),
795 );
796 return false;
797 }
798 true
799 }
800
801 pub fn matches_request(&self, request: &PythonRequest, cache: &Cache) -> bool {
803 fn is_same_executable(path1: &Path, path2: &Path) -> bool {
805 path1 == path2 || is_same_file(path1, path2).unwrap_or(false)
806 }
807
808 match request {
809 PythonRequest::Default | PythonRequest::Any => true,
810 PythonRequest::Version(version_request) => {
811 self.matches_version_request(version_request)
812 }
813 PythonRequest::Directory(directory) => {
814 is_same_executable(directory, self.sys_prefix())
816 || is_same_executable(
817 virtualenv_python_executable(directory).as_path(),
818 self.sys_executable(),
819 )
820 }
821 PythonRequest::File(file) => {
822 if is_same_executable(self.sys_executable(), file) {
824 return true;
825 }
826 if self
828 .sys_base_executable()
829 .is_some_and(|sys_base_executable| {
830 is_same_executable(sys_base_executable, file)
831 })
832 {
833 return true;
834 }
835 if cfg!(windows) {
840 if let Ok(file_interpreter) = Self::query(file, cache) {
841 if let (Some(file_base), Some(interpreter_base)) = (
842 file_interpreter.sys_base_executable(),
843 self.sys_base_executable(),
844 ) {
845 if is_same_executable(file_base, interpreter_base) {
846 return true;
847 }
848 }
849 }
850 }
851 false
852 }
853 PythonRequest::ExecutableName(name) => {
854 if self
856 .sys_executable()
857 .file_name()
858 .is_some_and(|filename| filename == name.as_str())
859 {
860 return true;
861 }
862 if self
864 .sys_base_executable()
865 .and_then(|executable| executable.file_name())
866 .is_some_and(|file_name| file_name == name.as_str())
867 {
868 return true;
869 }
870 if which(name)
873 .ok()
874 .as_ref()
875 .and_then(|executable| executable.file_name())
876 .is_some_and(|file_name| file_name == name.as_str())
877 {
878 return true;
879 }
880 false
881 }
882 PythonRequest::Implementation(implementation) => {
883 self.matches_implementation(*implementation)
884 }
885 PythonRequest::ImplementationVersion(implementation, version) => {
886 self.matches_version_request(version)
887 && self.matches_implementation(*implementation)
888 }
889 PythonRequest::Key(request) => self.matches_download_request(request),
890 }
891 }
892}
893
894pub fn canonicalize_executable(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
897 let path = path.as_ref();
898 debug_assert!(
899 path.is_absolute(),
900 "path must be absolute: {}",
901 path.display()
902 );
903
904 #[cfg(windows)]
905 {
906 if let Ok(Some(launcher)) = uv_trampoline_builder::Launcher::try_from_path(path) {
907 Ok(dunce::canonicalize(launcher.python_path)?)
908 } else {
909 Ok(path.to_path_buf())
910 }
911 }
912
913 #[cfg(unix)]
914 fs_err::canonicalize(path)
915}
916
917#[derive(Debug, Default, Clone)]
921pub struct ExternallyManaged {
922 error: Option<String>,
923}
924
925impl ExternallyManaged {
926 pub fn into_error(self) -> Option<String> {
928 self.error
929 }
930}
931
932#[derive(Debug, Error)]
933pub struct UnexpectedResponseError {
934 #[source]
935 err: serde_json::Error,
936 stdout: String,
937 stderr: String,
938 pub path: PathBuf,
939}
940
941impl Display for UnexpectedResponseError {
942 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
943 write!(
944 f,
945 "Querying Python at `{}` returned an invalid response: {}",
946 self.path.display(),
947 self.err
948 )?;
949
950 let mut non_empty = false;
951
952 if !self.stdout.trim().is_empty() {
953 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
954 non_empty = true;
955 }
956
957 if !self.stderr.trim().is_empty() {
958 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
959 non_empty = true;
960 }
961
962 if non_empty {
963 writeln!(f)?;
964 }
965
966 Ok(())
967 }
968}
969
970#[derive(Debug, Error)]
971pub struct StatusCodeError {
972 code: ExitStatus,
973 stdout: String,
974 stderr: String,
975 pub path: PathBuf,
976}
977
978impl Display for StatusCodeError {
979 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
980 write!(
981 f,
982 "Querying Python at `{}` failed with exit status {}",
983 self.path.display(),
984 self.code
985 )?;
986
987 let mut non_empty = false;
988
989 if !self.stdout.trim().is_empty() {
990 write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
991 non_empty = true;
992 }
993
994 if !self.stderr.trim().is_empty() {
995 write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
996 non_empty = true;
997 }
998
999 if non_empty {
1000 writeln!(f)?;
1001 }
1002
1003 Ok(())
1004 }
1005}
1006
1007#[derive(Debug, Error)]
1008pub enum Error {
1009 #[error("Failed to detect CPU capabilities")]
1010 CpuDetection(#[source] CpuDetectionError),
1011 #[error("Failed to query Python interpreter")]
1012 Io(#[from] io::Error),
1013 #[error(transparent)]
1014 BrokenLink(BrokenLink),
1015 #[error("Python interpreter not found at `{0}`")]
1016 NotFound(PathBuf),
1017 #[error("Failed to query Python interpreter at `{path}`")]
1018 SpawnFailed {
1019 path: PathBuf,
1020 #[source]
1021 err: io::Error,
1022 },
1023 #[cfg(windows)]
1024 #[error("Failed to query Python interpreter at `{path}`")]
1025 CorruptWindowsPackage {
1026 path: PathBuf,
1027 #[source]
1028 err: io::Error,
1029 },
1030 #[error("Failed to query Python interpreter at `{path}`")]
1031 PermissionDenied {
1032 path: PathBuf,
1033 #[source]
1034 err: io::Error,
1035 },
1036 #[error("{0}")]
1037 UnexpectedResponse(UnexpectedResponseError),
1038 #[error("{0}")]
1039 StatusCode(StatusCodeError),
1040 #[error("Can't use Python at `{path}`")]
1041 QueryScript {
1042 #[source]
1043 err: InterpreterInfoError,
1044 path: PathBuf,
1045 },
1046 #[error("Failed to write to cache")]
1047 Encode(#[from] rmp_serde::encode::Error),
1048}
1049
1050impl uv_errors::Hinted for Error {
1051 fn hints(&self) -> uv_errors::Hints<'_> {
1052 match self {
1053 Self::BrokenLink(err) => err.hints(),
1054 _ => uv_errors::Hints::none(),
1055 }
1056 }
1057}
1058
1059#[derive(Debug, Error)]
1060pub struct BrokenLink {
1061 pub path: PathBuf,
1062 pub unix: bool,
1065 pub venv: bool,
1067}
1068
1069impl Display for BrokenLink {
1070 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1071 if self.unix {
1072 write!(
1073 f,
1074 "Broken symlink at `{}`, was the underlying Python interpreter removed?",
1075 self.path.user_display()
1076 )
1077 } else {
1078 write!(
1079 f,
1080 "Broken Python trampoline at `{}`, was the underlying Python interpreter removed?",
1081 self.path.user_display()
1082 )
1083 }
1084 }
1085}
1086
1087impl uv_errors::Hinted for BrokenLink {
1088 fn hints(&self) -> uv_errors::Hints<'_> {
1089 if self.venv {
1090 uv_errors::Hints::from(format!(
1091 "Consider recreating the environment (e.g., with `{}`)",
1092 "uv venv".green()
1093 ))
1094 } else {
1095 uv_errors::Hints::none()
1096 }
1097 }
1098}
1099
1100#[derive(Debug, Deserialize)]
1101#[serde(tag = "result", rename_all = "lowercase")]
1102enum InterpreterInfoResult {
1103 Error(InterpreterInfoError),
1104 Success(Box<InterpreterInfoWire>),
1105}
1106
1107#[derive(Debug, Deserialize)]
1109struct InterpreterInfoWire {
1110 os: uv_platform_tags::Os,
1111 file_inputs: BTreeSet<PathBuf>,
1113 arch: uv_platform_tags::Arch,
1114 cpu_info: CpuProbe,
1115 #[serde(flatten)]
1116 metadata: InterpreterMetadata,
1117}
1118
1119#[derive(Debug, Deserialize)]
1120#[serde(rename_all = "snake_case")]
1121enum CpuProbe {
1122 Detected(CpuInfo),
1124 UnsupportedArchitecture(Box<str>),
1126 Unavailable(Box<str>),
1128 Error(CpuDetectionError),
1132}
1133
1134#[derive(Debug, Deserialize, Error)]
1136#[error("{0}")]
1137pub struct CpuDetectionError(Box<str>);
1138
1139#[derive(Debug, Error, Deserialize, Serialize)]
1140#[serde(tag = "kind", rename_all = "snake_case")]
1141pub enum InterpreterInfoError {
1142 #[error("Could not detect a glibc or a musl libc (while running on Linux)")]
1143 LibcNotFound,
1144 #[error(
1145 "Broken Python installation, `platform.mac_ver()` returned an empty value, please reinstall Python"
1146 )]
1147 BrokenMacVer,
1148 #[error("Unknown operating system: `{operating_system}`")]
1149 UnknownOperatingSystem { operating_system: String },
1150 #[error("Python {python_version} is not supported. Please use Python 3.6 or newer.")]
1151 UnsupportedPythonVersion { python_version: String },
1152 #[error("Python executable does not support `-I` flag. Please use Python 3.6 or newer.")]
1153 UnsupportedPython,
1154 #[error(
1155 "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`."
1156 )]
1157 MissingRequiredDistutils {
1158 python_major: usize,
1159 python_minor: usize,
1160 },
1161 #[error("Only Pyodide is supported for Emscripten Python")]
1162 EmscriptenNotPyodide,
1163}
1164
1165#[cfg(target_os = "macos")]
1166const SYSTEM_VERSION_PLIST: &str = "/System/Library/CoreServices/SystemVersion.plist";
1167
1168#[derive(Debug, Deserialize, Serialize, Clone)]
1169struct InterpreterInfo {
1170 platform: Platform,
1171 metadata: InterpreterMetadata,
1172 file_timestamps: HashMap<PathBuf, Option<Timestamp>>,
1175}
1176
1177#[expect(clippy::struct_excessive_bools)]
1178#[derive(Debug, Deserialize, Serialize, Clone)]
1179struct InterpreterMetadata {
1180 markers: MarkerEnvironment,
1181 scheme: Scheme,
1182 virtualenv: Scheme,
1183 manylinux_compatible: bool,
1184 sys_prefix: PathBuf,
1185 sys_base_exec_prefix: PathBuf,
1186 sys_base_prefix: PathBuf,
1187 sys_base_executable: Option<PathBuf>,
1188 sys_executable: PathBuf,
1189 sys_path: Vec<PathBuf>,
1190 site_packages: Vec<PathBuf>,
1191 stdlib: PathBuf,
1192 extension_suffixes: Vec<Box<str>>,
1193 standalone: bool,
1194 pointer_size: PointerSize,
1195 gil_disabled: bool,
1196 debug_enabled: bool,
1197}
1198
1199impl InterpreterInfo {
1200 fn query(
1202 interpreter: &Path,
1203 cache: &Cache,
1204 ) -> Result<(InterpreterInfoWire, Option<Timestamp>), Error> {
1205 let tempdir = tempfile::tempdir_in(cache.root())?;
1206 Self::setup_python_query_files(tempdir.path())?;
1207
1208 let script = format!(
1216 r"import sys; sys.path = [{}] + sys.path; from python.get_interpreter_info import main; main()",
1217 tempdir.path().escape_for_python()
1218 );
1219 let mut command = Command::new(interpreter);
1220 command
1221 .arg("-I") .arg("-B") .arg("-c")
1224 .arg(script);
1225
1226 #[cfg(target_os = "macos")]
1235 command.env("SYSTEM_VERSION_COMPAT", "0");
1236
1237 let probe_start = if cfg!(unix) {
1240 Timestamp::from_path(tempdir.path()).ok()
1241 } else {
1242 None
1243 };
1244 let output = command.output().map_err(|err| {
1245 match err.kind() {
1246 io::ErrorKind::NotFound => return Error::NotFound(interpreter.to_path_buf()),
1247 io::ErrorKind::PermissionDenied => {
1248 return Error::PermissionDenied {
1249 path: interpreter.to_path_buf(),
1250 err,
1251 };
1252 }
1253 _ => {}
1254 }
1255 #[cfg(windows)]
1256 if let Some(APPMODEL_ERROR_NO_PACKAGE | ERROR_CANT_ACCESS_FILE) = err
1257 .raw_os_error()
1258 .and_then(|code| u32::try_from(code).ok())
1259 .map(WIN32_ERROR)
1260 {
1261 return Error::CorruptWindowsPackage {
1264 path: interpreter.to_path_buf(),
1265 err,
1266 };
1267 }
1268 Error::SpawnFailed {
1269 path: interpreter.to_path_buf(),
1270 err,
1271 }
1272 })?;
1273
1274 if !output.status.success() {
1275 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1276
1277 if python_home(interpreter).is_some_and(|home| !home.exists()) {
1283 return Err(Error::BrokenLink(BrokenLink {
1284 path: interpreter.to_path_buf(),
1285 unix: false,
1286 venv: uv_fs::is_virtualenv_executable(interpreter),
1287 }));
1288 }
1289
1290 if stderr.contains("Unknown option: -I") {
1292 return Err(Error::QueryScript {
1293 err: InterpreterInfoError::UnsupportedPython,
1294 path: interpreter.to_path_buf(),
1295 });
1296 }
1297
1298 return Err(Error::StatusCode(StatusCodeError {
1299 code: output.status,
1300 stderr,
1301 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1302 path: interpreter.to_path_buf(),
1303 }));
1304 }
1305
1306 let result: InterpreterInfoResult =
1307 serde_json::from_slice(&output.stdout).map_err(|err| {
1308 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1309
1310 if stderr.contains("Unknown option: -I") {
1312 Error::QueryScript {
1313 err: InterpreterInfoError::UnsupportedPython,
1314 path: interpreter.to_path_buf(),
1315 }
1316 } else {
1317 Error::UnexpectedResponse(UnexpectedResponseError {
1318 err,
1319 stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1320 stderr,
1321 path: interpreter.to_path_buf(),
1322 })
1323 }
1324 })?;
1325
1326 match result {
1327 InterpreterInfoResult::Error(err) => Err(Error::QueryScript {
1328 err,
1329 path: interpreter.to_path_buf(),
1330 }),
1331 InterpreterInfoResult::Success(data) => Ok((*data, probe_start)),
1332 }
1333 }
1334
1335 fn setup_python_query_files(root: &Path) -> Result<(), Error> {
1338 let python_dir = root.join("python");
1339 fs_err::create_dir(&python_dir)?;
1340 fs_err::write(
1341 python_dir.join("get_interpreter_info.py"),
1342 include_str!("../python/get_interpreter_info.py"),
1343 )?;
1344 fs_err::write(
1345 python_dir.join("__init__.py"),
1346 include_str!("../python/__init__.py"),
1347 )?;
1348 let packaging_dir = python_dir.join("packaging");
1349 fs_err::create_dir(&packaging_dir)?;
1350 fs_err::write(
1351 packaging_dir.join("__init__.py"),
1352 include_str!("../python/packaging/__init__.py"),
1353 )?;
1354 fs_err::write(
1355 packaging_dir.join("_elffile.py"),
1356 include_str!("../python/packaging/_elffile.py"),
1357 )?;
1358 fs_err::write(
1359 packaging_dir.join("_manylinux.py"),
1360 include_str!("../python/packaging/_manylinux.py"),
1361 )?;
1362 fs_err::write(
1363 packaging_dir.join("_musllinux.py"),
1364 include_str!("../python/packaging/_musllinux.py"),
1365 )?;
1366 Ok(())
1367 }
1368
1369 fn cache_entry(absolute: &Path, canonical: &Path, cache: &Cache) -> CacheEntry {
1371 let python_executable = env::var_os(EnvVars::PYTHONEXECUTABLE).map(PathBuf::from);
1372 let pyvenv_launcher = env::var_os(EnvVars::PYVENV_LAUNCHER).map(PathBuf::from);
1373
1374 cache.entry(
1375 CacheBucket::Interpreter,
1376 cache_digest(&(
1379 ARCH,
1380 uv_platform::OsType::from_env()
1381 .map(|os_type| os_type.to_string())
1382 .unwrap_or_default(),
1383 uv_platform::OsRelease::from_env()
1384 .map(|os_release| os_release.to_string())
1385 .unwrap_or_default(),
1386 )),
1387 format!(
1398 "{}.msgpack",
1399 cache_digest(&(absolute, canonical, &python_executable, &pyvenv_launcher))
1400 ),
1401 )
1402 }
1403
1404 fn read_cached(cache: &Cache, entry: &CacheEntry, executable: &Path) -> Option<Self> {
1406 if !cache
1407 .freshness(entry, None, None)
1408 .is_ok_and(Freshness::is_fresh)
1409 {
1410 return None;
1411 }
1412
1413 let data = fs::read(entry.path()).ok()?;
1414 let cached: Self = match rmp_serde::from_slice(&data) {
1415 Ok(cached) => cached,
1416 Err(err) => {
1417 warn!(
1418 "Broken interpreter cache entry at `{}`, removing: {err}",
1419 entry.path().user_display()
1420 );
1421 let _ = fs::remove_file(entry.path());
1422 return None;
1423 }
1424 };
1425
1426 for (path, timestamp) in &cached.file_timestamps {
1431 let unchanged = match fs::symlink_metadata(path) {
1432 Ok(metadata) => Some(Timestamp::from_metadata(&metadata)) == *timestamp,
1433 Err(err) => err.kind() == io::ErrorKind::NotFound && timestamp.is_none(),
1434 };
1435 if !unchanged {
1436 trace!(
1437 "Ignoring cached interpreter markers for {} due to changed file metadata at {}",
1438 executable.user_display(),
1439 path.user_display()
1440 );
1441 return None;
1442 }
1443 }
1444
1445 trace!(
1446 "Found cached interpreter info for Python {}, skipping query of: {}",
1447 cached.metadata.markers.python_full_version(),
1448 executable.user_display()
1449 );
1450 Some(cached)
1451 }
1452
1453 fn query_cached(
1455 executable: &Path,
1456 cache: &Cache,
1457 probe: impl FnOnce() -> Result<(InterpreterInfoWire, Option<Timestamp>), Error>,
1458 ) -> Result<Self, Error> {
1459 let absolute = std::path::absolute(executable)?;
1460
1461 let handle_io_error = |err: io::Error| -> Error {
1465 if err.kind() == io::ErrorKind::NotFound {
1466 if absolute
1469 .symlink_metadata()
1470 .is_ok_and(|metadata| metadata.is_symlink())
1471 {
1472 Error::BrokenLink(BrokenLink {
1473 path: executable.to_path_buf(),
1474 unix: true,
1475 venv: uv_fs::is_virtualenv_executable(executable),
1476 })
1477 } else {
1478 Error::NotFound(executable.to_path_buf())
1479 }
1480 } else {
1481 err.into()
1482 }
1483 };
1484
1485 let canonical = canonicalize_executable(&absolute).map_err(handle_io_error)?;
1486 let cache_entry = Self::cache_entry(&absolute, &canonical, cache);
1487 if let Some(info) = Self::read_cached(cache, &cache_entry, executable) {
1488 return Ok(info);
1489 }
1490
1491 let mut file_timestamps =
1492 Self::cache_file_timestamps(&absolute, &canonical, &BTreeSet::new())
1493 .map_err(handle_io_error)?;
1494
1495 trace!(
1496 "Querying interpreter executable at `{}`",
1497 executable.display()
1498 );
1499 let (wire, probe_start) = probe()?;
1500
1501 let cacheable = Self::determine_cacheability(
1502 executable,
1503 &absolute,
1504 &canonical,
1505 &wire,
1506 probe_start,
1507 &mut file_timestamps,
1508 );
1509
1510 let cpu_info = match wire.cpu_info {
1511 CpuProbe::Detected(info) => Some(info),
1512 CpuProbe::UnsupportedArchitecture(architecture) => {
1513 debug!("CPU detection is unsupported for architecture `{architecture}`");
1514 None
1515 }
1516 CpuProbe::Unavailable(reason) => {
1517 debug!(
1518 "CPU information unavailable for `{}`: {reason}",
1519 executable.display()
1520 );
1521 None
1522 }
1523 CpuProbe::Error(err) => {
1524 if uv_preview::is_enabled(PreviewFeature::WheelVariants) {
1525 return Err(Error::CpuDetection(err));
1526 }
1527 warn_user_once_with_chain!(
1528 anyhow::Error::from(err)
1529 .context(format!(
1530 "Failed to detect CPU capabilities for interpreter at `{}`",
1531 executable.display()
1532 ))
1533 .as_ref(),
1534 Hints::from("CPU detection failures will become errors in a future release.")
1535 );
1536 None
1540 }
1541 };
1542 let info = Self {
1543 platform: Platform::from_interpreter(wire.os, wire.arch, cpu_info),
1544 metadata: wire.metadata,
1545 file_timestamps,
1546 };
1547
1548 if cacheable {
1549 fs::create_dir_all(cache_entry.dir())?;
1550 write_atomic_sync(cache_entry.path(), rmp_serde::to_vec(&info)?)?;
1551 }
1552
1553 Ok(info)
1554 }
1555
1556 fn determine_cacheability(
1558 executable: &Path,
1559 absolute: &Path,
1560 canonical: &Path,
1561 wire: &InterpreterInfoWire,
1562 probe_start: Option<Timestamp>,
1563 file_timestamps: &mut HashMap<PathBuf, Option<Timestamp>>,
1564 ) -> bool {
1565 if !is_same_file(executable, &wire.metadata.sys_executable).unwrap_or(false) {
1567 return false;
1568 }
1569
1570 let Ok(current) = Self::cache_file_timestamps(absolute, canonical, &wire.file_inputs)
1571 else {
1572 return false;
1573 };
1574
1575 if wire.file_inputs.is_empty() {
1576 return current == *file_timestamps;
1577 }
1578 let Some(probe_start) = probe_start else {
1579 return false;
1580 };
1581
1582 let known_inputs_unchanged = file_timestamps
1585 .iter()
1586 .all(|(path, timestamp)| current.get(path) == Some(timestamp));
1587 if !known_inputs_unchanged
1588 || current
1589 .values()
1590 .flatten()
1591 .any(|timestamp| *timestamp >= probe_start)
1592 {
1593 return false;
1594 }
1595
1596 *file_timestamps = current;
1597 true
1598 }
1599
1600 fn cache_file_timestamps(
1602 absolute: &Path,
1603 canonical: &Path,
1604 file_inputs: &BTreeSet<PathBuf>,
1605 ) -> Result<HashMap<PathBuf, Option<Timestamp>>, io::Error> {
1606 let mut file_timestamps = HashMap::new();
1607 record_file_timestamps(absolute, &mut file_timestamps)?;
1608 if !file_timestamps.contains_key(canonical) {
1609 record_file_timestamps(canonical, &mut file_timestamps)?;
1611 }
1612 for path in file_inputs {
1613 record_file_timestamps(path, &mut file_timestamps)?;
1614 }
1615 #[cfg(target_os = "macos")]
1618 record_file_timestamps(Path::new(SYSTEM_VERSION_PLIST), &mut file_timestamps)?;
1619 record_pyvenv_cfg_timestamps(absolute, &mut file_timestamps)?;
1620 Ok(file_timestamps)
1621 }
1622}
1623
1624fn record_pyvenv_cfg_timestamps(
1632 executable: &Path,
1633 timestamps: &mut HashMap<PathBuf, Option<Timestamp>>,
1634) -> io::Result<()> {
1635 let launcher_paths = [EnvVars::PYTHONEXECUTABLE, EnvVars::PYVENV_LAUNCHER]
1636 .into_iter()
1637 .filter_map(env::var_os)
1638 .filter(|path| !path.is_empty())
1639 .map(std::path::absolute)
1640 .collect::<io::Result<Vec<_>>>()?;
1641 for executable in std::iter::once(executable).chain(launcher_paths.iter().map(PathBuf::as_path))
1644 {
1645 let parent_directories = executable.ancestors().skip(1);
1646 for directory in parent_directories.take(2) {
1647 let path = directory.join("pyvenv.cfg");
1648 match record_file_timestamps(&path, timestamps) {
1649 Ok(()) => {}
1650 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
1651 Err(err) => return Err(err),
1652 }
1653 }
1654 }
1655 Ok(())
1656}
1657
1658fn record_file_timestamps(
1660 path: &Path,
1661 timestamps: &mut HashMap<PathBuf, Option<Timestamp>>,
1662) -> io::Result<()> {
1663 if !path.is_absolute() {
1664 return Err(io::Error::new(
1665 io::ErrorKind::InvalidInput,
1666 "Expected an absolute path for an interpreter file input",
1667 ));
1668 }
1669
1670 let mut path = Cow::Borrowed(path);
1671 for _ in 0..=40 {
1673 let metadata = match fs::symlink_metadata(path.as_ref()) {
1674 Ok(metadata) => metadata,
1675 Err(err) => {
1676 if err.kind() == io::ErrorKind::NotFound {
1677 timestamps.insert(path.as_ref().to_path_buf(), None);
1678 }
1679 return Err(err);
1680 }
1681 };
1682 timestamps.insert(
1683 path.as_ref().to_path_buf(),
1684 Some(Timestamp::from_metadata(&metadata)),
1685 );
1686 if !metadata.is_symlink() {
1687 return Ok(());
1688 }
1689 let target = fs::read_link(path.as_ref())?;
1690 path.to_mut().set_file_name(target);
1691 }
1692 Err(io::Error::other(
1693 "Too many symlinks for an interpreter file input",
1694 ))
1695}
1696
1697fn find_base_python(
1723 executable: &Path,
1724 major: u8,
1725 minor: u8,
1726 suffix: &str,
1727) -> Result<PathBuf, io::Error> {
1728 fn is_root(path: &Path) -> bool {
1730 let mut components = path.components();
1731 components.next() == Some(std::path::Component::RootDir) && components.next().is_none()
1732 }
1733
1734 fn is_prefix(dir: &Path, major: u8, minor: u8, suffix: &str) -> bool {
1738 if cfg!(windows) {
1739 dir.join("Lib").join("os.py").is_file()
1740 } else {
1741 dir.join("lib")
1742 .join(format!("python{major}.{minor}{suffix}"))
1743 .join("os.py")
1744 .is_file()
1745 }
1746 }
1747
1748 let mut executable = Cow::Borrowed(executable);
1749
1750 loop {
1751 debug!(
1752 "Assessing Python executable as base candidate: {}",
1753 executable.display()
1754 );
1755
1756 for prefix in executable.ancestors().take_while(|path| !is_root(path)) {
1758 if is_prefix(prefix, major, minor, suffix) {
1759 return Ok(executable.into_owned());
1760 }
1761 }
1762
1763 let resolved = fs_err::read_link(&executable)?;
1765
1766 let resolved = if resolved.is_relative() {
1768 if let Some(parent) = executable.parent() {
1769 parent.join(resolved)
1770 } else {
1771 return Err(io::Error::other("Symlink has no parent directory"));
1772 }
1773 } else {
1774 resolved
1775 };
1776
1777 let resolved = uv_fs::normalize_absolute_path(&resolved)?;
1779
1780 executable = Cow::Owned(resolved);
1781 }
1782}
1783
1784fn python_home(interpreter: &Path) -> Option<PathBuf> {
1786 let venv_root = interpreter.parent()?.parent()?;
1787 let pyvenv_cfg = PyVenvConfiguration::parse(venv_root.join("pyvenv.cfg")).ok()?;
1788 pyvenv_cfg.home
1789}
1790
1791#[cfg(unix)]
1792#[cfg(test)]
1793mod tests {
1794 use std::io;
1795 use std::path::Path;
1796 use std::str::FromStr;
1797 use std::time::{Duration, UNIX_EPOCH};
1798
1799 use anyhow::Result;
1800 use fs_err as fs;
1801 use indoc::indoc;
1802 use tempfile::tempdir;
1803
1804 use uv_cache::{Cache, CacheBucket};
1805 use uv_cache_info::Timestamp;
1806 use uv_pep440::Version;
1807 use uv_platform_tags::CpuInfo;
1808
1809 use crate::Interpreter;
1810 use crate::interpreter::{
1811 Error, InterpreterInfo, InterpreterInfoResult, InterpreterInfoWire, canonicalize_executable,
1812 };
1813
1814 fn mocked_interpreter_response(executable: &Path) -> Result<InterpreterInfoWire> {
1815 let InterpreterInfoResult::Success(mut response) = serde_json::from_str(indoc! {r##"
1816 {
1817 "result": "success",
1818 "file_inputs": [],
1819 "os": {
1820 "name": "manylinux",
1821 "major": 2,
1822 "minor": 38
1823 },
1824 "arch": "x86_64",
1825 "cpu_info": { "detected": { "kind": "flags", "flags": "pni ssse3" } },
1826 "manylinux_compatible": false,
1827 "standalone": false,
1828 "markers": {
1829 "implementation_name": "cpython",
1830 "implementation_version": "3.12.0",
1831 "os_name": "posix",
1832 "platform_machine": "x86_64",
1833 "platform_python_implementation": "CPython",
1834 "platform_release": "6.5.0-13-generic",
1835 "platform_system": "Linux",
1836 "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov 3 12:16:05 UTC 2023",
1837 "python_full_version": "3.12.0",
1838 "python_version": "3.12",
1839 "sys_platform": "linux"
1840 },
1841 "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1842 "sys_base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1843 "sys_prefix": "/home/ferris/projects/uv/.venv",
1844 "sys_executable": "",
1845 "sys_path": [
1846 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/lib/python3.12",
1847 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1848 ],
1849 "site_packages": [
1850 "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1851 ],
1852 "stdlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12",
1853 "extension_suffixes": [".cpython-312-x86_64-linux-gnu.so", ".abi3.so", ".so"],
1854 "scheme": {
1855 "data": "/home/ferris/.pyenv/versions/3.12.0",
1856 "include": "/home/ferris/.pyenv/versions/3.12.0/include",
1857 "platlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1858 "purelib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1859 "scripts": "/home/ferris/.pyenv/versions/3.12.0/bin"
1860 },
1861 "virtualenv": {
1862 "data": "",
1863 "include": "include",
1864 "platlib": "lib/python3.12/site-packages",
1865 "purelib": "lib/python3.12/site-packages",
1866 "scripts": "bin"
1867 },
1868 "pointer_size": "64",
1869 "gil_disabled": true,
1870 "debug_enabled": false
1871 }
1872 "##})?
1873 else {
1874 anyhow::bail!("expected a successful interpreter response");
1875 };
1876 response.metadata.sys_executable = executable.to_path_buf();
1877 Ok(*response)
1878 }
1879
1880 fn unexpected_probe() -> Result<(InterpreterInfoWire, Option<Timestamp>), Error> {
1881 Err(io::Error::other("expected an interpreter cache hit").into())
1882 }
1883
1884 #[tokio::test]
1885 async fn test_cache_invalidation() -> Result<()> {
1886 let mock_dir = tempdir()?;
1887 let mocked_interpreter = mock_dir.path().join("python");
1888 fs::write(&mocked_interpreter, [])?;
1889
1890 let cache = Cache::temp()?.init().await?;
1891 let original_version = Version::from_str("3.12")?;
1892 let updated_version = Version::from_str("3.13")?;
1893 let response = mocked_interpreter_response(&mocked_interpreter)?;
1894
1895 let interpreter =
1896 InterpreterInfo::query_cached(&mocked_interpreter, &cache, || Ok((response, None)))?;
1897 assert_eq!(
1898 interpreter.metadata.markers.python_version().version,
1899 original_version
1900 );
1901 assert!(cache.bucket(CacheBucket::Interpreter).is_dir());
1902
1903 let interpreter =
1904 InterpreterInfo::query_cached(&mocked_interpreter, &cache, unexpected_probe)?;
1905 let Some(CpuInfo::Flags { flags }) = interpreter.platform.cpu_info() else {
1906 anyhow::bail!("CPU flags missing from cached platform");
1907 };
1908 assert_eq!(flags.as_ref(), "pni ssse3");
1909 assert_eq!(
1910 interpreter.metadata.markers.python_version().version,
1911 original_version
1912 );
1913
1914 let absolute = std::path::absolute(&mocked_interpreter)?;
1915 let canonical = canonicalize_executable(&absolute)?;
1916 let cache_entry = InterpreterInfo::cache_entry(&absolute, &canonical, &cache);
1917 let mut cached: InterpreterInfo = rmp_serde::from_slice(&fs::read(cache_entry.path())?)?;
1918 assert_eq!(
1919 cached.file_timestamps.get(&canonical),
1920 Some(&Some(Timestamp::from_path(&canonical)?))
1921 );
1922
1923 fs::write(&mocked_interpreter, b"updated")?;
1924 let mut response = mocked_interpreter_response(&mocked_interpreter)?;
1925 let updated_full_version = Version::from_str("3.13.0")?;
1926 response.metadata.markers = response
1927 .metadata
1928 .markers
1929 .with_implementation_version(updated_full_version.clone())
1930 .with_python_full_version(updated_full_version)
1931 .with_python_version(updated_version.clone());
1932
1933 let modified = Timestamp::from_path(&canonical)?;
1936 let stale = if modified == Timestamp::from(UNIX_EPOCH) {
1937 Timestamp::from(UNIX_EPOCH + Duration::from_secs(1))
1938 } else {
1939 Timestamp::from(UNIX_EPOCH)
1940 };
1941 cached
1942 .file_timestamps
1943 .insert(canonical.clone(), Some(stale));
1944 fs::write(cache_entry.path(), rmp_serde::to_vec(&cached)?)?;
1945
1946 let interpreter =
1947 InterpreterInfo::query_cached(&mocked_interpreter, &cache, || Ok((response, None)))?;
1948 assert_eq!(
1949 interpreter.metadata.markers.python_version().version,
1950 updated_version
1951 );
1952 assert_eq!(
1953 interpreter.file_timestamps.get(&canonical),
1954 Some(&Some(Timestamp::from_path(&canonical)?))
1955 );
1956
1957 let interpreter =
1958 InterpreterInfo::query_cached(&mocked_interpreter, &cache, unexpected_probe)?;
1959 assert_eq!(
1960 interpreter.metadata.markers.python_version().version,
1961 updated_version
1962 );
1963
1964 Ok(())
1965 }
1966
1967 #[tokio::test]
1968 async fn test_cache_eviction_with_unchanged_executable() -> Result<()> {
1969 let mock_dir = tempdir()?;
1970 let mocked_interpreter = mock_dir.path().join("python");
1971 fs::write(&mocked_interpreter, [])?;
1972
1973 let cache = Cache::temp()?.init().await?;
1974 let original_version = Version::from_str("3.12.0")?;
1975 let updated_version = Version::from_str("3.12.13")?;
1976 let response = mocked_interpreter_response(&mocked_interpreter)?;
1977
1978 let interpreter =
1979 InterpreterInfo::query_cached(&mocked_interpreter, &cache, || Ok((response, None)))?;
1980 assert_eq!(
1981 interpreter.metadata.markers.python_full_version().version,
1982 original_version
1983 );
1984 let interpreter =
1985 InterpreterInfo::query_cached(&mocked_interpreter, &cache, unexpected_probe)?;
1986 assert_eq!(
1987 interpreter.metadata.markers.python_full_version().version,
1988 original_version
1989 );
1990
1991 Interpreter::clear_cache(&mocked_interpreter, &cache)?;
1992 let mut response = mocked_interpreter_response(&mocked_interpreter)?;
1993 response.metadata.markers = response
1994 .metadata
1995 .markers
1996 .with_implementation_version(updated_version.clone())
1997 .with_python_full_version(updated_version.clone());
1998
1999 let interpreter =
2000 InterpreterInfo::query_cached(&mocked_interpreter, &cache, || Ok((response, None)))?;
2001 assert_eq!(
2002 interpreter.metadata.markers.python_full_version().version,
2003 updated_version
2004 );
2005 let interpreter =
2006 InterpreterInfo::query_cached(&mocked_interpreter, &cache, unexpected_probe)?;
2007 assert_eq!(
2008 interpreter.metadata.markers.python_full_version().version,
2009 updated_version
2010 );
2011
2012 Ok(())
2013 }
2014}