Skip to main content

uv_python_commands/
list.rs

1use serde::Serialize;
2use std::collections::BTreeSet;
3use std::fmt::Write;
4use uv_configuration::PythonListFormat;
5use uv_pep440::Version;
6
7use anyhow::Result;
8use itertools::Either;
9use owo_colors::OwoColorize;
10use rustc_hash::FxHashSet;
11use uv_cache::Cache;
12use uv_client::BaseClientBuilder;
13use uv_fs::Simplified;
14use uv_python_discovery::find_all_python_installations;
15use uv_python_managed::downloads::{Error as PythonDownloadError, ManagedPythonDownloadList};
16use uv_python_types::{
17    EnvironmentPreference, PythonArchitecture, PythonDownloadRequest, PythonDownloads,
18    PythonPreference, PythonRequest, PythonSource,
19};
20use uv_settings::PythonInstallMirrors;
21
22use uv_command_support::ExitStatus;
23use uv_command_support::Printer;
24use uv_settings::PythonListKinds;
25
26#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
27enum Kind {
28    Download,
29    Managed,
30    System,
31}
32
33#[derive(Debug, Serialize)]
34struct NamedVersionParts {
35    major: u64,
36    minor: u64,
37    patch: u64,
38}
39
40#[derive(Debug, Serialize)]
41struct PrintData {
42    key: String,
43    version: Version,
44    version_parts: NamedVersionParts,
45    path: Option<String>,
46    symlink: Option<String>,
47    url: Option<String>,
48    os: String,
49    variant: String,
50    implementation: String,
51    arch: String,
52    libc: String,
53}
54
55/// List available Python installations.
56#[expect(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
57pub async fn list(
58    request: Option<String>,
59    kinds: PythonListKinds,
60    all_versions: bool,
61    all_platforms: bool,
62    all_arches: bool,
63    show_urls: bool,
64    output_format: PythonListFormat,
65    install_mirrors: PythonInstallMirrors,
66    python_preference: PythonPreference,
67    python_arch: Option<PythonArchitecture>,
68    python_downloads: PythonDownloads,
69    client_builder: &BaseClientBuilder<'_>,
70    cache: &Cache,
71    printer: Printer,
72) -> Result<ExitStatus> {
73    let python_arch = if all_platforms || all_arches {
74        None
75    } else {
76        python_arch
77    };
78    let request = request.as_deref().map(PythonRequest::parse);
79    let base_download_request = if python_preference == PythonPreference::OnlySystem {
80        None
81    } else {
82        // If the user request cannot be mapped to a download request, we won't show any downloads
83        PythonDownloadRequest::from_request(request.as_ref().unwrap_or(&PythonRequest::Any)).map(
84            |request| request.with_default_arch(python_arch.map(PythonArchitecture::into_inner)),
85        )
86    };
87
88    let download_request = if let Some(base_download_request) = base_download_request {
89        match kinds {
90            PythonListKinds::Installed => None,
91            PythonListKinds::Downloads => Some(if all_platforms {
92                base_download_request
93            } else if all_arches {
94                base_download_request.fill_platform()?.with_any_arch()
95            } else {
96                base_download_request.fill_platform()?
97            }),
98            PythonListKinds::Default => {
99                if python_downloads.is_automatic() {
100                    Some(if all_platforms {
101                        base_download_request
102                    } else if all_arches {
103                        base_download_request.fill_platform()?.with_any_arch()
104                    } else {
105                        base_download_request.fill_platform()?
106                    })
107                } else {
108                    // If fetching is not automatic, then don't show downloads as available by default
109                    None
110                }
111            }
112        }
113        // Include pre-release versions
114        .map(|request| request.with_prereleases(true))
115    } else {
116        None
117    };
118
119    let mut output = BTreeSet::new();
120    if let Some(download_request) = download_request {
121        let download_list = ManagedPythonDownloadList::new(
122            client_builder,
123            cache,
124            install_mirrors.python_downloads_json_url.as_deref(),
125        )
126        .await?;
127
128        let downloads = download_list
129            .iter_matching(&download_request)
130            // TODO(zanieb): Add a way to show debug downloads, we just hide them for now
131            .filter(|download| !download.key().variant().is_debug());
132
133        for download in downloads {
134            output.insert((
135                download.key().clone(),
136                Kind::Download,
137                Either::Right(
138                    download
139                        .download_urls(install_mirrors.mirrors())?
140                        .into_iter()
141                        .next()
142                        .ok_or(PythonDownloadError::NoPythonDownloadUrlFound)?,
143                ),
144            ));
145        }
146    }
147
148    let installed = match kinds {
149        PythonListKinds::Installed | PythonListKinds::Default => {
150            // While usually [`PythonPreference::OnlyManaged`] means we can skip searching the
151            // `PATH`, in `uv python list` we want to enumerate links to managed Python
152            // interpreters for inspection. Consequently, we widen the preference here and
153            // perform post-filtering.
154            let discovery_preference = if python_preference == PythonPreference::OnlyManaged {
155                PythonPreference::Managed
156            } else {
157                python_preference
158            };
159            let mut installations = find_all_python_installations(
160                request.as_ref().unwrap_or(&PythonRequest::Any),
161                EnvironmentPreference::OnlySystem,
162                discovery_preference,
163                python_arch,
164                cache,
165            )?;
166            // Apply the original `PythonPreference` to discovered interpreters, since we may
167            // have expanded it above.
168            installations
169                .retain(|installation| installation.satisfies_preference(&python_preference));
170            Some(installations)
171        }
172        PythonListKinds::Downloads => None,
173    };
174
175    if let Some(installed) = installed {
176        for installation in installed {
177            let kind = if matches!(installation.source(), PythonSource::Managed) {
178                Kind::Managed
179            } else {
180                Kind::System
181            };
182            output.insert((
183                installation.key(),
184                kind,
185                Either::Left(installation.interpreter().real_executable().to_path_buf()),
186            ));
187        }
188    }
189
190    let mut seen_minor = FxHashSet::default();
191    let mut seen_patch = FxHashSet::default();
192    let mut seen_paths = FxHashSet::default();
193    let mut include = Vec::new();
194    for (key, kind, uri) in output.iter().rev() {
195        // Do not show the same path more than once
196        if let Either::Left(path) = uri {
197            if !seen_paths.insert(path) {
198                continue;
199            }
200        }
201
202        // Only show the latest patch version for each download unless all were requested.
203        //
204        // We toggle off platforms/arches based unless all_platforms/all_arches because
205        // we want to only show the "best" option for each version by default, even
206        // if e.g. the x86_32 build would also work on x86_64.
207        if !matches!(kind, Kind::System) {
208            if let [major, minor, ..] = *key.version().release() {
209                if !seen_minor.insert((
210                    all_platforms.then_some(*key.os()),
211                    major,
212                    minor,
213                    key.variant(),
214                    key.implementation(),
215                    all_arches.then_some(*key.arch()),
216                    *key.libc(),
217                )) {
218                    if matches!(kind, Kind::Download) && !all_versions {
219                        continue;
220                    }
221                }
222            }
223            if let [major, minor, patch] = *key.version().release() {
224                if !seen_patch.insert((
225                    all_platforms.then_some(*key.os()),
226                    major,
227                    minor,
228                    patch,
229                    key.variant(),
230                    key.implementation(),
231                    all_arches.then_some(*key.arch()),
232                    key.libc(),
233                )) {
234                    if matches!(kind, Kind::Download) {
235                        continue;
236                    }
237                }
238            }
239        }
240        include.push((key, uri));
241    }
242
243    match output_format {
244        PythonListFormat::Json => {
245            let data = include
246                .iter()
247                .map(|(key, uri)| -> Result<_> {
248                    let mut path_or_none: Option<String> = None;
249                    let mut symlink_or_none: Option<String> = None;
250                    let mut url_or_none: Option<String> = None;
251                    match uri {
252                        Either::Left(path) => {
253                            path_or_none = Some(path.user_display().to_string());
254
255                            let is_symlink = fs_err::symlink_metadata(path)?.is_symlink();
256                            if is_symlink {
257                                symlink_or_none =
258                                    Some(path.read_link()?.user_display().to_string());
259                            }
260                        }
261                        Either::Right(url) => {
262                            url_or_none = Some((*url).to_string());
263                        }
264                    }
265                    let version = key.version();
266                    let release = version.release();
267
268                    Ok(PrintData {
269                        key: key.to_string(),
270                        version: version.version().clone(),
271                        #[expect(clippy::get_first)]
272                        version_parts: NamedVersionParts {
273                            major: release.get(0).copied().unwrap_or(0),
274                            minor: release.get(1).copied().unwrap_or(0),
275                            patch: release.get(2).copied().unwrap_or(0),
276                        },
277                        path: path_or_none,
278                        symlink: symlink_or_none,
279                        url: url_or_none,
280                        arch: key.arch().to_string(),
281                        implementation: key.implementation().to_string(),
282                        os: key.os().to_string(),
283                        variant: key.variant().to_string(),
284                        libc: key.libc().to_string(),
285                    })
286                })
287                .collect::<Result<Vec<_>>>()?;
288            writeln!(printer.stdout(), "{}", serde_json::to_string(&data)?)?;
289        }
290        PythonListFormat::Text => {
291            // Compute the width of the first column.
292            let width = include
293                .iter()
294                .fold(0usize, |acc, (key, _)| acc.max(key.to_string().len()));
295
296            for (key, uri) in include {
297                let key = key.to_string();
298                match uri {
299                    Either::Left(path) => {
300                        let is_symlink = fs_err::symlink_metadata(path)?.is_symlink();
301                        if is_symlink {
302                            writeln!(
303                                printer.stdout(),
304                                "{key:width$}    {} -> {}",
305                                path.user_display().cyan(),
306                                path.read_link()?.user_display().cyan()
307                            )?;
308                        } else {
309                            writeln!(
310                                printer.stdout(),
311                                "{key:width$}    {}",
312                                path.user_display().cyan()
313                            )?;
314                        }
315                    }
316                    Either::Right(url) => {
317                        if show_urls {
318                            writeln!(printer.stdout(), "{key:width$}    {}", url.dimmed())?;
319                        } else {
320                            writeln!(
321                                printer.stdout(),
322                                "{key:width$}    {}",
323                                "<download available>".dimmed()
324                            )?;
325                        }
326                    }
327                }
328            }
329        }
330    }
331
332    Ok(ExitStatus::Success)
333}