-
Notifications
You must be signed in to change notification settings - Fork 952
/
discovery.rs
2362 lines (2201 loc) · 89.8 KB
/
discovery.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use itertools::{Either, Itertools};
use regex::Regex;
use same_file::is_same_file;
use std::env::consts::EXE_SUFFIX;
use std::fmt::{self, Debug, Formatter};
use std::{env, io, iter};
use std::{path::Path, path::PathBuf, str::FromStr};
use thiserror::Error;
use tracing::{debug, instrument, trace};
use which::{which, which_all};
use uv_cache::Cache;
use uv_fs::which::is_executable;
use uv_fs::Simplified;
use uv_pep440::{Prerelease, Version, VersionSpecifier, VersionSpecifiers};
use uv_static::EnvVars;
use uv_warnings::warn_user_once;
use crate::downloads::PythonDownloadRequest;
use crate::implementation::ImplementationName;
use crate::installation::PythonInstallation;
use crate::interpreter::Error as InterpreterError;
use crate::managed::ManagedPythonInstallations;
#[cfg(windows)]
use crate::microsoft_store::find_microsoft_store_pythons;
#[cfg(windows)]
use crate::py_launcher::{registry_pythons, WindowsPython};
use crate::virtualenv::{
conda_prefix_from_env, virtualenv_from_env, virtualenv_from_working_dir,
virtualenv_python_executable,
};
use crate::{Interpreter, PythonVersion};
/// A request to find a Python installation.
///
/// See [`PythonRequest::from_str`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PythonRequest {
/// An appropriate default Python installation
///
/// This may skip some Python installations, such as pre-release versions or alternative
/// implementations.
#[default]
Default,
/// Any Python installation
Any,
/// A Python version without an implementation name e.g. `3.10` or `>=3.12,<3.13`
Version(VersionRequest),
/// A path to a directory containing a Python installation, e.g. `.venv`
Directory(PathBuf),
/// A path to a Python executable e.g. `~/bin/python`
File(PathBuf),
/// The name of a Python executable (i.e. for lookup in the PATH) e.g. `foopython3`
ExecutableName(String),
/// A Python implementation without a version e.g. `pypy` or `pp`
Implementation(ImplementationName),
/// A Python implementation name and version e.g. `pypy3.8` or `pypy@3.8` or `pp38`
ImplementationVersion(ImplementationName, VersionRequest),
/// A request for a specific Python installation key e.g. `cpython-3.12-x86_64-linux-gnu`
/// Generally these refer to managed Python downloads.
Key(PythonDownloadRequest),
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum PythonPreference {
/// Only use managed Python installations; never use system Python installations.
OnlyManaged,
#[default]
/// Prefer managed Python installations over system Python installations.
///
/// System Python installations are still preferred over downloading managed Python versions.
/// Use `only-managed` to always fetch a managed Python version.
Managed,
/// Prefer system Python installations over managed Python installations.
///
/// If a system Python installation cannot be found, a managed Python installation can be used.
System,
/// Only use system Python installations; never use managed Python installations.
OnlySystem,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum PythonDownloads {
/// Automatically download managed Python installations when needed.
#[default]
#[serde(alias = "auto")]
Automatic,
/// Do not automatically download managed Python installations; require explicit installation.
Manual,
/// Do not ever allow Python downloads.
Never,
}
impl FromStr for PythonDownloads {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"auto" | "automatic" | "true" | "1" => Ok(PythonDownloads::Automatic),
"manual" => Ok(PythonDownloads::Manual),
"never" | "false" | "0" => Ok(PythonDownloads::Never),
_ => Err(format!("Invalid value for `python-download`: '{s}'")),
}
}
}
impl From<bool> for PythonDownloads {
fn from(value: bool) -> Self {
if value {
PythonDownloads::Automatic
} else {
PythonDownloads::Never
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EnvironmentPreference {
/// Only use virtual environments, never allow a system environment.
#[default]
OnlyVirtual,
/// Prefer virtual environments and allow a system environment if explicitly requested.
ExplicitSystem,
/// Only use a system environment, ignore virtual environments.
OnlySystem,
/// Allow any environment.
Any,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PythonVariant {
#[default]
Default,
Freethreaded,
}
/// A Python discovery version request.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum VersionRequest {
/// Allow an appropriate default Python version.
#[default]
Default,
/// Allow any Python version.
Any,
Major(u8, PythonVariant),
MajorMinor(u8, u8, PythonVariant),
MajorMinorPatch(u8, u8, u8, PythonVariant),
MajorMinorPrerelease(u8, u8, Prerelease, PythonVariant),
Range(VersionSpecifiers, PythonVariant),
}
/// The result of an Python installation search.
///
/// Returned by [`find_python_installation`].
type FindPythonResult = Result<PythonInstallation, PythonNotFound>;
/// The result of failed Python installation discovery.
///
/// See [`FindPythonResult`].
#[derive(Clone, Debug, Error)]
pub struct PythonNotFound {
pub request: PythonRequest,
pub python_preference: PythonPreference,
pub environment_preference: EnvironmentPreference,
}
/// A location for discovery of a Python installation or interpreter.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord)]
pub enum PythonSource {
/// The path was provided directly
ProvidedPath,
/// An environment was active e.g. via `VIRTUAL_ENV`
ActiveEnvironment,
/// A conda environment was active e.g. via `CONDA_PREFIX`
CondaPrefix,
/// An environment was discovered e.g. via `.venv`
DiscoveredEnvironment,
/// An executable was found in the search path i.e. `PATH`
SearchPath,
/// An executable was found in the Windows registry via PEP 514
Registry,
/// An executable was found in the known Microsoft Store locations
MicrosoftStore,
/// The Python installation was found in the uv managed Python directory
Managed,
/// The Python installation was found via the invoking interpreter i.e. via `python -m uv ...`
ParentInterpreter,
}
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
/// An error was encountering when retrieving interpreter information.
#[error("Failed to inspect Python interpreter from {2} at `{}` ", .1.user_display())]
Query(
#[source] Box<crate::interpreter::Error>,
PathBuf,
PythonSource,
),
/// An error was encountered when interacting with a managed Python installation.
#[error(transparent)]
ManagedPython(#[from] crate::managed::Error),
/// An error was encountered when inspecting a virtual environment.
#[error(transparent)]
VirtualEnv(#[from] crate::virtualenv::Error),
#[cfg(windows)]
#[error("Failed to query installed Python versions from the Windows registry")]
RegistryError(#[from] windows_result::Error),
/// An invalid version request was given
#[error("Invalid version request: {0}")]
InvalidVersionRequest(String),
// TODO(zanieb): Is this error case necessary still? We should probably drop it.
#[error("Interpreter discovery for `{0}` requires `{1}` but only {2} is allowed")]
SourceNotAllowed(PythonRequest, PythonSource, PythonPreference),
}
/// Lazily iterate over Python executables in mutable environments.
///
/// The following sources are supported:
///
/// - Active virtual environment (via `VIRTUAL_ENV`)
/// - Active conda environment (via `CONDA_PREFIX`)
/// - Discovered virtual environment (e.g. `.venv` in a parent directory)
///
/// Notably, "system" environments are excluded. See [`python_executables_from_installed`].
fn python_executables_from_environments<'a>(
) -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a {
let from_virtual_environment = std::iter::once_with(|| {
virtualenv_from_env()
.into_iter()
.map(virtualenv_python_executable)
.map(|path| Ok((PythonSource::ActiveEnvironment, path)))
})
.flatten();
let from_conda_environment = std::iter::once_with(|| {
conda_prefix_from_env()
.into_iter()
.map(virtualenv_python_executable)
.map(|path| Ok((PythonSource::CondaPrefix, path)))
})
.flatten();
let from_discovered_environment = std::iter::once_with(|| {
virtualenv_from_working_dir()
.map(|path| {
path.map(virtualenv_python_executable)
.map(|path| (PythonSource::DiscoveredEnvironment, path))
.into_iter()
})
.map_err(Error::from)
})
.flatten_ok();
from_virtual_environment
.chain(from_conda_environment)
.chain(from_discovered_environment)
}
/// Lazily iterate over Python executables installed on the system.
///
/// The following sources are supported:
///
/// - Managed Python installations (e.g. `uv python install`)
/// - The search path (i.e. `PATH`)
/// - The `py` launcher (Windows only)
///
/// The ordering and presence of each source is determined by the [`PythonPreference`].
///
/// If a [`VersionRequest`] is provided, we will skip executables that we know do not satisfy the request
/// and (as discussed in [`python_executables_from_search_path`]) additional version-specific executables may
/// be included. However, the caller MUST query the returned executables to ensure they satisfy the request;
/// this function does not guarantee that the executables provide any particular version. See
/// [`find_python_installation`] instead.
///
/// This function does not guarantee that the executables are valid Python interpreters.
/// See [`python_interpreters_from_executables`].
fn python_executables_from_installed<'a>(
version: &'a VersionRequest,
implementation: Option<&'a ImplementationName>,
preference: PythonPreference,
) -> Box<dyn Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a> {
let from_managed_installations = std::iter::once_with(move || {
ManagedPythonInstallations::from_settings()
.map_err(Error::from)
.and_then(|installed_installations| {
debug!(
"Searching for managed installations at `{}`",
installed_installations.root().user_display()
);
let installations = installed_installations.find_matching_current_platform()?;
// Check that the Python version satisfies the request to avoid unnecessary interpreter queries later
Ok(installations
.into_iter()
.filter(move |installation| {
if version.matches_version(&installation.version()) {
true
} else {
debug!("Skipping incompatible managed installation `{installation}`");
false
}
})
.inspect(|installation| debug!("Found managed installation `{installation}`"))
.map(|installation| (PythonSource::Managed, installation.executable())))
})
})
.flatten_ok();
let from_search_path = std::iter::once_with(move || {
python_executables_from_search_path(version, implementation)
.map(|path| Ok((PythonSource::SearchPath, path)))
})
.flatten();
let from_windows_registry = std::iter::once_with(move || {
#[cfg(windows)]
{
// Skip interpreter probing if we already know the version doesn't match.
let version_filter = move |entry: &WindowsPython| {
if let Some(found) = &entry.version {
version.matches_version(found)
} else {
true
}
};
env::var_os(EnvVars::UV_TEST_PYTHON_PATH)
.is_none()
.then(|| {
registry_pythons()
.map(|entries| {
entries
.into_iter()
.filter(version_filter)
.map(|entry| (PythonSource::Registry, entry.path))
.chain(
find_microsoft_store_pythons()
.filter(version_filter)
.map(|entry| (PythonSource::MicrosoftStore, entry.path)),
)
})
.map_err(Error::from)
})
.into_iter()
.flatten_ok()
}
#[cfg(not(windows))]
{
Vec::new()
}
})
.flatten();
match preference {
PythonPreference::OnlyManaged => Box::new(from_managed_installations),
PythonPreference::Managed => Box::new(
from_managed_installations
.chain(from_search_path)
.chain(from_windows_registry),
),
PythonPreference::System => Box::new(
from_search_path
.chain(from_windows_registry)
.chain(from_managed_installations),
),
PythonPreference::OnlySystem => Box::new(from_search_path.chain(from_windows_registry)),
}
}
/// Lazily iterate over all discoverable Python executables.
///
/// Note that Python executables may be excluded by the given [`EnvironmentPreference`] and [`PythonPreference`].
///
/// See [`python_executables_from_installed`] and [`python_executables_from_environments`]
/// for more information on discovery.
fn python_executables<'a>(
version: &'a VersionRequest,
implementation: Option<&'a ImplementationName>,
environments: EnvironmentPreference,
preference: PythonPreference,
) -> Box<dyn Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a> {
// Always read from `UV_INTERNAL__PARENT_INTERPRETER` — it could be a system interpreter
let from_parent_interpreter = std::iter::once_with(|| {
std::env::var_os(EnvVars::UV_INTERNAL__PARENT_INTERPRETER)
.into_iter()
.map(|path| Ok((PythonSource::ParentInterpreter, PathBuf::from(path))))
})
.flatten();
let from_environments = python_executables_from_environments();
let from_installed = python_executables_from_installed(version, implementation, preference);
// Limit the search to the relevant environment preference; we later validate that they match
// the preference but queries are expensive and we query less interpreters this way.
match environments {
EnvironmentPreference::OnlyVirtual => {
Box::new(from_parent_interpreter.chain(from_environments))
}
EnvironmentPreference::ExplicitSystem | EnvironmentPreference::Any => Box::new(
from_parent_interpreter
.chain(from_environments)
.chain(from_installed),
),
EnvironmentPreference::OnlySystem => {
Box::new(from_parent_interpreter.chain(from_installed))
}
}
}
/// Lazily iterate over Python executables in the `PATH`.
///
/// The [`VersionRequest`] and [`ImplementationName`] are used to determine the possible
/// Python interpreter names, e.g. if looking for Python 3.9 we will look for `python3.9`
/// or if looking for `PyPy` we will look for `pypy` in addition to the default names.
///
/// Executables are returned in the search path order, then by specificity of the name, e.g.
/// `python3.9` is preferred over `python3` and `pypy3.9` is preferred over `python3.9`.
///
/// If a `version` is not provided, we will only look for default executable names e.g.
/// `python3` and `python` — `python3.9` and similar will not be included.
fn python_executables_from_search_path<'a>(
version: &'a VersionRequest,
implementation: Option<&'a ImplementationName>,
) -> impl Iterator<Item = PathBuf> + 'a {
// `UV_TEST_PYTHON_PATH` can be used to override `PATH` to limit Python executable availability in the test suite
let search_path = env::var_os(EnvVars::UV_TEST_PYTHON_PATH)
.unwrap_or(env::var_os(EnvVars::PATH).unwrap_or_default());
let possible_names: Vec<_> = version
.executable_names(implementation)
.into_iter()
.map(|name| name.to_string())
.collect();
trace!(
"Searching PATH for executables: {}",
possible_names.join(", ")
);
// Split and iterate over the paths instead of using `which_all` so we can
// check multiple names per directory while respecting the search path order and python names
// precedence.
let search_dirs: Vec<_> = env::split_paths(&search_path).collect();
search_dirs
.into_iter()
.filter(|dir| dir.is_dir())
.flat_map(move |dir| {
// Clone the directory for second closure
let dir_clone = dir.clone();
trace!(
"Checking `PATH` directory for interpreters: {}",
dir.display()
);
possible_names
.clone()
.into_iter()
.flat_map(move |name| {
// Since we're just working with a single directory at a time, we collect to simplify ownership
which::which_in_global(&*name, Some(&dir))
.into_iter()
.flatten()
// We have to collect since `which` requires that the regex outlives its
// parameters, and the dir is local while we return the iterator.
.collect::<Vec<_>>()
})
.chain(find_all_minor(implementation, version, &dir_clone))
.filter(|path| !is_windows_store_shim(path))
.inspect(|path| trace!("Found possible Python executable: {}", path.display()))
.chain(
// TODO(zanieb): Consider moving `python.bat` into `possible_names` to avoid a chain
cfg!(windows)
.then(move || {
which::which_in_global("python.bat", Some(&dir_clone))
.into_iter()
.flatten()
.collect::<Vec<_>>()
})
.into_iter()
.flatten(),
)
})
}
/// Find all acceptable `python3.x` minor versions.
///
/// For example, let's say `python` and `python3` are Python 3.10. When a user requests `>= 3.11`,
/// we still need to find a `python3.12` in PATH.
fn find_all_minor(
implementation: Option<&ImplementationName>,
version_request: &VersionRequest,
dir: &Path,
) -> impl Iterator<Item = PathBuf> {
match version_request {
&VersionRequest::Any
| VersionRequest::Default
| VersionRequest::Major(_, _)
| VersionRequest::Range(_, _) => {
let regex = if let Some(implementation) = implementation {
Regex::new(&format!(
r"^({}|python3)\.(?<minor>\d\d?)t?{}$",
regex::escape(&implementation.to_string()),
regex::escape(EXE_SUFFIX)
))
.unwrap()
} else {
Regex::new(&format!(
r"^python3\.(?<minor>\d\d?)t?{}$",
regex::escape(EXE_SUFFIX)
))
.unwrap()
};
let all_minors = fs_err::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.filter(move |path| {
let Some(filename) = path.file_name() else {
return false;
};
let Some(filename) = filename.to_str() else {
return false;
};
let Some(captures) = regex.captures(filename) else {
return false;
};
// Filter out interpreter we already know have a too low minor version.
let minor = captures["minor"].parse().ok();
if let Some(minor) = minor {
// Optimization: Skip generally unsupported Python versions without querying.
if minor < 7 {
return false;
}
// Optimization 2: Skip excluded Python (minor) versions without querying.
if !version_request.matches_major_minor(3, minor) {
return false;
}
}
true
})
.filter(|path| is_executable(path))
.collect::<Vec<_>>();
Either::Left(all_minors.into_iter())
}
VersionRequest::MajorMinor(_, _, _)
| VersionRequest::MajorMinorPatch(_, _, _, _)
| VersionRequest::MajorMinorPrerelease(_, _, _, _) => Either::Right(iter::empty()),
}
}
/// Lazily iterate over all discoverable Python interpreters.
///
/// Note interpreters may be excluded by the given [`EnvironmentPreference`] and [`PythonPreference`].
///
/// See [`python_executables`] for more information on discovery.
fn python_interpreters<'a>(
version: &'a VersionRequest,
implementation: Option<&'a ImplementationName>,
environments: EnvironmentPreference,
preference: PythonPreference,
cache: &'a Cache,
) -> impl Iterator<Item = Result<(PythonSource, Interpreter), Error>> + 'a {
python_interpreters_from_executables(
python_executables(version, implementation, environments, preference),
cache,
)
.filter(move |result| result_satisfies_environment_preference(result, environments))
.filter(move |result| result_satisfies_version_request(result, version))
}
/// Lazily convert Python executables into interpreters.
fn python_interpreters_from_executables<'a>(
executables: impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a,
cache: &'a Cache,
) -> impl Iterator<Item = Result<(PythonSource, Interpreter), Error>> + 'a {
executables.map(|result| match result {
Ok((source, path)) => Interpreter::query(&path, cache)
.map(|interpreter| (source, interpreter))
.inspect(|(source, interpreter)| {
debug!(
"Found `{}` at `{}` ({source})",
interpreter.key(),
path.display()
);
})
.map_err(|err| Error::Query(Box::new(err), path, source))
.inspect_err(|err| debug!("{err}")),
Err(err) => Err(err),
})
}
/// Returns true if a Python interpreter matches the [`EnvironmentPreference`].
fn satisfies_environment_preference(
source: PythonSource,
interpreter: &Interpreter,
preference: EnvironmentPreference,
) -> bool {
match (
preference,
// Conda environments are not conformant virtual environments but we treat them as such
interpreter.is_virtualenv() || matches!(source, PythonSource::CondaPrefix),
) {
(EnvironmentPreference::Any, _) => true,
(EnvironmentPreference::OnlyVirtual, true) => true,
(EnvironmentPreference::OnlyVirtual, false) => {
debug!(
"Ignoring Python interpreter at `{}`: only virtual environments allowed",
interpreter.sys_executable().display()
);
false
}
(EnvironmentPreference::ExplicitSystem, true) => true,
(EnvironmentPreference::ExplicitSystem, false) => {
if matches!(
source,
PythonSource::ProvidedPath | PythonSource::ParentInterpreter
) {
debug!(
"Allowing explicitly requested system Python interpreter at `{}`",
interpreter.sys_executable().display()
);
true
} else {
debug!(
"Ignoring Python interpreter at `{}`: system interpreter not explicitly requested",
interpreter.sys_executable().display()
);
false
}
}
(EnvironmentPreference::OnlySystem, true) => {
debug!(
"Ignoring Python interpreter at `{}`: system interpreter required",
interpreter.sys_executable().display()
);
false
}
(EnvironmentPreference::OnlySystem, false) => true,
}
}
/// Utility for applying [`VersionRequest::matches_interpreter`] to a result type.
fn result_satisfies_version_request(
result: &Result<(PythonSource, Interpreter), Error>,
request: &VersionRequest,
) -> bool {
result.as_ref().ok().map_or(true, |(source, interpreter)| {
let request = request.clone().into_request_for_source(*source);
if request.matches_interpreter(interpreter) {
true
} else {
debug!(
"Skipping interpreter at `{}` from {source}: does not satisfy request `{request}`",
interpreter.sys_executable().user_display()
);
false
}
})
}
/// Utility for applying [`satisfies_environment_preference`] to a result type.
fn result_satisfies_environment_preference(
result: &Result<(PythonSource, Interpreter), Error>,
preference: EnvironmentPreference,
) -> bool {
result.as_ref().ok().map_or(true, |(source, interpreter)| {
satisfies_environment_preference(*source, interpreter, preference)
})
}
/// Check if an encountered error is critical and should stop discovery.
///
/// Returns false when an error could be due to a faulty Python installation and we should continue searching for a working one.
impl Error {
pub fn is_critical(&self) -> bool {
match self {
// When querying the Python interpreter fails, we will only raise errors that demonstrate that something is broken
// If the Python interpreter returned a bad response, we'll continue searching for one that works
Error::Query(err, _, source) => match &**err {
InterpreterError::Encode(_)
| InterpreterError::Io(_)
| InterpreterError::SpawnFailed { .. } => true,
InterpreterError::QueryScript { path, .. }
| InterpreterError::UnexpectedResponse { path, .. }
| InterpreterError::StatusCode { path, .. } => {
debug!(
"Skipping bad interpreter at {} from {source}: {err}",
path.display()
);
false
}
InterpreterError::NotFound(path) => {
trace!("Skipping missing interpreter at {}", path.display());
false
}
},
_ => true,
}
}
}
/// Create a [`PythonInstallation`] from a Python interpreter path.
fn python_installation_from_executable(
path: &PathBuf,
cache: &Cache,
) -> Result<PythonInstallation, crate::interpreter::Error> {
Ok(PythonInstallation {
source: PythonSource::ProvidedPath,
interpreter: Interpreter::query(path, cache)?,
})
}
/// Create a [`PythonInstallation`] from a Python installation root directory.
fn python_installation_from_directory(
path: &PathBuf,
cache: &Cache,
) -> Result<PythonInstallation, crate::interpreter::Error> {
let executable = virtualenv_python_executable(path);
python_installation_from_executable(&executable, cache)
}
/// Lazily iterate over all Python interpreters on the path with the given executable name.
fn python_interpreters_with_executable_name<'a>(
name: &'a str,
cache: &'a Cache,
) -> impl Iterator<Item = Result<(PythonSource, Interpreter), Error>> + 'a {
python_interpreters_from_executables(
which_all(name)
.into_iter()
.flat_map(|inner| inner.map(|path| Ok((PythonSource::SearchPath, path)))),
cache,
)
}
/// Iterate over all Python installations that satisfy the given request.
pub fn find_python_installations<'a>(
request: &'a PythonRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
cache: &'a Cache,
) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
match request {
PythonRequest::File(path) => Box::new(std::iter::once({
if preference.allows(PythonSource::ProvidedPath) {
debug!("Checking for Python interpreter at {request}");
match python_installation_from_executable(path, cache) {
Ok(installation) => Ok(FindPythonResult::Ok(installation)),
Err(InterpreterError::NotFound(_)) => {
Ok(FindPythonResult::Err(PythonNotFound {
request: request.clone(),
python_preference: preference,
environment_preference: environments,
}))
}
Err(err) => Err(Error::Query(
Box::new(err),
path.clone(),
PythonSource::ProvidedPath,
)),
}
} else {
Err(Error::SourceNotAllowed(
request.clone(),
PythonSource::ProvidedPath,
preference,
))
}
})),
PythonRequest::Directory(path) => Box::new(std::iter::once({
debug!("Checking for Python interpreter in {request}");
if preference.allows(PythonSource::ProvidedPath) {
debug!("Checking for Python interpreter at {request}");
match python_installation_from_directory(path, cache) {
Ok(installation) => Ok(FindPythonResult::Ok(installation)),
Err(InterpreterError::NotFound(_)) => {
Ok(FindPythonResult::Err(PythonNotFound {
request: request.clone(),
python_preference: preference,
environment_preference: environments,
}))
}
Err(err) => Err(Error::Query(
Box::new(err),
path.clone(),
PythonSource::ProvidedPath,
)),
}
} else {
Err(Error::SourceNotAllowed(
request.clone(),
PythonSource::ProvidedPath,
preference,
))
}
})),
PythonRequest::ExecutableName(name) => {
debug!("Searching for Python interpreter with {request}");
if preference.allows(PythonSource::SearchPath) {
debug!("Checking for Python interpreter at {request}");
Box::new(
python_interpreters_with_executable_name(name, cache)
.filter(move |result| {
result_satisfies_environment_preference(result, environments)
})
.map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
}),
)
} else {
Box::new(std::iter::once(Err(Error::SourceNotAllowed(
request.clone(),
PythonSource::SearchPath,
preference,
))))
}
}
PythonRequest::Any => Box::new({
debug!("Searching for any Python interpreter in {preference}");
python_interpreters(&VersionRequest::Any, None, environments, preference, cache).map(
|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
},
)
}),
PythonRequest::Default => Box::new({
debug!("Searching for default Python interpreter in {preference}");
python_interpreters(
&VersionRequest::Default,
None,
environments,
preference,
cache,
)
.map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
})
}),
PythonRequest::Version(version) => {
if let Err(err) = version.check_supported() {
return Box::new(std::iter::once(Err(Error::InvalidVersionRequest(err))));
};
Box::new({
debug!("Searching for {request} in {preference}");
python_interpreters(version, None, environments, preference, cache).map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
})
})
}
PythonRequest::Implementation(implementation) => Box::new({
debug!("Searching for a {request} interpreter in {preference}");
python_interpreters(
&VersionRequest::Default,
Some(implementation),
environments,
preference,
cache,
)
.filter(|result| match result {
Err(_) => true,
Ok((_source, interpreter)) => interpreter
.implementation_name()
.eq_ignore_ascii_case(implementation.into()),
})
.map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
})
}),
PythonRequest::ImplementationVersion(implementation, version) => {
if let Err(err) = version.check_supported() {
return Box::new(std::iter::once(Err(Error::InvalidVersionRequest(err))));
};
Box::new({
debug!("Searching for {request} in {preference}");
python_interpreters(
version,
Some(implementation),
environments,
preference,
cache,
)
.filter(|result| match result {
Err(_) => true,
Ok((_source, interpreter)) => interpreter
.implementation_name()
.eq_ignore_ascii_case(implementation.into()),
})
.map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
})
})
}
PythonRequest::Key(request) => {
if let Some(version) = request.version() {
if let Err(err) = version.check_supported() {
return Box::new(std::iter::once(Err(Error::InvalidVersionRequest(err))));
};
};
Box::new({
debug!("Searching for {request} in {preference}");
python_interpreters(
request.version().unwrap_or(&VersionRequest::Default),
request.implementation(),
environments,
preference,
cache,
)
.filter(|result| match result {
Err(_) => true,
Ok((_source, interpreter)) => request.satisfied_by_interpreter(interpreter),
})
.map(|result| {
result
.map(PythonInstallation::from_tuple)
.map(FindPythonResult::Ok)
})
})
}
}
}
/// Find a Python installation that satisfies the given request.
///
/// If an error is encountered while locating or inspecting a candidate installation,
/// the error will raised instead of attempting further candidates.
pub(crate) fn find_python_installation(
request: &PythonRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
cache: &Cache,
) -> Result<FindPythonResult, Error> {
let installations = find_python_installations(request, environments, preference, cache);
let mut first_prerelease = None;
for result in installations {
// Iterate until the first critical error or happy result
if !result.as_ref().err().map_or(true, Error::is_critical) {
continue;
}
// If it's an error, we're done.
let Ok(Ok(ref installation)) = result else {
return result;
};
// Check if we need to skip the interpreter because it is "not allowed", e.g., if it is a
// pre-release version or an alternative implementation, using it requires opt-in.
// If the interpreter has a default executable name, e.g. `python`, and was found on the
// search path, we consider this opt-in to use it.
let has_default_executable_name = installation.interpreter.has_default_executable_name()
&& installation.source == PythonSource::SearchPath;
// If it's a pre-release and pre-releases aren't allowed, skip it — but store it for later
// since we'll use a pre-release if no other versions are available.
if installation.python_version().pre().is_some()
&& !request.allows_prereleases()
&& !installation.source.allows_prereleases()
&& !has_default_executable_name
{
debug!("Skipping pre-release {}", installation.key());
if first_prerelease.is_none() {
first_prerelease = Some(installation.clone());
}
continue;
}
// If it's an alternative implementation and alternative implementations aren't allowed,
// skip it. Note we avoid querying these interpreters at all if they're on the search path
// and are not requested, but other sources such as the managed installations can include
// them.
if installation.is_alternative_implementation()
&& !request.allows_alternative_implementations()
&& !installation.source.allows_alternative_implementations()
&& !has_default_executable_name
{