1use itertools::{Either, Itertools};
2use rayon::iter::{IntoParallelIterator, ParallelIterator};
3use regex::Regex;
4use rustc_hash::{FxBuildHasher, FxHashSet};
5use std::cmp::Reverse;
6use std::env::consts::EXE_SUFFIX;
7use std::fmt::{self, Debug, Formatter};
8use std::{env, io, iter};
9use std::{path::Path, path::PathBuf};
10use thiserror::Error;
11use tracing::{debug, instrument, trace};
12use uv_cache::Cache;
13use uv_client::BaseClientBuilder;
14use uv_fs::Simplified;
15use uv_fs::which::is_executable;
16use uv_macros::DebugNoInline;
17use uv_platform::Platform;
18use uv_python_types::{
19 EnvironmentPreference, PythonPreference, PythonRequest, PythonRequestError, PythonSource,
20 VersionRequest,
21};
22use uv_static::EnvVars;
23use uv_warnings::{warn_user_once, warn_user_with_chain};
24use which::which_all;
25
26use crate::installation::PythonInstallation;
27#[cfg(windows)]
28use crate::microsoft_store::find_microsoft_store_pythons;
29use crate::virtualenv_discovery::CondaEnvironmentKind;
30use crate::virtualenv_discovery::conda_environment_from_env;
31use crate::virtualenv_discovery::virtualenv_from_env;
32use crate::virtualenv_discovery::virtualenv_from_working_dir;
33#[cfg(windows)]
34use crate::windows_registry::{WindowsPython, registry_pythons};
35use uv_python_interpreter::{
36 BrokenLink, Interpreter, InterpreterError, StatusCodeError, UnexpectedResponseError,
37 VirtualEnvError, virtualenv_python_executable,
38};
39use uv_python_managed::ManagedPythonInstallations;
40use uv_python_managed::PythonMinorVersionLink;
41use uv_python_managed::downloads::ManagedPythonDownloadList;
42use uv_python_types::{
43 ArchRequest, ImplementationName, PlatformRequest, PythonArchitecture, PythonDownloadMirrors,
44 PythonDownloadRequest, python_build_versions_from_env,
45};
46
47#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub(crate) struct DiscoveryPreferences {
49 python_preference: PythonPreference,
50 environment_preference: EnvironmentPreference,
51}
52
53type FindPythonResult = Result<PythonInstallation, PythonNotFound>;
57
58#[derive(Clone, Debug, Error)]
60pub struct PythonNotFound {
61 pub(super) request: PythonRequest,
62 pub(super) python_preference: PythonPreference,
63 pub(super) environment_preference: EnvironmentPreference,
64}
65
66struct PythonExecutableGroup(Vec<(PythonSource, PathBuf)>);
71
72impl PythonExecutableGroup {
73 fn new(executables: Vec<(PythonSource, PathBuf)>) -> Option<Self> {
74 (!executables.is_empty()).then_some(Self(executables))
75 }
76
77 fn filter(mut self, mut predicate: impl FnMut(PythonSource, &Path) -> bool) -> Option<Self> {
78 self.0.retain(|(source, path)| predicate(*source, path));
79 (!self.0.is_empty()).then_some(self)
80 }
81}
82
83#[derive(Error, DebugNoInline)]
84pub enum Error {
85 #[error(transparent)]
86 Io(#[from] io::Error),
87
88 #[error("Failed to inspect Python interpreter from {} at `{}` ", _2, _1.user_display())]
90 Query(
91 #[source] Box<uv_python_interpreter::InterpreterError>,
92 PathBuf,
93 PythonSource,
94 ),
95
96 #[error("Failed to discover managed Python installations")]
99 ManagedPython(#[from] uv_python_managed::Error),
100
101 #[error(transparent)]
103 VirtualEnv(#[from] uv_python_interpreter::VirtualEnvError),
104
105 #[cfg(windows)]
106 #[error("Failed to query installed Python versions from the Windows registry")]
107 RegistryError(#[from] windows::core::Error),
108
109 #[error(transparent)]
110 InvalidEnvironmentVariable(#[from] uv_static::InvalidEnvironmentVariable),
111
112 #[error("Invalid version request: {0}")]
114 InvalidVersionRequest(String),
115
116 #[error("Requesting the 'latest' Python version is not yet supported")]
118 LatestVersionRequest,
119
120 #[error("Interpreter discovery for `{0}` requires `{1}` but only `{2}` is allowed")]
122 SourceNotAllowed(PythonRequest, PythonSource, PythonPreference),
123
124 #[error(transparent)]
125 BuildVersion(#[from] uv_python_types::BuildVersionError),
126}
127
128impl From<PythonRequestError> for Error {
129 fn from(error: PythonRequestError) -> Self {
130 match error {
131 PythonRequestError::InvalidVersionRequest(value) => Self::InvalidVersionRequest(value),
132 PythonRequestError::LatestVersionRequest => Self::LatestVersionRequest,
133 }
134 }
135}
136
137impl uv_errors::Hinted for Error {
138 fn hints(&self) -> uv_errors::Hints<'_> {
139 match self {
140 Self::Query(err, _, _) => err.hints(),
141 _ => uv_errors::Hints::none(),
142 }
143 }
144}
145
146fn python_executables_from_virtual_environments<'a>()
155-> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a {
156 let from_active_environment = iter::once_with(|| {
157 virtualenv_from_env()
158 .into_iter()
159 .map(virtualenv_python_executable)
160 .map(|path| Ok((PythonSource::ActiveEnvironment, path)))
161 })
162 .flatten();
163
164 let from_conda_environment = iter::once_with(move || {
166 conda_environment_from_env(CondaEnvironmentKind::Child)
167 .into_iter()
168 .map(virtualenv_python_executable)
169 .map(|path| Ok((PythonSource::CondaPrefix, path)))
170 })
171 .flatten();
172
173 let from_discovered_environment = iter::once_with(|| {
174 virtualenv_from_working_dir()
175 .map(|path| {
176 path.map(virtualenv_python_executable)
177 .map(|path| (PythonSource::DiscoveredEnvironment, path))
178 .into_iter()
179 })
180 .map_err(Error::from)
181 })
182 .flatten_ok();
183
184 from_active_environment
185 .chain(from_conda_environment)
186 .chain(from_discovered_environment)
187}
188
189fn python_executables_from_installed<'a>(
208 version: &'a VersionRequest,
209 implementation: Option<&'a ImplementationName>,
210 platform: PlatformRequest,
211 preference: PythonPreference,
212) -> Box<dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a> {
213 let from_managed_installations = iter::once_with(move || {
214 ManagedPythonInstallations::from_settings(None)
215 .map_err(Error::from)
216 .and_then(|installed_installations| {
217 debug!(
218 "Searching for managed installations at `{}`",
219 installed_installations.root().user_display()
220 );
221 let installations = ManagedPythonInstallations::find_matching_current_platform()?;
222
223 let build_versions = python_build_versions_from_env()?;
224
225 Ok(installations
228 .into_iter()
229 .filter(move |installation| {
230 if !version.matches_version(&installation.version()) {
231 debug!("Skipping managed installation `{installation}`: does not satisfy `{version}`");
232 return false;
233 }
234 if !platform.matches(installation.platform()) {
235 debug!("Skipping managed installation `{installation}`: does not satisfy requested platform `{platform}`");
236 return false;
237 }
238
239 if let Some(requested_build) = build_versions.get(&installation.implementation()) {
240 let Some(installation_build) = installation.build() else {
241 debug!(
242 "Skipping managed installation `{installation}`: a build version was requested but is not recorded for this installation"
243 );
244 return false;
245 };
246 if installation_build != requested_build {
247 debug!(
248 "Skipping managed installation `{installation}`: requested build version `{requested_build}` does not match installation build version `{installation_build}`"
249 );
250 return false;
251 }
252 }
253
254 true
255 })
256 .inspect(|installation| debug!("Found managed installation `{installation}`"))
257 .map(move |installation| {
258 let executable = version
261 .patch()
262 .is_none()
263 .then(|| {
264 PythonMinorVersionLink::from_installation(&installation)
265 .filter(PythonMinorVersionLink::exists)
266 .map(
267 |minor_version_link| {
268 minor_version_link.symlink_executable.clone()
269 },
270 )
271 })
272 .flatten()
273 .unwrap_or_else(|| installation.executable(false));
274 (PythonSource::Managed, executable)
275 })
276 )
277 })
278 })
279 .flatten_ok()
280 .map_ok(|executable| PythonExecutableGroup(vec![executable]));
281
282 let from_search_path = iter::once_with(move || {
283 let mut first = true;
284 python_executables_from_search_path(version, implementation).filter_map(move |paths| {
285 let executables = paths
286 .into_iter()
287 .map(|path| {
288 let source = if first {
289 first = false;
290 PythonSource::SearchPathFirst
291 } else {
292 PythonSource::SearchPath
293 };
294 (source, path)
295 })
296 .collect();
297 PythonExecutableGroup::new(executables).map(Ok)
298 })
299 })
300 .flatten();
301
302 #[cfg(windows)]
303 let from_windows_registry: Box<
304 dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
305 > = match uv_static::parse_boolish_environment_variable(EnvVars::UV_PYTHON_NO_REGISTRY) {
306 Ok(Some(true)) => Box::new(iter::empty()),
307 Ok(Some(false) | None) => Box::new(
308 iter::once_with(move || {
309 let version_filter = move |entry: &WindowsPython| {
311 if let Some(found) = &entry.version {
312 if found.string.chars().filter(|c| *c == '.').count() == 1 {
314 version.matches_major_minor(found.major(), found.minor())
315 } else {
316 version.matches_version(found)
317 }
318 } else {
319 true
320 }
321 };
322
323 registry_pythons()
324 .map(|entries| {
325 entries
326 .into_iter()
327 .filter(version_filter)
328 .map(|entry| (PythonSource::Registry, entry.path))
329 .chain(
330 find_microsoft_store_pythons()
331 .filter(version_filter)
332 .map(|entry| (PythonSource::MicrosoftStore, entry.path)),
333 )
334 })
335 .map_err(Error::from)
336 })
337 .flatten_ok()
338 .map_ok(|executable| PythonExecutableGroup(vec![executable])),
339 ),
340 Err(err) => Box::new(iter::once(Err(Error::from(err)))),
341 };
342
343 #[cfg(not(windows))]
344 let from_windows_registry: Box<
345 dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
346 > = Box::new(iter::empty());
347
348 match preference {
349 PythonPreference::OnlyManaged => {
350 if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok() {
354 Box::new(from_managed_installations.chain(from_search_path))
355 } else {
356 Box::new(from_managed_installations)
357 }
358 }
359 PythonPreference::Managed => Box::new(
360 from_managed_installations
361 .chain(from_search_path)
362 .chain(from_windows_registry),
363 ),
364 PythonPreference::System => Box::new(
365 from_search_path
366 .chain(from_windows_registry)
367 .chain(from_managed_installations),
368 ),
369 PythonPreference::OnlySystem => Box::new(from_search_path.chain(from_windows_registry)),
370 }
371}
372
373fn python_executables<'a>(
383 version: &'a VersionRequest,
384 implementation: Option<&'a ImplementationName>,
385 platform: PlatformRequest,
386 environments: EnvironmentPreference,
387 preference: PythonPreference,
388) -> Box<dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a> {
389 let from_parent_interpreter = iter::once_with(|| {
391 env::var_os(EnvVars::UV_INTERNAL__PARENT_INTERPRETER)
392 .into_iter()
393 .map(|path| {
394 Ok(PythonExecutableGroup(vec![(
395 PythonSource::ParentInterpreter,
396 PathBuf::from(path),
397 )]))
398 })
399 })
400 .flatten();
401
402 let from_base_conda_environment = iter::once_with(move || {
404 conda_environment_from_env(CondaEnvironmentKind::Base)
405 .into_iter()
406 .map(virtualenv_python_executable)
407 .map(|path| {
408 Ok(PythonExecutableGroup(vec![(
409 PythonSource::BaseCondaPrefix,
410 path,
411 )]))
412 })
413 })
414 .flatten();
415
416 let from_virtual_environments = python_executables_from_virtual_environments()
417 .map_ok(|executable| PythonExecutableGroup(vec![executable]));
418 let from_installed =
419 python_executables_from_installed(version, implementation, platform, preference);
420
421 match environments {
425 EnvironmentPreference::OnlyVirtual => {
426 Box::new(from_parent_interpreter.chain(from_virtual_environments))
427 }
428 EnvironmentPreference::ExplicitSystem | EnvironmentPreference::Any => Box::new(
429 from_parent_interpreter
430 .chain(from_virtual_environments)
431 .chain(from_base_conda_environment)
432 .chain(from_installed),
433 ),
434 EnvironmentPreference::OnlySystem => Box::new(
435 from_parent_interpreter
436 .chain(from_base_conda_environment)
437 .chain(from_installed),
438 ),
439 }
440}
441
442fn python_executables_from_search_path<'a>(
470 version: &'a VersionRequest,
471 implementation: Option<&'a ImplementationName>,
472) -> impl Iterator<Item = Vec<PathBuf>> + 'a {
473 let search_path = env::var_os(EnvVars::UV_PYTHON_SEARCH_PATH)
475 .unwrap_or(env::var_os(EnvVars::PATH).unwrap_or_default());
476
477 let possible_names: Vec<_> = version
478 .executable_names(implementation)
479 .into_iter()
480 .map(|name| name.to_string())
481 .collect();
482
483 trace!(
484 "Searching PATH for executables: {}",
485 possible_names.join(", ")
486 );
487
488 let search_dirs: Vec<_> = env::split_paths(&search_path).collect();
492 let mut seen_dirs = FxHashSet::with_capacity_and_hasher(search_dirs.len(), FxBuildHasher);
493 search_dirs
494 .into_iter()
495 .filter(|dir| dir.is_dir())
496 .flat_map(move |dir| {
497 let dir_clone = dir.clone();
499 trace!(
500 "Checking `PATH` directory for interpreters: {}",
501 dir.display()
502 );
503 same_file::Handle::from_path(&dir)
504 .map(|handle| seen_dirs.insert(handle))
507 .inspect(|fresh_dir| {
508 if !fresh_dir {
509 trace!("Skipping already seen directory: {}", dir.display());
510 }
511 })
512 .unwrap_or(true)
514 .then(|| {
515 let minor_version_directory = dir_clone.clone();
516
517 possible_names
518 .clone()
519 .into_iter()
520 .flat_map(move |name| {
521 which::which_in_global(&*name, Some(&dir))
523 .into_iter()
524 .flatten()
525 .filter(|path| !is_windows_store_shim(path))
526 .map(|path| vec![path])
527 .collect::<Vec<_>>()
530 })
531 .chain(
532 iter::once_with(move || {
533 find_all_minor(implementation, version, &minor_version_directory)
534 .filter(|path| !is_windows_store_shim(path))
535 .collect::<Vec<_>>()
536 })
537 .filter(|paths| !paths.is_empty()),
538 )
539 .inspect(|paths| {
540 for path in paths {
541 trace!("Found possible Python executable: {}", path.display());
542 }
543 })
544 .chain(
545 cfg!(windows)
547 .then(move || {
548 which::which_in_global("python.bat", Some(&dir_clone))
549 .into_iter()
550 .flatten()
551 .map(|path| vec![path])
552 .collect::<Vec<_>>()
553 })
554 .into_iter()
555 .flatten(),
556 )
557 })
558 .into_iter()
559 .flatten()
560 })
561}
562
563fn find_all_minor(
568 implementation: Option<&ImplementationName>,
569 version_request: &VersionRequest,
570 dir: &Path,
571) -> impl Iterator<Item = PathBuf> + use<> {
572 match version_request {
573 &VersionRequest::Any
574 | VersionRequest::Default
575 | VersionRequest::Major(_, _)
576 | VersionRequest::Range(_, _) => {
577 let regex = if let Some(implementation) = implementation {
578 Regex::new(&format!(
579 r"^({}|python3)\.(?<minor>\d\d?)t?{}$",
580 regex::escape(&implementation.to_string()),
581 regex::escape(EXE_SUFFIX)
582 ))
583 .unwrap()
584 } else {
585 Regex::new(&format!(
586 r"^python3\.(?<minor>\d\d?)t?{}$",
587 regex::escape(EXE_SUFFIX)
588 ))
589 .unwrap()
590 };
591 let all_minors = fs_err::read_dir(dir)
592 .into_iter()
593 .flatten()
594 .flatten()
595 .map(|entry| entry.path())
596 .filter(move |path| {
597 let Some(filename) = path.file_name() else {
598 return false;
599 };
600 let Some(filename) = filename.to_str() else {
601 return false;
602 };
603 let Some(captures) = regex.captures(filename) else {
604 return false;
605 };
606
607 let minor = captures["minor"].parse().ok();
609 if let Some(minor) = minor {
610 if minor < 6 {
612 return false;
613 }
614 if !version_request.matches_major_minor(3, minor) {
616 return false;
617 }
618 }
619 true
620 })
621 .filter(|path| is_executable(path))
622 .collect::<Vec<_>>();
623 Either::Left(all_minors.into_iter())
624 }
625 VersionRequest::MajorMinor(_, _, _)
626 | VersionRequest::MajorMinorPatch(_, _, _, _)
627 | VersionRequest::MajorMinorPrerelease(_, _, _, _)
628 | VersionRequest::MajorMinorPatchPrerelease(_, _, _, _, _) => Either::Right(iter::empty()),
629 }
630}
631
632#[derive(Debug, Clone, Copy)]
634enum QueryStrategy {
635 Sequential,
637 Parallel,
639}
640
641fn python_installations<'a>(
651 version: &'a VersionRequest,
652 implementation: Option<&'a ImplementationName>,
653 platform: PlatformRequest,
654 environments: EnvironmentPreference,
655 preference: PythonPreference,
656 cache: &'a Cache,
657 strategy: QueryStrategy,
658) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
659 Box::new(
660 python_installations_from_executables(
661 python_executables(version, implementation, platform, environments, preference)
665 .filter_map(move |result| match result {
666 Ok(group) => group
667 .filter(|source, path| {
668 source_satisfies_environment_preference(source, path, environments)
669 })
670 .map(Ok),
671 Err(error) => Some(Err(error)),
672 }),
673 cache,
674 strategy,
675 )
676 .filter_ok(move |installation| {
677 installation.satisfies_preferences(version, environments, preference)
678 && platform.matches(&Platform::from(installation.interpreter.platform()))
679 })
680 .map_ok(PythonInstallation::maybe_with_test_source),
681 )
682}
683
684fn python_installation_from_executable(
686 source: PythonSource,
687 path: PathBuf,
688 cache: &Cache,
689) -> Result<PythonInstallation, Error> {
690 Interpreter::query(&path, cache)
691 .map(|interpreter| PythonInstallation {
692 source,
693 interpreter,
694 })
695 .inspect(|installation| {
696 debug!(
697 "Found `{}` at `{}` ({source})",
698 installation.key(),
699 path.display()
700 );
701 })
702 .map_err(|err| Error::Query(Box::new(err), path, source))
703 .inspect_err(|err| debug!("{err}"))
704}
705
706fn python_installations_from_executables<'a>(
708 executables: impl Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
709 cache: &'a Cache,
710 strategy: QueryStrategy,
711) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
712 match strategy {
713 QueryStrategy::Sequential => Box::new(executables.flat_map(move |group| {
714 python_installations_from_executable_group(group, cache, strategy)
715 })),
716 QueryStrategy::Parallel => {
717 let items: Vec<Result<PythonExecutableGroup, Error>> = executables.collect();
718 let results: Vec<Vec<Result<PythonInstallation, Error>>> = items
719 .into_par_iter()
720 .map(|group| {
721 python_installations_from_executable_group(group, cache, strategy)
722 .collect::<Vec<_>>()
723 })
724 .collect();
725 Box::new(results.into_iter().flatten())
726 }
727 }
728}
729
730fn python_installations_from_executable_group(
732 group: Result<PythonExecutableGroup, Error>,
733 cache: &Cache,
734 strategy: QueryStrategy,
735) -> impl Iterator<Item = Result<PythonInstallation, Error>> + use<> {
736 match group {
737 Err(error) => Either::Left(iter::once(Err(error))),
738 Ok(PythonExecutableGroup(executables)) => {
739 let mut installations = match strategy {
740 QueryStrategy::Sequential => executables
741 .into_iter()
742 .map(|(source, path)| python_installation_from_executable(source, path, cache))
743 .collect::<Vec<_>>(),
744 QueryStrategy::Parallel => executables
745 .into_par_iter()
746 .map(|(source, path)| python_installation_from_executable(source, path, cache))
747 .collect::<Vec<_>>(),
748 };
749
750 sort_installations_by_key(&mut installations, PythonInstallation::key);
751
752 Either::Right(installations.into_iter())
753 }
754 }
755}
756
757fn sort_installations_by_key<T, K: Ord>(
759 installations: &mut [Result<T, Error>],
760 key: impl Fn(&T) -> K,
761) {
762 for candidates in
765 installations.split_mut(|result| result.as_ref().is_err_and(Error::is_critical))
766 {
767 candidates.sort_by_key(|result| Reverse(result.as_ref().ok().map(&key)));
768 }
769}
770
771fn source_satisfies_environment_preference(
778 source: PythonSource,
779 interpreter_path: &Path,
780 preference: EnvironmentPreference,
781) -> bool {
782 match preference {
783 EnvironmentPreference::Any => true,
784 EnvironmentPreference::OnlyVirtual => {
785 if source.is_maybe_virtualenv() {
786 true
787 } else {
788 debug!(
789 "Ignoring Python interpreter at `{}`: only virtual environments allowed",
790 interpreter_path.display()
791 );
792 false
793 }
794 }
795 EnvironmentPreference::ExplicitSystem => {
796 if source.is_maybe_virtualenv() {
797 true
798 } else {
799 debug!(
800 "Ignoring Python interpreter at `{}`: system interpreter not explicitly requested",
801 interpreter_path.display()
802 );
803 false
804 }
805 }
806 EnvironmentPreference::OnlySystem => {
807 if source.is_maybe_system() {
808 true
809 } else {
810 debug!(
811 "Ignoring Python interpreter at `{}`: system interpreter required",
812 interpreter_path.display()
813 );
814 false
815 }
816 }
817 }
818}
819
820impl Error {
824 pub(crate) fn is_critical(&self) -> bool {
825 match self {
826 Self::Query(err, _, source) => match &**err {
829 InterpreterError::Encode(_)
830 | InterpreterError::Io(_)
831 | InterpreterError::SpawnFailed { .. } => true,
832 InterpreterError::UnexpectedResponse(UnexpectedResponseError { path, .. })
833 | InterpreterError::StatusCode(StatusCodeError { path, .. }) => {
834 debug!(
835 "Skipping bad interpreter at `{}` from {source}: {err}",
836 path.display()
837 );
838 false
839 }
840 InterpreterError::QueryScript { path, err } => {
841 debug!(
842 "Skipping bad interpreter at `{}` from {source}: {err}",
843 path.display()
844 );
845 false
846 }
847 #[cfg(windows)]
848 InterpreterError::CorruptWindowsPackage { path, err } => {
849 debug!(
850 "Skipping bad interpreter at `{}` from {source}: {err}",
851 path.display()
852 );
853 false
854 }
855 InterpreterError::PermissionDenied { path, err } => {
856 debug!(
857 "Skipping unexecutable interpreter at `{}` from {source}: {err}",
858 path.display()
859 );
860 false
861 }
862 InterpreterError::NotFound(path)
863 | InterpreterError::BrokenLink(BrokenLink { path, .. }) => {
864 if matches!(source, PythonSource::ActiveEnvironment)
867 && uv_fs::is_virtualenv_executable(path)
868 {
869 true
870 } else {
871 trace!("Skipping missing interpreter at `{}`", path.display());
872 false
873 }
874 }
875 },
876 Self::VirtualEnv(VirtualEnvError::MissingPyVenvCfg(path)) => {
877 trace!("Skipping broken virtualenv at `{}`", path.display());
878 false
879 }
880 _ => true,
881 }
882 }
883}
884
885fn python_installation_from_directory(
887 path: &PathBuf,
888 cache: &Cache,
889) -> Result<PythonInstallation, uv_python_interpreter::InterpreterError> {
890 let executable = virtualenv_python_executable(path);
891 Ok(PythonInstallation {
892 source: PythonSource::ProvidedPath,
893 interpreter: Interpreter::query(&executable, cache)?,
894 })
895}
896
897fn python_executables_with_name(
899 name: &str,
900) -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + '_ {
901 which_all(name)
902 .into_iter()
903 .flat_map(|inner| inner.map(|path| Ok((PythonSource::SearchPath, path))))
904}
905
906fn python_installations_with_name<'a>(
908 name: &'a str,
909 cache: &'a Cache,
910 strategy: QueryStrategy,
911) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
912 python_installations_from_executables(
913 python_executables_with_name(name)
914 .map_ok(|executable| PythonExecutableGroup(vec![executable])),
915 cache,
916 strategy,
917 )
918}
919
920pub(crate) fn find_python_installations<'a>(
922 request: &'a PythonRequest,
923 environments: EnvironmentPreference,
924 preference: PythonPreference,
925 arch: Option<PythonArchitecture>,
926 cache: &'a Cache,
927) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
928 find_python_installations_with_strategy(
929 request,
930 environments,
931 preference,
932 arch,
933 cache,
934 QueryStrategy::Sequential,
935 )
936}
937
938fn find_python_installations_with_strategy<'a>(
941 request: &'a PythonRequest,
942 environments: EnvironmentPreference,
943 preference: PythonPreference,
944 arch: Option<PythonArchitecture>,
945 cache: &'a Cache,
946 strategy: QueryStrategy,
947) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
948 let arch = arch.map(|arch| {
949 PythonDownloadRequest::from_request(request)
950 .and_then(|request| request.arch().map(ArchRequest::inner))
951 .unwrap_or_else(|| arch.into_inner())
952 });
953 let platform = PlatformRequest::default().with_default_arch(arch);
954 let sources = DiscoveryPreferences {
955 python_preference: preference,
956 environment_preference: environments,
957 }
958 .sources(request);
959
960 match request {
961 PythonRequest::File(path) => Box::new(iter::once({
962 if preference.allows_source(PythonSource::ProvidedPath) {
963 debug!("Checking for Python interpreter at {request}");
964 match Interpreter::query(path, cache) {
965 Ok(interpreter) => Ok(Ok(PythonInstallation {
966 source: PythonSource::ProvidedPath,
967 interpreter,
968 })),
969 Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
970 Ok(Err(PythonNotFound {
971 request: request.clone(),
972 python_preference: preference,
973 environment_preference: environments,
974 }))
975 }
976 Err(err) => Err(Error::Query(
977 Box::new(err),
978 path.clone(),
979 PythonSource::ProvidedPath,
980 )),
981 }
982 } else {
983 Err(Error::SourceNotAllowed(
984 request.clone(),
985 PythonSource::ProvidedPath,
986 preference,
987 ))
988 }
989 })),
990 PythonRequest::Directory(path) => Box::new(iter::once({
991 if preference.allows_source(PythonSource::ProvidedPath) {
992 debug!("Checking for Python interpreter in {request}");
993 match python_installation_from_directory(path, cache) {
994 Ok(installation) => Ok(Ok(installation)),
995 Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
996 Ok(Err(PythonNotFound {
997 request: request.clone(),
998 python_preference: preference,
999 environment_preference: environments,
1000 }))
1001 }
1002 Err(err) => Err(Error::Query(
1003 Box::new(err),
1004 path.clone(),
1005 PythonSource::ProvidedPath,
1006 )),
1007 }
1008 } else {
1009 Err(Error::SourceNotAllowed(
1010 request.clone(),
1011 PythonSource::ProvidedPath,
1012 preference,
1013 ))
1014 }
1015 })),
1016 PythonRequest::ExecutableName(name) => {
1017 if preference.allows_source(PythonSource::SearchPath) {
1018 debug!("Searching for Python interpreter with {request}");
1019 Box::new(
1020 python_installations_with_name(name, cache, strategy)
1021 .filter_ok(move |installation| {
1022 installation.satisfies_environment_preference(environments)
1023 })
1024 .map_ok(Ok),
1025 )
1026 } else {
1027 Box::new(iter::once(Err(Error::SourceNotAllowed(
1028 request.clone(),
1029 PythonSource::SearchPath,
1030 preference,
1031 ))))
1032 }
1033 }
1034 PythonRequest::Any => Box::new({
1035 debug!("Searching for any Python interpreter in {sources}");
1036 python_installations(
1037 &VersionRequest::Any,
1038 None,
1039 platform,
1040 environments,
1041 preference,
1042 cache,
1043 strategy,
1044 )
1045 .map_ok(Ok)
1046 }),
1047 PythonRequest::Default => Box::new({
1048 debug!("Searching for default Python interpreter in {sources}");
1049 python_installations(
1050 &VersionRequest::Default,
1051 None,
1052 platform,
1053 environments,
1054 preference,
1055 cache,
1056 strategy,
1057 )
1058 .map_ok(Ok)
1059 }),
1060 PythonRequest::Version(version) => {
1061 if let Err(err) = version.check_supported() {
1062 return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1063 }
1064 Box::new({
1065 debug!("Searching for {request} in {sources}");
1066 python_installations(
1067 version,
1068 None,
1069 platform,
1070 environments,
1071 preference,
1072 cache,
1073 strategy,
1074 )
1075 .map_ok(Ok)
1076 })
1077 }
1078 PythonRequest::Implementation(implementation) => Box::new({
1079 debug!("Searching for a {request} interpreter in {sources}");
1080 python_installations(
1081 &VersionRequest::Default,
1082 Some(implementation),
1083 platform,
1084 environments,
1085 preference,
1086 cache,
1087 strategy,
1088 )
1089 .filter_ok(move |installation| {
1090 installation
1091 .interpreter
1092 .matches_implementation(*implementation)
1093 })
1094 .map_ok(Ok)
1095 }),
1096 PythonRequest::ImplementationVersion(implementation, version) => {
1097 if let Err(err) = version.check_supported() {
1098 return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1099 }
1100 Box::new({
1101 debug!("Searching for {request} in {sources}");
1102 python_installations(
1103 version,
1104 Some(implementation),
1105 platform,
1106 environments,
1107 preference,
1108 cache,
1109 strategy,
1110 )
1111 .filter_ok(move |installation| {
1112 installation
1113 .interpreter
1114 .matches_implementation(*implementation)
1115 })
1116 .map_ok(Ok)
1117 })
1118 }
1119 PythonRequest::Key(request) => {
1120 if let Some(version) = request.version()
1121 && let Err(err) = version.check_supported()
1122 {
1123 return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1124 }
1125
1126 Box::new({
1127 debug!("Searching for {request} in {sources}");
1128 python_installations(
1129 request.version().unwrap_or(&VersionRequest::Default),
1130 request.implementation(),
1131 request.platform().with_default_arch(arch),
1132 environments,
1133 preference,
1134 cache,
1135 strategy,
1136 )
1137 .filter_ok(move |installation| {
1138 installation.interpreter.matches_download_request(request)
1139 })
1140 .map_ok(Ok)
1141 })
1142 }
1143 }
1144}
1145
1146pub fn find_all_python_installations(
1153 request: &PythonRequest,
1154 environments: EnvironmentPreference,
1155 preference: PythonPreference,
1156 arch: Option<PythonArchitecture>,
1157 cache: &Cache,
1158) -> Result<Vec<PythonInstallation>, Error> {
1159 let results = find_python_installations_with_strategy(
1160 request,
1161 environments,
1162 preference,
1163 arch,
1164 cache,
1165 QueryStrategy::Parallel,
1166 );
1167 let mut installations = Vec::new();
1168 for result in results {
1169 match result {
1170 Ok(Ok(installation)) => installations.push(installation),
1171 Ok(Err(_)) => {}
1172 Err(err @ Error::Query(..)) => {
1173 warn_user_with_chain!(&err);
1174 }
1175 Err(err) if err.is_critical() => return Err(err),
1176 Err(_) => {}
1177 }
1178 }
1179 Ok(installations)
1180}
1181
1182pub(crate) fn find_python_installation(
1187 request: &PythonRequest,
1188 environments: EnvironmentPreference,
1189 preference: PythonPreference,
1190 arch: Option<PythonArchitecture>,
1191 cache: &Cache,
1192) -> Result<FindPythonResult, Error> {
1193 let installations = find_python_installations(request, environments, preference, arch, cache);
1194 let mut first_prerelease = None;
1195 let mut first_debug = None;
1196 let mut first_managed = None;
1197 let mut first_error = None;
1198 for result in installations {
1199 if !result.as_ref().err().is_none_or(Error::is_critical) {
1201 if first_error.is_none()
1203 && let Err(err) = result
1204 {
1205 first_error = Some(err);
1206 }
1207 continue;
1208 }
1209
1210 let Ok(Ok(installation)) = result else {
1212 return result;
1213 };
1214
1215 let has_default_executable_name = installation.interpreter.has_default_executable_name()
1221 && matches!(
1222 installation.source,
1223 PythonSource::SearchPath | PythonSource::SearchPathFirst
1224 );
1225
1226 if installation.python_version().pre().is_some()
1229 && !request.allows_prereleases()
1230 && !installation.source.allows_prereleases()
1231 && !has_default_executable_name
1232 {
1233 debug!("Skipping pre-release installation {}", installation.key());
1234 if first_prerelease.is_none() {
1235 first_prerelease = Some(installation);
1236 }
1237 continue;
1238 }
1239
1240 if installation.key().variant().is_debug()
1243 && !request.allows_debug()
1244 && !installation.source.allows_debug()
1245 && !has_default_executable_name
1246 {
1247 debug!("Skipping debug installation {}", installation.key());
1248 if first_debug.is_none() {
1249 first_debug = Some(installation);
1250 }
1251 continue;
1252 }
1253
1254 if installation.is_alternative_implementation()
1259 && !request.allows_alternative_implementations()
1260 && !installation.source.allows_alternative_implementations()
1261 && !has_default_executable_name
1262 {
1263 debug!("Skipping alternative implementation {}", installation.key());
1264 continue;
1265 }
1266
1267 if matches!(preference, PythonPreference::System) && installation.is_managed() {
1270 debug!(
1271 "Skipping managed installation {}: system installation preferred",
1272 installation.key()
1273 );
1274 if first_managed.is_none() {
1275 first_managed = Some(installation);
1276 }
1277 continue;
1278 }
1279
1280 return Ok(Ok(installation));
1282 }
1283
1284 if let Some(installation) = first_managed {
1287 debug!(
1288 "Allowing managed installation {}: no system installations",
1289 installation.key()
1290 );
1291 return Ok(Ok(installation));
1292 }
1293
1294 if let Some(installation) = first_debug {
1297 debug!(
1298 "Allowing debug installation {}: no non-debug installations",
1299 installation.key()
1300 );
1301 return Ok(Ok(installation));
1302 }
1303
1304 if let Some(installation) = first_prerelease {
1306 debug!(
1307 "Allowing pre-release installation {}: no stable installations",
1308 installation.key()
1309 );
1310 return Ok(Ok(installation));
1311 }
1312
1313 if let Some(err) = first_error {
1316 return Err(err);
1317 }
1318
1319 Ok(Err(PythonNotFound {
1320 request: request
1321 .with_default_arch(arch.map(PythonArchitecture::into_inner))
1322 .into_owned(),
1323 environment_preference: environments,
1324 python_preference: preference,
1325 }))
1326}
1327
1328#[instrument(skip_all, fields(request))]
1342pub(crate) async fn find_best_python_installation(
1343 request: &PythonRequest,
1344 environments: EnvironmentPreference,
1345 preference: PythonPreference,
1346 arch: Option<PythonArchitecture>,
1347 downloads_enabled: bool,
1348 client_builder: &BaseClientBuilder<'_>,
1349 cache: &Cache,
1350 reporter: Option<&dyn uv_python_managed::downloads::Reporter>,
1351 mirrors: PythonDownloadMirrors<'_>,
1352 python_downloads_json_url: Option<&str>,
1353) -> Result<PythonInstallation, crate::Error> {
1354 debug!("Starting Python discovery for {request}");
1355 let original_request = request;
1356
1357 let mut previous_fetch_failed = false;
1358 let mut download_state = None;
1359
1360 let request_without_patch = match request {
1361 PythonRequest::Version(version) => {
1362 if version.has_patch() {
1363 Some(PythonRequest::Version(version.clone().without_patch()))
1364 } else {
1365 None
1366 }
1367 }
1368 PythonRequest::ImplementationVersion(implementation, version) => Some(
1369 PythonRequest::ImplementationVersion(*implementation, version.clone().without_patch()),
1370 ),
1371 _ => None,
1372 };
1373
1374 for (attempt, request) in iter::once(original_request)
1375 .chain(request_without_patch.iter())
1376 .chain(iter::once(&PythonRequest::Default))
1377 .enumerate()
1378 {
1379 debug!(
1380 "Looking for {request}{}",
1381 if request != original_request {
1382 format!(" attempt {attempt} (fallback after failing to find: {original_request})")
1383 } else {
1384 String::new()
1385 }
1386 );
1387 let result = find_python_installation(request, environments, preference, arch, cache);
1388 let error = match result {
1389 Ok(Ok(installation)) => {
1390 warn_on_unsupported_python(installation.interpreter());
1391 return Ok(installation);
1392 }
1393 Ok(Err(error)) => error.into(),
1395 Err(error) if !error.is_critical() => error.into(),
1396 Err(error) => return Err(error.into()),
1397 };
1398
1399 if downloads_enabled
1401 && !previous_fetch_failed
1402 && let Some(download_request) = PythonDownloadRequest::from_request(request)
1403 {
1404 let (client, retry_policy, download_list) =
1405 if let Some(download_state) = &mut download_state {
1406 download_state
1407 } else {
1408 let download_list = ManagedPythonDownloadList::new(
1409 client_builder,
1410 cache,
1411 python_downloads_json_url,
1412 )
1413 .await?;
1414 let retry_policy = client_builder.retry_policy();
1415
1416 let client = client_builder.clone().retries(0).build()?;
1419 download_state.insert((client, retry_policy, download_list))
1420 };
1421
1422 let download = download_request
1423 .clone()
1424 .with_default_arch(arch.map(PythonArchitecture::into_inner))
1425 .fill()
1426 .map(|request| download_list.find(&request));
1427
1428 let result = match download {
1429 Ok(Ok(download)) => PythonInstallation::fetch(
1430 download,
1431 client,
1432 retry_policy,
1433 cache,
1434 reporter,
1435 mirrors,
1436 )
1437 .await
1438 .map(Some),
1439 Ok(Err(uv_python_managed::downloads::Error::NoDownloadFound(_))) => Ok(None),
1440 Ok(Err(error)) => Err(error.into()),
1441 Err(error) => Err(error.into()),
1442 };
1443 if let Ok(Some(installation)) = result {
1444 return Ok(installation);
1445 }
1446 if let Err(error) = result {
1454 if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1458 return Err(error);
1459 }
1460
1461 warn_user_with_chain!(
1462 anyhow::Error::from(error)
1463 .context(format!(
1464 "A managed Python download is available for {request}, but an error occurred when attempting to download it."
1465 ))
1466 .as_ref()
1467 );
1468 previous_fetch_failed = true;
1469 }
1470 }
1471
1472 if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1478 return Err(match error {
1479 crate::Error::MissingPython(err, _) => PythonNotFound {
1480 request: original_request
1482 .with_default_arch(arch.map(PythonArchitecture::into_inner))
1483 .into_owned(),
1484 python_preference: err.python_preference,
1485 environment_preference: err.environment_preference,
1486 }
1487 .into(),
1488 other => other,
1489 });
1490 }
1491 }
1492
1493 unreachable!("The loop should have terminated when it reached PythonRequest::Default");
1494}
1495
1496fn warn_on_unsupported_python(interpreter: &Interpreter) {
1498 if interpreter.python_tuple() < (3, 8) {
1500 warn_user_once!(
1501 "uv is only compatible with Python >=3.8, found Python {}",
1502 interpreter.python_version()
1503 );
1504 }
1505}
1506
1507#[cfg(windows)]
1524fn is_windows_store_shim(path: &Path) -> bool {
1525 use std::os::windows::fs::MetadataExt;
1526 use std::os::windows::prelude::OsStrExt;
1527 use windows::Win32::Foundation::CloseHandle;
1528 use windows::Win32::Storage::FileSystem::{
1529 CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
1530 FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_MODE, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
1531 OPEN_EXISTING,
1532 };
1533 use windows::Win32::System::IO::DeviceIoControl;
1534 use windows::Win32::System::Ioctl::FSCTL_GET_REPARSE_POINT;
1535 use windows::core::PCWSTR;
1536
1537 if !path.is_absolute() {
1539 return false;
1540 }
1541
1542 let mut components = path.components().rev();
1545
1546 if !components
1548 .next()
1549 .and_then(|component| component.as_os_str().to_str())
1550 .is_some_and(|component| {
1551 component.starts_with("python")
1552 && std::path::Path::new(component)
1553 .extension()
1554 .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"))
1555 })
1556 {
1557 return false;
1558 }
1559
1560 if components
1562 .next()
1563 .is_none_or(|component| component.as_os_str() != "WindowsApps")
1564 {
1565 return false;
1566 }
1567
1568 if components
1570 .next()
1571 .is_none_or(|component| component.as_os_str() != "Microsoft")
1572 {
1573 return false;
1574 }
1575
1576 let Ok(md) = fs_err::symlink_metadata(path) else {
1578 return false;
1579 };
1580 if md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0 {
1581 return false;
1582 }
1583
1584 let mut path_encoded = path
1585 .as_os_str()
1586 .encode_wide()
1587 .chain(std::iter::once(0))
1588 .collect::<Vec<_>>();
1589
1590 #[allow(unsafe_code)]
1592 let reparse_handle = unsafe {
1593 CreateFileW(
1594 PCWSTR(path_encoded.as_mut_ptr()),
1595 0,
1596 FILE_SHARE_MODE(0),
1597 None,
1598 OPEN_EXISTING,
1599 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1600 None,
1601 )
1602 };
1603
1604 let Ok(reparse_handle) = reparse_handle else {
1605 return false;
1606 };
1607
1608 let mut buf = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
1609 let mut bytes_returned = 0;
1610
1611 #[allow(unsafe_code, clippy::cast_possible_truncation)]
1613 let success = unsafe {
1614 DeviceIoControl(
1615 reparse_handle,
1616 FSCTL_GET_REPARSE_POINT,
1617 None,
1618 0,
1619 Some(buf.as_mut_ptr().cast()),
1620 buf.len() as u32 * 2,
1621 Some(&raw mut bytes_returned),
1622 None,
1623 )
1624 .is_ok()
1625 };
1626
1627 #[allow(unsafe_code)]
1629 unsafe {
1630 let _ = CloseHandle(reparse_handle);
1631 }
1632
1633 if !success {
1635 return false;
1636 }
1637
1638 let reparse_point = String::from_utf16_lossy(&buf[..bytes_returned as usize]);
1639 reparse_point.contains("\\AppInstallerPythonRedirector.exe")
1640}
1641
1642#[cfg(not(windows))]
1646fn is_windows_store_shim(_path: &Path) -> bool {
1647 false
1648}
1649
1650impl DiscoveryPreferences {
1651 fn sources(&self, request: &PythonRequest) -> String {
1654 let python_sources = self
1655 .python_preference
1656 .sources()
1657 .iter()
1658 .map(ToString::to_string)
1659 .collect::<Vec<_>>();
1660 match self.environment_preference {
1661 EnvironmentPreference::Any => disjunction(
1662 &["virtual environments"]
1663 .into_iter()
1664 .chain(python_sources.iter().map(String::as_str))
1665 .collect::<Vec<_>>(),
1666 ),
1667 EnvironmentPreference::ExplicitSystem => {
1668 if request.is_explicit_system() {
1669 disjunction(
1670 &["virtual environments"]
1671 .into_iter()
1672 .chain(python_sources.iter().map(String::as_str))
1673 .collect::<Vec<_>>(),
1674 )
1675 } else {
1676 disjunction(&["virtual environments"])
1677 }
1678 }
1679 EnvironmentPreference::OnlySystem => disjunction(
1680 &python_sources
1681 .iter()
1682 .map(String::as_str)
1683 .collect::<Vec<_>>(),
1684 ),
1685 EnvironmentPreference::OnlyVirtual => disjunction(&["virtual environments"]),
1686 }
1687 }
1688}
1689
1690impl fmt::Display for PythonNotFound {
1691 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1692 let sources = DiscoveryPreferences {
1693 python_preference: self.python_preference,
1694 environment_preference: self.environment_preference,
1695 }
1696 .sources(&self.request);
1697
1698 match self.request {
1699 PythonRequest::Default | PythonRequest::Any => {
1700 write!(f, "No interpreter found in {sources}")
1701 }
1702 PythonRequest::File(_) => {
1703 write!(f, "No interpreter found at {}", self.request)
1704 }
1705 PythonRequest::Directory(_) => {
1706 write!(f, "No interpreter found in {}", self.request)
1707 }
1708 _ => {
1709 write!(f, "No interpreter found for {} in {sources}", self.request)
1710 }
1711 }
1712 }
1713}
1714
1715fn disjunction(items: &[&str]) -> String {
1717 match items.len() {
1718 0 => String::new(),
1719 1 => items[0].to_string(),
1720 2 => format!("{} or {}", items[0], items[1]),
1721 _ => {
1722 let last = items.last().unwrap();
1723 format!(
1724 "{}, or {}",
1725 items.iter().take(items.len() - 1).join(", "),
1726 last
1727 )
1728 }
1729 }
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734 use std::assert_matches;
1735 use std::{cell::Cell, io, path::PathBuf};
1736
1737 use test_log::test;
1738 use uv_cache::Cache;
1739
1740 use uv_python_types::PythonRequest;
1741
1742 use super::{
1743 DiscoveryPreferences, EnvironmentPreference, Error, InterpreterError,
1744 PythonExecutableGroup, PythonPreference, PythonSource, QueryStrategy,
1745 python_installations_from_executables, sort_installations_by_key,
1746 };
1747
1748 #[test]
1750 fn installation_key_order_only_partitions_critical_errors() {
1751 let query_error = |error| {
1752 Error::Query(
1753 Box::new(error),
1754 PathBuf::from("python"),
1755 PythonSource::SearchPath,
1756 )
1757 };
1758
1759 let mut installations = [
1760 Ok(1_u8),
1761 Err(query_error(InterpreterError::NotFound(PathBuf::from(
1762 "missing",
1763 )))),
1764 Ok(2),
1765 Err(query_error(InterpreterError::Io(io::Error::other(
1766 "critical",
1767 )))),
1768 Ok(3),
1769 ];
1770
1771 sort_installations_by_key(&mut installations, |key| *key);
1772
1773 assert_matches!(
1774 &installations[..],
1775 [Ok(2), Ok(1), Err(noncritical), Err(critical), Ok(3)]
1776 if !noncritical.is_critical() && critical.is_critical()
1777 );
1778 }
1779
1780 #[test]
1781 fn sequential_query_strategy_does_not_prefetch_executable_groups() -> anyhow::Result<()> {
1782 let cache = Cache::temp()?;
1783 let pulls = Cell::new(0);
1784 let executables = (0..2).map(|_| {
1785 pulls.set(pulls.get() + 1);
1786 Err::<PythonExecutableGroup, _>(Error::SourceNotAllowed(
1787 PythonRequest::Default,
1788 PythonSource::SearchPath,
1789 PythonPreference::OnlyManaged,
1790 ))
1791 });
1792
1793 let mut installations =
1794 python_installations_from_executables(executables, &cache, QueryStrategy::Sequential);
1795
1796 assert_eq!(pulls.get(), 0);
1797 assert!(installations.next().is_some_and(|result| result.is_err()));
1798 assert_eq!(pulls.get(), 1);
1799
1800 Ok(())
1801 }
1802
1803 #[test]
1804 fn discovery_sources_prefer_system_orders_search_path_first() {
1805 let preferences = DiscoveryPreferences {
1806 python_preference: PythonPreference::System,
1807 environment_preference: EnvironmentPreference::OnlySystem,
1808 };
1809 let sources = preferences.sources(&PythonRequest::Default);
1810
1811 if cfg!(windows) {
1812 assert_eq!(sources, "search path, registry, or managed installations");
1813 } else {
1814 assert_eq!(sources, "search path or managed installations");
1815 }
1816 }
1817
1818 #[test]
1819 fn discovery_sources_only_system_matches_platform_order() {
1820 let preferences = DiscoveryPreferences {
1821 python_preference: PythonPreference::OnlySystem,
1822 environment_preference: EnvironmentPreference::OnlySystem,
1823 };
1824 let sources = preferences.sources(&PythonRequest::Default);
1825
1826 if cfg!(windows) {
1827 assert_eq!(sources, "search path or registry");
1828 } else {
1829 assert_eq!(sources, "search path");
1830 }
1831 }
1832}