Skip to main content

uv_python_commands/
find.rs

1use anyhow::Result;
2use std::fmt::Write;
3use std::path::Path;
4
5use uv_cache::Cache;
6use uv_client::BaseClientBuilder;
7use uv_configuration::{ActiveEnvironment, DependencyGroupsWithDefaults};
8use uv_errors::ErrorWithHints;
9use uv_fs::Simplified;
10use uv_python_discovery::ConfigDiscovery;
11use uv_python_discovery::PythonInstallation;
12use uv_python_types::{
13    EnvironmentPreference, PythonArchitecture, PythonDownloads, PythonPreference, PythonRequest,
14};
15use uv_scripts::Pep723ItemRef;
16use uv_settings::PythonInstallMirrors;
17use uv_warnings::{warn_user, warn_user_once_with_chain};
18use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache, WorkspaceErrorKind};
19
20use uv_command_support::ExitStatus;
21use uv_command_support::Printer;
22use uv_python_discovery::ProjectPythonRequest;
23use uv_python_discovery::ScriptInterpreter;
24
25/// Find a Python interpreter.
26#[expect(clippy::fn_params_excessive_bools)]
27pub async fn find(
28    project_dir: &Path,
29    request: Option<String>,
30    show_version: bool,
31    resolve_links: bool,
32    no_project: bool,
33    system: bool,
34    config_discovery: ConfigDiscovery,
35    python_preference: PythonPreference,
36    python_arch: Option<PythonArchitecture>,
37    python_downloads_json_url: Option<&str>,
38    client_builder: &BaseClientBuilder<'_>,
39    cache: &Cache,
40    workspace_cache: &WorkspaceCache,
41    printer: Printer,
42) -> Result<ExitStatus> {
43    let environment_preference = if system {
44        EnvironmentPreference::OnlySystem
45    } else {
46        EnvironmentPreference::Any
47    };
48
49    let project = if no_project {
50        None
51    } else {
52        match VirtualProject::discover(
53            project_dir,
54            &DiscoveryOptions::default(),
55            cache,
56            workspace_cache,
57        )
58        .await
59        {
60            Ok(project) => Some(project),
61            Err(err) => {
62                // Ignore missing or unmanaged workspaces in Python discovery.
63                if !matches!(
64                    err.as_ref(),
65                    WorkspaceErrorKind::MissingProject(_)
66                        | WorkspaceErrorKind::MissingPyprojectToml
67                        | WorkspaceErrorKind::NonWorkspace(_)
68                ) {
69                    warn_user_once_with_chain!(&err);
70                }
71                None
72            }
73        }
74    };
75
76    // Don't enable the requires-python settings on groups
77    let groups = DependencyGroupsWithDefaults::none();
78    let project_python = ProjectPythonRequest::from_request(
79        request.map(|request| PythonRequest::parse(&request)),
80        project.as_ref().map(VirtualProject::workspace),
81        &groups,
82        project_dir,
83        config_discovery,
84    )
85    .await?;
86
87    let python_request = project_python
88        .python_request
89        .as_ref()
90        .unwrap_or(&PythonRequest::Default);
91    let python = PythonInstallation::find_existing(
92        python_request,
93        environment_preference,
94        python_preference,
95        python_arch,
96        cache,
97    )?;
98    python
99        .download_and_warn_if_outdated_prerelease(
100            python_request,
101            client_builder,
102            cache,
103            python_downloads_json_url,
104        )
105        .await?;
106
107    // Warn if the discovered Python version is incompatible with the current workspace
108    if let Err(err) = project_python.check(python.interpreter()) {
109        warn_user!("{err}");
110    }
111
112    if show_version {
113        writeln!(
114            printer.stdout(),
115            "{}",
116            python.interpreter().python_version()
117        )?;
118    } else {
119        let path = if resolve_links {
120            dunce::canonicalize(python.interpreter().sys_executable())?
121        } else {
122            std::path::absolute(python.interpreter().sys_executable())?
123        };
124        writeln!(printer.stdout(), "{}", path.simplified_display())?;
125    }
126
127    Ok(ExitStatus::Success)
128}
129
130pub async fn find_script(
131    script: Pep723ItemRef<'_>,
132    show_version: bool,
133    resolve_links: bool,
134    client_builder: &BaseClientBuilder<'_>,
135    python_preference: PythonPreference,
136    python_arch: Option<PythonArchitecture>,
137    python_downloads: PythonDownloads,
138    config_discovery: ConfigDiscovery,
139    cache: &Cache,
140    printer: Printer,
141) -> Result<ExitStatus> {
142    let interpreter = match ScriptInterpreter::discover(
143        script,
144        None,
145        client_builder,
146        python_preference,
147        python_arch,
148        python_downloads,
149        &PythonInstallMirrors::default(),
150        false,
151        config_discovery,
152        ActiveEnvironment::Ignore,
153        cache,
154        printer,
155    )
156    .await
157    {
158        Err(error) => {
159            writeln!(
160                printer.stderr(),
161                "{}",
162                ErrorWithHints::new(&error, uv_errors::Hinted::hints(&error))
163            )?;
164            return Ok(ExitStatus::Failure);
165        }
166        Ok(ScriptInterpreter::Interpreter(selection)) => selection.into_interpreter(),
167        Ok(ScriptInterpreter::Environment(environment)) => environment.into_interpreter(),
168    };
169
170    if show_version {
171        writeln!(printer.stdout(), "{}", interpreter.python_version())?;
172    } else {
173        let path = if resolve_links {
174            dunce::canonicalize(interpreter.sys_executable())?
175        } else {
176            std::path::absolute(interpreter.sys_executable())?
177        };
178        writeln!(printer.stdout(), "{}", path.simplified_display())?;
179    }
180
181    Ok(ExitStatus::Success)
182}