Skip to main content

uv_python_discovery/
script.rs

1//! Interpreter discovery for PEP 723 scripts and environment compatibility.
2
3use std::path::{Path, PathBuf};
4
5use crate::ConfigDiscovery;
6use crate::PythonInstallation;
7use crate::PythonVersionFile;
8use crate::VersionFileDiscoveryOptions;
9use tracing::{debug, trace, warn};
10use uv_cache::{Cache, CacheBucket};
11use uv_cache_key::{cache_digest, cache_name};
12use uv_client::BaseClientBuilder;
13use uv_command_support::Printer;
14use uv_configuration::ActiveEnvironment;
15use uv_distribution_types::RequiresPython;
16use uv_fs::{CWD, Simplified};
17use uv_pep440::Version;
18use uv_python_interpreter::{Interpreter, PythonEnvironment, RequestedInterpreter};
19use uv_python_types::{
20    EnvironmentPreference, PythonArchitecture, PythonDownloads, PythonPreference, PythonRequest,
21    PythonSource, PythonVariant, VersionRequest,
22};
23use uv_scripts::Pep723ItemRef;
24use uv_settings::PythonInstallMirrors;
25use uv_static::EnvVars;
26use uv_warnings::{warn_user, warn_user_once};
27
28use crate::PythonDownloadReporter;
29use crate::PythonRequestSource;
30use crate::PythonSelectionError;
31
32/// Determine the [`RequiresPython`] requirement for a new PEP 723 script.
33pub async fn init_script_python_requirement(
34    python: Option<&str>,
35    install_mirrors: &PythonInstallMirrors,
36    directory: &Path,
37    no_pin_python: bool,
38    python_preference: PythonPreference,
39    python_arch: Option<PythonArchitecture>,
40    python_downloads: PythonDownloads,
41    config_discovery: ConfigDiscovery,
42    client_builder: &BaseClientBuilder<'_>,
43    cache: &Cache,
44    reporter: &PythonDownloadReporter,
45) -> Result<RequiresPython, PythonSelectionError> {
46    let python_request = if let Some(request) = python {
47        // (1) Explicit request from user
48        Some(PythonRequest::parse(request))
49    } else if let (false, Some(request)) = (
50        no_pin_python,
51        PythonVersionFile::discover(
52            directory,
53            &VersionFileDiscoveryOptions::default().with_config_discovery(config_discovery),
54        )
55        .await?
56        .and_then(PythonVersionFile::into_version),
57    ) {
58        // (2) Request from `.python-version`
59        Some(request)
60    } else {
61        // (3) No explicit request
62        None
63    };
64
65    let interpreter = PythonInstallation::find_or_download(
66        python_request.as_ref(),
67        EnvironmentPreference::Any,
68        python_preference,
69        python_arch,
70        python_downloads,
71        client_builder,
72        cache,
73        Some(reporter),
74        install_mirrors.mirrors(),
75        install_mirrors.python_downloads_json_url.as_deref(),
76    )
77    .await?
78    .into_interpreter();
79
80    Ok(RequiresPython::greater_than_equal_version(
81        &interpreter.python_minor_version(),
82    ))
83}
84
85/// Returns an error if the [`Interpreter`] does not satisfy the script's `requires-python`.
86fn validate_script_requires_python(
87    interpreter: &Interpreter,
88    requires_python: &RequiresPython,
89    source: &PythonRequestSource,
90) -> Result<(), PythonSelectionError> {
91    if requires_python.contains(interpreter.python_version()) {
92        return Ok(());
93    }
94    match source {
95        PythonRequestSource::UserRequest => {
96            Err(PythonSelectionError::RequestedPythonScriptIncompatibility(
97                interpreter.python_version().clone(),
98                requires_python.clone(),
99            ))
100        }
101        PythonRequestSource::DotPythonVersion(file) => {
102            Err(PythonSelectionError::DotPythonVersionScriptIncompatibility(
103                file.file_name().to_string(),
104                interpreter.python_version().clone(),
105                requires_python.clone(),
106            ))
107        }
108        PythonRequestSource::RequiresPython => {
109            Err(PythonSelectionError::RequiresPythonScriptIncompatibility(
110                interpreter.python_version().clone(),
111                requires_python.clone(),
112            ))
113        }
114    }
115}
116
117/// An interpreter suitable for a PEP 723 script.
118#[derive(Debug, Clone)]
119#[expect(clippy::large_enum_variant)]
120pub enum ScriptInterpreter {
121    /// An interpreter to use to create a new script environment.
122    Interpreter(RequestedInterpreter),
123    /// An interpreter from an existing script environment.
124    Environment(PythonEnvironment),
125}
126
127impl ScriptInterpreter {
128    /// Return the expected virtual environment path for the [`Pep723ItemRef`].
129    ///
130    /// If `--active` is set, the active virtual environment will be preferred.
131    ///
132    /// See: [`uv_workspace::Workspace::environment_selection`].
133    pub fn root(script: Pep723ItemRef<'_>, active: ActiveEnvironment, cache: &Cache) -> PathBuf {
134        /// Resolve the `VIRTUAL_ENV` variable, if any.
135        fn from_virtual_env_variable() -> Option<PathBuf> {
136            let value = std::env::var_os(EnvVars::VIRTUAL_ENV)?;
137
138            if value.is_empty() {
139                return None;
140            }
141
142            let path = PathBuf::from(value);
143            if path.is_absolute() {
144                return Some(path);
145            }
146
147            // Resolve the path relative to current directory.
148            Some(CWD.join(path))
149        }
150
151        // Determine the stable path to the script environment in the cache.
152        let cache_env = {
153            let entry = match script {
154                // For local scripts, use a hash of the path to the script.
155                Pep723ItemRef::Script(script) => {
156                    let digest = cache_digest(&script.path);
157                    if let Some(file_name) = script
158                        .path
159                        .file_stem()
160                        .and_then(|name| name.to_str())
161                        .and_then(|name| cache_name(name, Some(100)))
162                    {
163                        format!("{file_name}-{digest}")
164                    } else {
165                        digest
166                    }
167                }
168                // For remote scripts, use a hash of the URL.
169                Pep723ItemRef::Remote(.., url) => cache_digest(url),
170                // Otherwise, use a hash of the metadata.
171                Pep723ItemRef::Stdin(metadata) => cache_digest(&metadata.raw),
172            };
173
174            cache
175                .shard(CacheBucket::Environments, entry)
176                .into_path_buf()
177        };
178
179        // If `--active` is set, prefer the active virtual environment.
180        if let Some(from_virtual_env) = from_virtual_env_variable() {
181            if !uv_fs::is_same_file_allow_missing(&from_virtual_env, &cache_env).unwrap_or(false) {
182                match active {
183                    ActiveEnvironment::Prefer => {
184                        debug!(
185                            "Using active virtual environment `{}` instead of script environment `{}`",
186                            from_virtual_env.user_display(),
187                            cache_env.user_display()
188                        );
189                        return from_virtual_env;
190                    }
191                    ActiveEnvironment::Ignore => {}
192                    ActiveEnvironment::Warn => {
193                        warn_user_once!(
194                            "`VIRTUAL_ENV={}` does not match the script environment path `{}` and will be ignored; use `--active` to target the active environment instead",
195                            from_virtual_env.user_display(),
196                            cache_env.user_display()
197                        );
198                    }
199                }
200            }
201        } else {
202            if active == ActiveEnvironment::Prefer {
203                debug!(
204                    "Use of the active virtual environment was requested, but `VIRTUAL_ENV` is not set"
205                );
206            }
207        }
208
209        // Otherwise, use the cache root.
210        cache_env
211    }
212
213    /// Discover an existing script environment without selecting or downloading an interpreter.
214    pub fn discover_existing(
215        script: Pep723ItemRef<'_>,
216        active: ActiveEnvironment,
217        cache: &Cache,
218    ) -> Option<PythonEnvironment> {
219        let root = Self::root(script, active, cache);
220        match PythonEnvironment::from_root(&root, cache) {
221            Ok(environment) => Some(environment),
222            Err(uv_python_interpreter::PythonEnvironmentError::MissingEnvironment(_)) => None,
223            Err(err) => {
224                warn!("Ignoring existing script environment: {err}");
225                None
226            }
227        }
228    }
229
230    /// Discover the interpreter to use for the current [`Pep723ItemRef`].
231    pub async fn discover(
232        script: Pep723ItemRef<'_>,
233        python_request: Option<PythonRequest>,
234        client_builder: &BaseClientBuilder<'_>,
235        python_preference: PythonPreference,
236        python_arch: Option<PythonArchitecture>,
237        python_downloads: PythonDownloads,
238        install_mirrors: &PythonInstallMirrors,
239        keep_incompatible: bool,
240        config_discovery: ConfigDiscovery,
241        active: ActiveEnvironment,
242        cache: &Cache,
243        printer: Printer,
244    ) -> Result<Self, PythonSelectionError> {
245        let ScriptPython {
246            source,
247            python_request,
248            requires_python,
249        } = ScriptPython::from_request(python_request, script, config_discovery).await?;
250
251        if let Some(environment) = Self::discover_existing(script, active, cache) {
252            match check_environment_compatibility(
253                &environment,
254                EnvironmentKind::Script,
255                python_request.as_ref(),
256                python_preference,
257                python_arch,
258                requires_python.as_ref(),
259                cache,
260            ) {
261                Ok(()) => return Ok(Self::Environment(environment)),
262                Err(err) if keep_incompatible => {
263                    warn_user!(
264                        "Using incompatible environment (`{}`) due to `--no-sync` ({err})",
265                        environment.root().user_display().cyan(),
266                    );
267                    return Ok(Self::Environment(environment));
268                }
269                Err(err) => {
270                    debug!("{err}");
271                }
272            }
273        }
274
275        let reporter = PythonDownloadReporter::single(printer);
276
277        let interpreter = PythonInstallation::find_or_download(
278            python_request.as_ref(),
279            EnvironmentPreference::Any,
280            python_preference,
281            python_arch,
282            python_downloads,
283            client_builder,
284            cache,
285            Some(&reporter),
286            install_mirrors.mirrors(),
287            install_mirrors.python_downloads_json_url.as_deref(),
288        )
289        .await?
290        .into_interpreter();
291
292        if let Some(requires_python) = requires_python
293            && let Err(err) =
294                validate_script_requires_python(&interpreter, &requires_python, &source)
295        {
296            warn_user!("{err}");
297        }
298
299        Ok(Self::Interpreter(RequestedInterpreter::new(
300            interpreter,
301            python_request.unwrap_or_default(),
302        )))
303    }
304
305    /// Consume the script selection and return its [`Interpreter`].
306    pub fn into_interpreter(self) -> Interpreter {
307        match self {
308            Self::Interpreter(requested) => requested.into_interpreter(),
309            Self::Environment(venv) => venv.into_interpreter(),
310        }
311    }
312}
313
314#[derive(Debug)]
315pub enum EnvironmentKind {
316    Script,
317    Project,
318}
319
320impl std::fmt::Display for EnvironmentKind {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        match self {
323            Self::Script => write!(f, "script"),
324            Self::Project => write!(f, "project"),
325        }
326    }
327}
328
329#[derive(Debug, thiserror::Error)]
330pub enum EnvironmentIncompatibilityError {
331    #[error("The {0} environment's Python version does not satisfy the request: `{1}`")]
332    PythonRequest(EnvironmentKind, PythonRequest),
333
334    #[error("The {0} environment's Python version does not meet the Python requirement: `{1}`")]
335    RequiresPython(EnvironmentKind, RequiresPython),
336
337    #[error(
338        "The interpreter in the {0} environment has a different version ({1}) than it was created with ({2})"
339    )]
340    PyenvVersionConflict(EnvironmentKind, Version, Version),
341
342    #[error("The {0} environment's Python interpreter does not meet the Python preference: `{1}`")]
343    PythonPreference(EnvironmentKind, PythonPreference),
344}
345
346/// Check whether an environment satisfies the requested Python constraints.
347pub fn check_environment_compatibility(
348    environment: &PythonEnvironment,
349    kind: EnvironmentKind,
350    python_request: Option<&PythonRequest>,
351    python_preference: PythonPreference,
352    python_arch: Option<PythonArchitecture>,
353    requires_python: Option<&RequiresPython>,
354    cache: &Cache,
355) -> Result<(), EnvironmentIncompatibilityError> {
356    if let Some((cfg_version, int_version)) = environment.get_pyvenv_version_conflict() {
357        return Err(EnvironmentIncompatibilityError::PyenvVersionConflict(
358            kind,
359            int_version,
360            cfg_version,
361        ));
362    }
363
364    let python_request = python_request
365        .or_else(|| python_arch.map(|_| &PythonRequest::Any))
366        .map(|request| request.with_default_arch(python_arch.map(PythonArchitecture::into_inner)));
367    if let Some(request) = python_request {
368        if environment.interpreter().matches_request(&request, cache) {
369            debug!("The {kind} environment's Python version satisfies the request: `{request}`");
370        } else {
371            return Err(EnvironmentIncompatibilityError::PythonRequest(
372                kind,
373                request.into_owned(),
374            ));
375        }
376    }
377
378    if let Some(requires_python) = requires_python {
379        if requires_python.contains(environment.interpreter().python_version()) {
380            trace!(
381                "The {kind} environment's Python version meets the Python requirement: `{requires_python}`"
382            );
383        } else {
384            return Err(EnvironmentIncompatibilityError::RequiresPython(
385                kind,
386                requires_python.clone(),
387            ));
388        }
389    }
390
391    if PythonInstallation::new(
392        PythonSource::DiscoveredEnvironment,
393        environment.interpreter().clone(),
394    )
395    .satisfies_preference(&python_preference)
396    {
397        trace!(
398            "The virtual environment's Python interpreter meets the Python preference: `{}`",
399            python_preference
400        );
401    } else {
402        return Err(EnvironmentIncompatibilityError::PythonPreference(
403            kind,
404            python_preference,
405        ));
406    }
407
408    Ok(())
409}
410
411/// The resolved Python request and requirement for a [`Pep723ItemRef`].
412#[derive(Debug, Clone)]
413struct ScriptPython {
414    /// The source of the Python request.
415    source: PythonRequestSource,
416    /// The resolved Python request, computed by considering (1) any explicit request from the user
417    /// via `--python`, (2) any implicit request from the user via `.python-version`, (3) any
418    /// `Requires-Python` specifier in the script metadata.
419    python_request: Option<PythonRequest>,
420    /// The resolved Python requirement for the script.
421    requires_python: Option<RequiresPython>,
422}
423
424impl ScriptPython {
425    /// Determine the [`ScriptPython`] for the current [`Pep723ItemRef`].
426    async fn from_request(
427        python_request: Option<PythonRequest>,
428        script: Pep723ItemRef<'_>,
429        config_discovery: ConfigDiscovery,
430    ) -> Result<Self, PythonSelectionError> {
431        let requires_python = script
432            .metadata()
433            .requires_python
434            .as_ref()
435            .map(|specifiers| RequiresPython::from_specifiers(specifiers.clone()));
436
437        let project_dir = script.path().and_then(Path::parent).unwrap_or(&**CWD);
438
439        let (source, python_request) = if let Some(request) = python_request {
440            // (1) Explicit request from user
441            (PythonRequestSource::UserRequest, Some(request))
442        } else if let Some(file) = PythonVersionFile::discover(
443            project_dir,
444            &VersionFileDiscoveryOptions::default().with_config_discovery(config_discovery),
445        )
446        .await?
447        .filter(|file| {
448            // Ignore version files that are incompatible with the script's `requires-python`
449            match (file.version(), requires_python.as_ref()) {
450                (Some(request), Some(requires_python)) => {
451                    request.intersects_specifiers(requires_python.specifiers())
452                }
453                _ => true,
454            }
455        }) {
456            // (2) Request from `.python-version`
457            (
458                PythonRequestSource::DotPythonVersion(file.clone()),
459                file.version().cloned(),
460            )
461        } else if let Some(specifiers) = script.metadata().requires_python.as_ref() {
462            // (3) `requires-python` from script metadata
463            let request = PythonRequest::Version(VersionRequest::from_specifiers(
464                specifiers.clone(),
465                PythonVariant::Default,
466            ));
467            (PythonRequestSource::RequiresPython, Some(request))
468        } else {
469            // (4) No Python request or requirement.
470            (PythonRequestSource::RequiresPython, None)
471        };
472
473        if let Some(python_request) = python_request.as_ref() {
474            debug!(
475                "Using Python request `{}` from {source}",
476                python_request.to_canonical_string()
477            );
478        }
479
480        Ok(Self {
481            source,
482            python_request,
483            requires_python,
484        })
485    }
486}