diff --git a/crates/ide-host/src/ops/dependencies.rs b/crates/ide-host/src/ops/dependencies.rs index a97e0344e1..3de1d6ec23 100644 --- a/crates/ide-host/src/ops/dependencies.rs +++ b/crates/ide-host/src/ops/dependencies.rs @@ -4,7 +4,7 @@ use ide_command::command; use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId}; use ide_workspace::dependencies::{ DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm, - python, + pypi, python, }; use std::collections::BTreeMap; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -301,6 +301,35 @@ pub async fn python_requirements( result } +/// A project on pypi.org by its exact name; `None` when PyPI has no such project. +#[command(trust = outside_restricted)] +pub async fn pypi_package( + host: &Host, + window: &str, + name: String, + request: RequestId, +) -> IdeResult> { + let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?; + let cancel = host.begin_project_read_request(window, request); + let result = host + .blocking(move || { + let search_path = std::env::var_os("PATH").unwrap_or_default(); + let text = ide_tools::Http::new(&search_path)?.https_only().get_text_limited_or_empty_on_404( + &url, + 16 * 1024 * 1024, + &cancel, + )?; + // The helper's body for a 404. + if text == "[]" { + return Ok(None); + } + pypi::parse_project(&text).map(Some).ok_or_else(|| IdeError::internal("invalid PyPI response")) + }) + .await; + host.end_request(request); + result +} + #[cfg(test)] mod tests { use super::*; @@ -458,4 +487,4 @@ mod tests { } } -ide_command::domain!(dependencies: dependency_versions, python_requirements); +ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package); diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index 000dee44bc..bd341da42f 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -435,6 +435,26 @@ pub async fn sdk_python_packages( result? } +/// A package index other than PyPI that installing from `python` uses; `None` for PyPI. +#[command(trust = outside_restricted)] +pub async fn sdk_python_package_index( + host: &Host, + window: &str, + python: PathBuf, + request: RequestId, +) -> IdeResult> { + host.require_trust_if_project(window)?; + let project_root = host.project(window).ok().map(|p| p.root.clone()); + let cancel = host.begin_project_request(window, request); + let result = tokio::task::spawn_blocking(move || { + ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel) + }) + .await + .map_err(join_err); + host.end_request(request); + result? +} + /// Installs (`uninstall = false`) or removes a package; output streams through `on_output`. #[allow(clippy::too_many_arguments)] #[command(trust = outside_restricted)] @@ -679,6 +699,7 @@ ide_command::domain!( sdk_python_hatch_envs, sdk_python_interpreter, sdk_python_packages, + sdk_python_package_index, sdk_python_pip, sdk_python_project_interpreters, sdk_python_sys_path, diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index 2e4525afd6..dee3b1a579 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -579,6 +579,35 @@ pub(crate) fn resolve_requirement(requirement: &str, base: Option<&Path>) -> Ide Ok(base.join(requirement).to_string_lossy().into_owned()) } +/// Environments with a pip run in progress, by [`environment_key`]. +static BUSY: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds an environment for one pip run; two runs at once can leave it half installed. +pub(crate) struct Busy(PathBuf); + +impl Busy { + pub(crate) fn take(python: &Path) -> IdeResult { + let key = environment_key(python); + let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner()); + if busy.contains(&key) { + return Err(IdeError::unavailable("another package operation is running for this interpreter")); + } + busy.push(key.clone()); + Ok(Self(key)) + } +} + +impl Drop for Busy { + fn drop(&mut self) { + BUSY.lock().unwrap_or_else(|e| e.into_inner()).retain(|k| *k != self.0); + } +} + +/// A virtualenv's folder (its `python` and `python3` are one environment), else the interpreter. +fn environment_key(python: &Path) -> PathBuf { + venv_of(python).unwrap_or_else(|| python.to_path_buf()) +} + /// Installs (or upgrades, with `upgrade`) a requirement such as `requests` or `django==5.0`; /// relative paths (`./pkg`) are resolved against `project_root`. pub fn install_package( @@ -595,6 +624,7 @@ pub fn install_package( } let requirement = resolve_requirement(requirement, project_root)?; let installer = installer(python)?; + let _busy = Busy::take(python)?; let mut sub = vec!["install"]; if upgrade { sub.push("--upgrade"); @@ -692,7 +722,91 @@ pub fn uninstall_package( return Err(IdeError::invalid("no package selected")); } let installer = installer(python)?; + let _busy = Busy::take(python)?; let (program, args) = pip_command(python, &installer, &["uninstall", "-y", name]); let dir = neutral_dir(); stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ()) } + +/// A package index other than PyPI that installing from `python` uses, as configured for pip +/// (`pip config list`, `PIP_INDEX_URL`, `PIP_EXTRA_INDEX_URL`) or for uv (its environment +/// variables, `uv.toml`, `[tool.uv]` in the project's `pyproject.toml`). Package names should +/// then not be sent to PyPI unasked: a private package may have a public namesake. +pub fn configured_index( + python: &Path, + project_root: Option<&Path>, + cancel: &CancellationToken, +) -> IdeResult> { + let env = |key: &str| std::env::var(key).ok().and_then(|v| custom_index_url(&v).map(str::to_owned)); + for key in ["PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"] { + if let Some(url) = env(key) { + return Ok(Some(url)); + } + } + match installer(python)? { + Installer::Pip => { + let (program, args) = pip_command(python, &Installer::Pip, &["config", "list"]); + let dir = neutral_dir(); + let out = stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, &|_| {})?; + Ok(pip_config_index(&out)) + } + Installer::Uv(_) => { + for key in ["UV_INDEX_URL", "UV_EXTRA_INDEX_URL", "UV_DEFAULT_INDEX", "UV_INDEX"] { + if let Some(url) = env(key) { + return Ok(Some(url)); + } + } + let mut files: Vec = Vec::new(); + if let Some(root) = project_root { + files.push(root.join("uv.toml")); + files.push(root.join("pyproject.toml")); + } + if let Some(config) = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| dirs::home_dir().map(|h| h.join(".config"))) + { + files.push(config.join("uv/uv.toml")); + } + if let Some(config) = dirs::config_dir() { + files.push(config.join("uv/uv.toml")); + } + files.push(PathBuf::from("/etc/uv/uv.toml")); + Ok(files.iter().find_map(|f| uv_config_index(f.file_name()?.to_str()?, &std::fs::read_to_string(f).ok()?))) + } + } +} + +fn custom_index_url(value: &str) -> Option<&str> { + value.split_whitespace().find(|value| { + !url::Url::parse(value) + .is_ok_and(|url| url.scheme() == "https" && matches!(url.host_str(), Some("pypi.org" | "pypi.python.org"))) + }) +} + +/// The first non-PyPI `index-url` / `extra-index-url` in `pip config list` output +/// (`global.index-url='https://…'`, `:env:.extra-index-url='…'`). +pub(crate) fn pip_config_index(out: &str) -> Option { + out.lines().find_map(|line| { + let (key, value) = line.split_once('=')?; + if !key.ends_with(".index-url") && !key.ends_with(".extra-index-url") { + return None; + } + custom_index_url(value.trim().trim_matches(['\'', '"'])).map(str::to_owned) + }) +} + +/// An index configured in a uv config file: `index-url`, `extra-index-url` or `[[index]]` +/// in `uv.toml`, the same under `[tool.uv]` in `pyproject.toml`. +pub(crate) fn uv_config_index(file_name: &str, text: &str) -> Option { + let doc: toml::Table = text.parse().ok()?; + let uv = if file_name == "pyproject.toml" { doc.get("tool")?.get("uv")?.as_table()? } else { &doc }; + let extras = uv.get("extra-index-url").and_then(toml::Value::as_array); + let indexes = uv.get("index").and_then(toml::Value::as_array); + uv.get("index-url") + .into_iter() + .chain(extras.into_iter().flatten()) + .chain(indexes.into_iter().flatten().filter_map(|index| index.get("url"))) + .filter_map(toml::Value::as_str) + .find_map(custom_index_url) + .map(str::to_owned) +} diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 786fcb0859..b30c52b5e0 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -3505,3 +3505,67 @@ fn unsatisfied_requirements_are_judged_by_the_interpreter() { let old = packaging.then(|| crate::python::Unsatisfied { installed: Some("1.0".into()) }); assert_eq!(found, [None, None, old, missing(), None]); } + +#[test] +fn a_custom_package_index_is_found_in_pip_and_uv_configuration() { + use crate::python::{pip_config_index, uv_config_index}; + assert_eq!( + pip_config_index( + "$ python -m pip config list\nglobal.timeout='60'\nglobal.index-url='https://pypi.acme.dev/simple'\n" + ) + .as_deref(), + Some("https://pypi.acme.dev/simple") + ); + assert_eq!( + pip_config_index(":env:.extra-index-url='https://a.example/simple https://b.example/simple'\n").as_deref(), + Some("https://a.example/simple") + ); + assert_eq!( + pip_config_index( + "global.index-url='https://pypi.org/simple'\ninstall.extra-index-url='https://pypi.python.org/simple https://a.example/simple'\n" + ) + .as_deref(), + Some("https://a.example/simple") + ); + assert_eq!( + pip_config_index("global.index-url='https://a.example/https://pypi.org/simple'\n").as_deref(), + Some("https://a.example/https://pypi.org/simple") + ); + assert_eq!(pip_config_index("global.timeout='60'\n"), None); + assert_eq!( + uv_config_index("uv.toml", "index-url = \"https://pypi.acme.dev/simple\"\n").as_deref(), + Some("https://pypi.acme.dev/simple") + ); + assert_eq!( + uv_config_index( + "pyproject.toml", + "[project]\nname = \"x\"\n[[tool.uv.index]]\nname = \"acme\"\nurl = \"https://pypi.acme.dev/simple\"\n" + ) + .as_deref(), + Some("https://pypi.acme.dev/simple") + ); + assert_eq!(uv_config_index("pyproject.toml", "[project]\nname = \"x\"\n"), None); + assert_eq!(uv_config_index("uv.toml", "index-url = \"https://pypi.org/simple\"\n"), None); + assert_eq!( + uv_config_index( + "uv.toml", + "index-url = \"https://pypi.org/simple\"\n[[index]]\nurl = \"https://pypi.org/simple\"\n[[index]]\nurl = \"https://a.example/simple\"\n" + ) + .as_deref(), + Some("https://a.example/simple") + ); +} + +#[test] +fn one_pip_run_at_a_time_per_environment() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("venv/bin")).unwrap(); + std::fs::write(dir.path().join("venv/pyvenv.cfg"), "home = /usr/bin\n").unwrap(); + let python = dir.path().join("venv/bin/python"); + let busy = crate::python::Busy::take(&python).unwrap(); + // `python3` of the same virtualenv is the same environment. + assert!(crate::python::Busy::take(&dir.path().join("venv/bin/python3")).is_err()); + assert!(crate::python::Busy::take(&dir.path().join("other/python")).is_ok()); + drop(busy); + assert!(crate::python::Busy::take(&python).is_ok()); +} diff --git a/crates/ide-tools/src/process.rs b/crates/ide-tools/src/process.rs index 279fb01c06..de13dce923 100644 --- a/crates/ide-tools/src/process.rs +++ b/crates/ide-tools/src/process.rs @@ -481,6 +481,16 @@ impl Http { self.get_text_response(url, None, Request::GetOrEmptyOn404, cancel) } + /// [`Self::get_text_or_empty_on_404`], failing when the response is larger than `max_bytes`. + pub fn get_text_limited_or_empty_on_404( + &self, + url: &str, + max_bytes: u64, + cancel: &CancellationToken, + ) -> IdeResult { + self.get_text_response(url, Some(max_bytes), Request::GetOrEmptyOn404, cancel) + } + fn get_text_response( &self, url: &str, diff --git a/crates/ide-workspace/src/dependencies/mod.rs b/crates/ide-workspace/src/dependencies/mod.rs index f5449a85a4..ccbcf25797 100644 --- a/crates/ide-workspace/src/dependencies/mod.rs +++ b/crates/ide-workspace/src/dependencies/mod.rs @@ -4,6 +4,7 @@ pub mod cargo; pub mod go; pub mod maven; pub mod npm; +pub mod pypi; pub mod python; pub use cache::VersionCache; diff --git a/crates/ide-workspace/src/dependencies/pypi.rs b/crates/ide-workspace/src/dependencies/pypi.rs new file mode 100644 index 0000000000..04d13f6d27 --- /dev/null +++ b/crates/ide-workspace/src/dependencies/pypi.rs @@ -0,0 +1,102 @@ +//! Projects on pypi.org, from its JSON API (`/pypi//json`). +use serde::{Deserialize, Serialize}; +use specta::Type; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PypiPackage { + /// The name as PyPI spells it. + pub name: String, + pub summary: String, + /// The newest release that is not a pre-release; empty when every release is yanked. + pub latest: String, + /// Releases with files to install, most recently uploaded first; yanked ones left out. + pub versions: Vec, +} + +/// The JSON API URL of a project; `None` unless `name` is a valid distribution name (PEP 508). +pub fn project_url(name: &str) -> Option { + let edge = |b: Option<&u8>| b.is_some_and(u8::is_ascii_alphanumeric); + let bytes = name.as_bytes(); + (name.len() <= 128 + && edge(bytes.first()) + && edge(bytes.last()) + && bytes.iter().all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(b))) + .then(|| format!("https://pypi.org/pypi/{name}/json")) +} + +pub fn parse_project(json: &str) -> Option { + #[derive(Deserialize)] + struct Project { + info: Info, + #[serde(default)] + releases: std::collections::BTreeMap>, + } + #[derive(Deserialize)] + struct Info { + name: String, + summary: Option, + version: String, + #[serde(default)] + yanked: bool, + } + #[derive(Deserialize)] + struct File { + #[serde(default)] + yanked: bool, + #[serde(default)] + upload_time_iso_8601: String, + } + let project: Project = serde_json::from_str(json).ok()?; + // ponytail: ordered by upload time, not PEP 440, so a backport released after a newer + // major sorts above it. Parse the versions if that order turns out to matter. + let mut releases: Vec<(String, String)> = project + .releases + .into_iter() + .filter(|(_, files)| files.iter().any(|f| !f.yanked)) + .map(|(version, files)| (files.into_iter().map(|f| f.upload_time_iso_8601).min().unwrap_or_default(), version)) + .collect(); + releases.sort_unstable_by(|a, b| b.cmp(a)); + let info = project.info; + Some(PypiPackage { + name: info.name, + summary: info.summary.unwrap_or_default(), + latest: if info.yanked { String::new() } else { info.version }, + versions: releases.into_iter().map(|(_, version)| version).collect(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_distribution_names_get_a_url() { + assert_eq!(project_url("typing_extensions").as_deref(), Some("https://pypi.org/pypi/typing_extensions/json")); + assert!(project_url("zope.interface").is_some()); + for bad in ["", "-pip", "pip-", "a/b", "../x", "a b", "requests==2.0", "naïve", "a?b", &"a".repeat(129)] { + assert_eq!(project_url(bad), None, "{bad}"); + } + } + + #[test] + fn releases_are_listed_newest_first_without_yanked_or_empty_ones() { + let json = r#"{ + "info": {"name": "Demo", "summary": null, "version": "2.0", "yanked": false}, + "releases": { + "1.0": [{"yanked": false, "upload_time_iso_8601": "2020-01-01T00:00:00.000000Z"}], + "1.1": [{"yanked": true, "upload_time_iso_8601": "2020-06-01T00:00:00.000000Z"}], + "2.0": [{"yanked": false, "upload_time_iso_8601": "2021-01-01T00:00:00.000000Z"}, + {"yanked": false, "upload_time_iso_8601": "2021-01-02T00:00:00.000000Z"}], + "2.1rc1": [{"yanked": false, "upload_time_iso_8601": "2021-03-01T00:00:00.000000Z"}], + "0.1": [] + } + }"#; + let project = parse_project(json).unwrap(); + assert_eq!(project.name, "Demo"); + assert_eq!(project.summary, ""); + assert_eq!(project.latest, "2.0"); + assert_eq!(project.versions, ["2.1rc1", "2.0", "1.0"]); + assert_eq!(parse_project(r#"{"message": "Not Found"}"#), None); + } +} diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 378e968e00..26b0abd9d3 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -85,6 +85,8 @@ You can also select an existing interpreter or environment folder. The new inter The same page lists the installed packages of the selected interpreter. You can search them, **Install** a package by name, **Upgrade** and **Uninstall**. The IDE uses the interpreter's pip, or `uv pip` for environments without pip (uv creates them that way). The **Latest** column marks the packages that have a newer release: after the list loads, the IDE asks the same tool (`pip list --outdated`, or `uv pip list --outdated`), so the answer comes from the index that tool is configured to use (pip's configuration for pip, uv's for uv) and is the newest release that the interpreter can install. When the index cannot be reached for every package, or the check takes more than two minutes, the page says the check failed rather than show a list that may be missing upgrades. +The **Python Packages** tool window (**View | Tool Windows**, or Find Action) manages the same packages next to the code. It lists what is installed and marks what can be upgraded. Type a name in its search field to filter the list; when the text is the exact name of a PyPI project that is not installed, the project appears under **PyPI**. Select a package to see its summary and its versions, then **Install** it (the newest release that fits the interpreter, or a version you pick), **Upgrade** or **Uninstall** it. The window manages the interpreter that runs use for the active file (in a workspace, its member's virtualenv) and shows its path. The lookup asks pypi.org by exact name: it does not search names by substring, and it does not ask a private index configured for pip, although installing does use pip's configuration. What you type in the search field is sent to pypi.org; the name of an installed package is sent only when you click **Show PyPI Details**. When pip or uv is configured to install from another index, nothing is sent to PyPI until you click **Search PyPI for …**, since a private package may have a public namesake. + Other options on the page: - **Activate virtualenv** (section **Terminal**): new terminal sessions run the virtualenv's activate script. diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index 2646eed410..1d5ab3e60d 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -85,6 +85,8 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml` 同一页面会列出所选解释器已安装的软件包,可以搜索、按名称 **安装**、**升级** 和 **卸载**。IDE 使用解释器自带的 pip;没有 pip 的环境(uv 创建的环境默认如此)改用 `uv pip`。**最新版本** 列会标出有新版本的软件包:列表加载后,IDE 用同一工具查询(`pip list --outdated` 或 `uv pip list --outdated`),因此结果来自该工具配置的索引(pip 用 pip 的配置,uv 用 uv 的配置),并且是该解释器可以安装的最新版本。如果有软件包无法访问索引,或者检查超过两分钟,页面会提示检查失败,而不是显示一份可能漏掉升级的列表。 +**Python 软件包** 工具窗口(**视图 | 工具窗口**,或通过查找操作打开)可以在代码旁边管理同一批软件包。它会列出已安装的软件包并标出可升级的。在搜索框中输入名称可筛选列表;当输入的文本正好是 PyPI 上某个未安装项目的名称时,该项目会显示在 **PyPI** 分组下。选中软件包可查看摘要和版本,然后 **安装**(适合该解释器的最新版本,或您选择的版本)、**升级** 或 **卸载**。该窗口管理的是运行当前文件时使用的解释器(在工作区中为其所属成员的虚拟环境),并显示其路径。查询按精确名称访问 pypi.org:不支持按子串搜索名称,也不会查询为 pip 配置的私有索引,但安装时仍使用 pip 的配置。在搜索框中输入的文本会发送到 pypi.org;已安装软件包的名称只有在点击 **显示 PyPI 详情** 时才会发送。如果 pip 或 uv 配置了从其他索引安装,在点击 **在 PyPI 中搜索 …** 之前不会向 PyPI 发送任何内容,因为私有软件包可能在 PyPI 上有同名的公开项目。 + 页面上的其他选项: - **激活 virtualenv**(**终端** 分组):新的终端会话会运行虚拟环境的激活脚本。 diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 07707b57f8..a165e4ac13 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -519,6 +519,7 @@ project_trust_status always project_host bin project_workspace_member_set always project_host bindings spawn project_workspace_members always project_host bindings spawn proxy_check_connection always desktop bindings async +pypi_package outside_restricted project_host bindings async python_requirements trusted project_host bindings async recent_files always project_host bindings sync recent_project_groups always desktop bindings sync @@ -601,6 +602,7 @@ sdk_python_create_venv outside_restricted project_host bin sdk_python_effective trusted project_host bindings async sdk_python_hatch_envs outside_restricted project_host bindings async sdk_python_interpreter outside_restricted project_host bindings async +sdk_python_package_index outside_restricted project_host bindings async sdk_python_packages outside_restricted project_host bindings async sdk_python_pip outside_restricted project_host bindings async sdk_python_project_interpreters outside_restricted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 22b5592915..e3ef5fbdc0 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1390,6 +1390,16 @@ export const commands = { * edited (not yet applied); the response status, or why there was none. */ proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError(__TAURI_INVOKE("proxy_check_connection", { proxy, url })), + /** A project on pypi.org by its exact name; `None` when PyPI has no such project. */ + pypiPackage: (name: string, request: RequestId) => typedError<{ + /** The name as PyPI spells it. */ + name: string, + summary: string, + /** The newest release that is not a pre-release; empty when every release is yanked. */ + latest: string, + /** Releases with files to install, most recently uploaded first; yanked ones left out. */ + versions: string[], +} | null, IdeError>(__TAURI_INVOKE("pypi_package", { name, request })), /** * The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter * doesn't satisfy; `None` for other files, or with no local interpreter to ask. @@ -1680,6 +1690,8 @@ export const commands = { /** Rust standard library sources, Go default GOPATH. */ extra: IpcPath | null, } | null, IdeError>(__TAURI_INVOKE("sdk_python_interpreter", { path })), + /** A package index other than PyPI that installing from `python` uses; `None` for PyPI. */ + sdkPythonPackageIndex: (python: string, request: RequestId) => typedError(__TAURI_INVOKE("sdk_python_package_index", { python, request })), sdkPythonPackages: (python: string, outdated: boolean, request: RequestId) => typedError(__TAURI_INVOKE("sdk_python_packages", { python, outdated, request })), /** Installs (`uninstall = false`) or removes a package; output streams through `on_output`. */ sdkPythonPip: (python: string, requirement: string, uninstall: boolean, upgrade: boolean, request: RequestId, onOutput: Channel) => typedError(__TAURI_INVOKE("sdk_python_pip", { python, requirement, uninstall, upgrade, request, onOutput })), @@ -11343,6 +11355,16 @@ export type PushTargetChoices = { export type PushTargetState = "ready" | "diverged" | "fetchRequired"; +export type PypiPackage = { + /** The name as PyPI spells it. */ + name: string, + summary: string, + /** The newest release that is not a pre-release; empty when every release is yanked. */ + latest: string, + /** Releases with files to install, most recently uploaded first; yanked ones left out. */ + versions: string[], +}; + /** A class definition and the methods it declares. */ export type PythonClassFacts = { name: string, diff --git a/src/features/index.ts b/src/features/index.ts index ecccffd69e..f490a393cc 100644 --- a/src/features/index.ts +++ b/src/features/index.ts @@ -38,6 +38,7 @@ import { activate as libraries } from "./libraries"; import { activate as viewers } from "./viewers"; import { activate as notebook } from "./notebook"; import { activate as pythonConsole } from "./python-console"; +import { activate as pythonPackages } from "./python-packages"; import { activate as web } from "./web"; import { activate as analysis } from "./analysis"; import { activate as services } from "./services"; @@ -93,6 +94,7 @@ const features: Array<[string, Activate]> = [ ["libraries", libraries], ["notebook", notebook], ["python-console", pythonConsole], + ["python-packages", pythonPackages], ["viewers", viewers], ["web", web], ["analysis", analysis], diff --git a/src/features/python-packages/PackagesView.test.tsx b/src/features/python-packages/PackagesView.test.tsx new file mode 100644 index 0000000000..ab2099f8ca --- /dev/null +++ b/src/features/python-packages/PackagesView.test.tsx @@ -0,0 +1,227 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ProjectInfo } from "@/platform/ipc"; + +const mocks = vi.hoisted(() => ({ + effective: vi.fn(), + packages: vi.fn(), + pypi: vi.fn(), + pip: vi.fn(), + container: vi.fn(), + index: vi.fn(), + cancel: vi.fn(), + active: null as string | null, +})); +vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} })); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + sdkPythonEffective: mocks.effective, + sdkPythonPackages: mocks.packages, + sdkPythonPip: mocks.pip, + sdkContainerPython: mocks.container, + sdkPythonPackageIndex: mocks.index, + pypiPackage: mocks.pypi, + cancelRequest: mocks.cancel, + }, + }; +}); + +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + editorService: () => ({ activePath: () => mocks.active, onActiveInputChange: () => () => {} }), +})); + +const { useProject } = await import("@/platform/project"); +const { PackagesView } = await import("./PackagesView"); + +const ok = (data: T) => ({ status: "ok" as const, data }); +const INSTALLED = [ + { name: "requests", version: "2.31.0" }, + { name: "urllib3", version: "2.8.0" }, +]; +const SIX = { + name: "six", + summary: "Python 2 and 3 compatibility utilities", + latest: "1.17.0", + versions: ["1.17.0", "1.16.0"], +}; + +function open(interpreter = "") { + useProject.setState({ + project: { root: "/p" } as ProjectInfo, + settings: { languages: { python: { interpreter } } } as never, + }); + render(); +} +// The list selects a row on mouse down. +const select = (row: HTMLElement) => fireEvent.mouseDown(row); +const search = (text: string) => + fireEvent.change(screen.getByRole("textbox", { name: "Search packages" }), { target: { value: text } }); + +beforeEach(() => { + mocks.effective.mockResolvedValue(ok("/p/.venv/bin/python")); + mocks.packages.mockImplementation((_python: string, outdated: boolean) => + Promise.resolve(ok(outdated ? [{ name: "requests", version: "2.31.0", latestVersion: "2.34.2" }] : INSTALLED)), + ); + mocks.pypi.mockImplementation((name: string) => Promise.resolve(ok(name === "six" ? SIX : null))); + mocks.pip.mockResolvedValue(ok(null)); + mocks.container.mockResolvedValue(ok(null)); + mocks.index.mockResolvedValue(ok(null)); + mocks.active = null; +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("Python Packages", () => { + it("lists the interpreter's packages and marks the upgradable ones", async () => { + open(); + expect(await screen.findByText("urllib3")).toBeInTheDocument(); + expect(await screen.findByTitle("Upgrade available: 2.34.2")).toBeInTheDocument(); + expect(mocks.packages).toHaveBeenCalledWith("/p/.venv/bin/python", false, expect.anything()); + expect(mocks.pypi).not.toHaveBeenCalled(); + }); + + it("finds a PyPI project by its exact name and installs it", async () => { + open(); + await screen.findByText("urllib3"); + search("six"); + select(await screen.findByText("six")); + expect(screen.queryByText("urllib3")).toBeNull(); + expect(await screen.findByText(SIX.summary)).toBeInTheDocument(); + expect(mocks.pypi).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole("button", { name: "Install" })); + // No version picked: pip chooses the newest one the interpreter can install. + expect(mocks.pip).toHaveBeenCalledWith( + "/p/.venv/bin/python", + "six", + false, + false, + expect.anything(), + expect.anything(), + ); + // The list is read again once pip is done. + await waitFor(() => expect(mocks.packages.mock.calls.filter((c) => c[1] === false)).toHaveLength(2)); + }); + + it("sends an installed package's name to PyPI only when asked, once per session", async () => { + open(); + select(await screen.findByText("urllib3")); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(mocks.pypi).not.toHaveBeenCalled(); + mocks.pypi.mockResolvedValue(ok({ ...SIX, name: "urllib3", summary: "HTTP library" })); + fireEvent.click(screen.getByRole("button", { name: "Show PyPI Details" })); + expect(await screen.findByText("HTTP library")).toBeInTheDocument(); + select(screen.getByText("requests")); + select(screen.getByText("urllib3")); + expect(screen.getByText("HTTP library")).toBeInTheDocument(); + expect(mocks.pypi).toHaveBeenCalledTimes(1); + }); + + it("does not search PyPI on its own when installing uses another index", async () => { + mocks.index.mockResolvedValue(ok("https://pypi.acme.dev/simple")); + open(); + await screen.findByText("urllib3"); + search("acme-utils"); + await new Promise((resolve) => setTimeout(resolve, 400)); + expect(mocks.pypi).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Search PyPI for acme-utils" })); + await waitFor(() => expect(mocks.pypi).toHaveBeenCalledWith("acme-utils", expect.anything())); + }); + + it("says when PyPI cannot be reached, and tries again", async () => { + mocks.pypi.mockResolvedValue({ status: "error", error: { kind: "unavailable", message: "offline" } }); + open(); + await screen.findByText("urllib3"); + search("flask"); + expect(await screen.findByText("Could not load package information from PyPI.")).toBeInTheDocument(); + expect(screen.queryByText("No packages match")).not.toBeInTheDocument(); + mocks.pypi.mockResolvedValue(ok({ ...SIX, name: "flask" })); + fireEvent.click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByText("flask")).toBeInTheDocument(); + }); + + it("manages the interpreter of the active file's folder, and shows it", async () => { + mocks.active = "/p/backend/app.py"; + mocks.effective.mockResolvedValue(ok("/p/backend/.venv/bin/python")); + open(); + expect(await screen.findByText("backend/.venv/bin/python")).toBeInTheDocument(); + expect(mocks.effective).toHaveBeenCalledWith("/p/backend"); + }); + + it("reloads the list after a failed pip run, which may have installed part of it", async () => { + mocks.pip.mockResolvedValue({ status: "error", error: { kind: "io", message: "pip failed" } }); + open(); + select(await screen.findByText("requests")); + fireEvent.click(await screen.findByRole("button", { name: "Uninstall" })); + expect(await screen.findByText("pip failed")).toBeInTheDocument(); + await waitFor(() => expect(mocks.packages.mock.calls.filter((c) => c[1] === false)).toHaveLength(2)); + }); + + it("does not ask PyPI about text that is not a package name", async () => { + open(); + await screen.findByText("urllib3"); + search("requests==2"); + await new Promise((resolve) => setTimeout(resolve, 400)); + expect(mocks.pypi).not.toHaveBeenCalled(); + expect(screen.getByText("No packages match")).toBeInTheDocument(); + }); + + it("upgrades and uninstalls an installed package", async () => { + open(); + select(await screen.findByText("requests")); + fireEvent.click(await screen.findByRole("button", { name: "Upgrade to 2.34.2" })); + expect(mocks.pip).toHaveBeenLastCalledWith( + "/p/.venv/bin/python", + "requests", + false, + true, + expect.anything(), + expect.anything(), + ); + await waitFor(() => expect(screen.getByRole("button", { name: "Uninstall" })).toBeEnabled()); + fireEvent.click(screen.getByRole("button", { name: "Uninstall" })); + expect(mocks.pip).toHaveBeenLastCalledWith( + "/p/.venv/bin/python", + "requests", + true, + false, + expect.anything(), + expect.anything(), + ); + }); + + it("says so when the project has no interpreter", async () => { + mocks.effective.mockResolvedValue(ok(null)); + open(); + expect(await screen.findByText("No Python interpreter")).toBeInTheDocument(); + expect(mocks.packages).not.toHaveBeenCalled(); + }); + + it("refreshes a container snapshot that is still being taken", async () => { + mocks.container + .mockResolvedValueOnce(ok({ packages: [], updating: true })) + .mockResolvedValue(ok({ packages: [{ name: "Django", version: "5.1.3" }], updating: false })); + open("target:web"); + expect(await screen.findByText("Loading packages…")).toBeInTheDocument(); + expect(await screen.findByText("Django", {}, { timeout: 3000 })).toBeInTheDocument(); + expect(mocks.container).toHaveBeenCalledTimes(2); + }); + + it("lists a container interpreter's packages read-only", async () => { + mocks.container.mockResolvedValue(ok({ packages: [{ name: "Django", version: "5.1.3" }] })); + open("target:web"); + select(await screen.findByText("Django")); + expect(screen.getByText(/read-only here/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Uninstall" })).toBeNull(); + search("six"); + await new Promise((resolve) => setTimeout(resolve, 400)); + expect(mocks.pypi).not.toHaveBeenCalled(); + expect(mocks.packages).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/python-packages/PackagesView.tsx b/src/features/python-packages/PackagesView.tsx new file mode 100644 index 0000000000..4faa9acace --- /dev/null +++ b/src/features/python-packages/PackagesView.tsx @@ -0,0 +1,521 @@ +/** + * Python Packages tool window: the packages of the project's interpreter, a PyPI project + * looked up by exact name, and install / upgrade / uninstall through pip or uv. + */ +import { Channel } from "@tauri-apps/api/core"; +import { useEffect, useMemo, useState } from "react"; +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import { call, commands, isCancelled, nextRequestId, type PypiPackage, type PythonPackage } from "@/platform/ipc"; +import { dirname, useProject } from "@/platform/project"; +import { usePythonPackages } from "@/platform/pythonPackages"; +import { + Button, + EmptyState, + Icon, + IconButton, + Input, + List, + Select, + Spinner, + SplitGroup, + SplitHandle, + SplitPanel, + T, +} from "@/ui"; +import { editorService } from "@/workbench/contributions"; +import { isPackageName, listRows, normalize, requirementOf, rowKey, type Row } from "./model"; +import styles from "./PythonPackages.module.css"; + +type Op = "install" | "upgrade" | "uninstall"; + +interface Job { + op: Op; + target: string; + cancel: () => void; +} + +const message = (e: unknown) => String((e as Error)?.message ?? e); + +/** The folder of the active editor's file, which picks the interpreter as runs do. */ +function useActiveFolder() { + const folder = () => { + const path = editorService().activePath(); + return path ? dirname(path) : null; + }; + const [current, setCurrent] = useState(folder); + useEffect(() => editorService().onActiveInputChange?.(() => setCurrent(folder())), []); + return current; +} + +/** + * The interpreter whose packages are listed: the one runs and the Python Console use for the + * active file (in a workspace, its member's virtualenv). A run target's (`container`) is read-only. + */ +function useInterpreter() { + const root = useProject((s) => s.project?.root ?? null); + const setting = useProject((s) => s.settings?.languages?.python?.interpreter ?? ""); + const near = useActiveFolder(); + const container = setting.trim().startsWith("target:"); + const key = `${root}\n${setting}\n${near}`; + const [local, setLocal] = useState<{ key: string; python: string | null } | null>(null); + const [snapshot, setSnapshot] = useState<{ + key: string; + packages: PythonPackage[]; + updating: boolean; + error: string | null; + } | null>(null); + const [tick, setTick] = useState(0); + useEffect(() => { + if (!root) return; + let live = true; + let timer: ReturnType | undefined; + if (container) { + const load = () => + call(commands.sdkContainerPython()).then( + (info) => { + if (!live) return; + setSnapshot({ key, packages: info?.packages ?? [], updating: !!info?.updating, error: null }); + if (info?.updating) timer = setTimeout(load, 2000); + }, + (e: unknown) => live && setSnapshot({ key, packages: [], updating: false, error: message(e) }), + ); + void load(); + } else { + call(commands.sdkPythonEffective(near)).then( + (python) => live && setLocal({ key, python }), + () => live && setLocal({ key, python: null }), + ); + } + return () => { + live = false; + clearTimeout(timer); + }; + }, [root, container, near, key, tick]); + return { + root, + container, + python: !container && local?.key === key ? local.python : null, + snapshot: container && snapshot?.key === key ? snapshot : null, + resolved: container ? snapshot?.key === key : local?.key === key, + retry: () => setTick((t) => t + 1), + }; +} + +/** A package index other than PyPI configured for `python`'s pip or uv; `undefined` until known. */ +function useCustomIndex(python: string | null) { + const [state, setState] = useState<{ python: string; index: string | null } | null>(null); + useEffect(() => { + if (!python) return; + let live = true; + const request = nextRequestId(); + call(commands.sdkPythonPackageIndex(python, request)).then( + (index) => live && setState({ python, index }), + // Unknown counts as custom: names stay on this machine. + () => live && setState({ python, index: "" }), + ); + return () => { + live = false; + void commands.cancelRequest(request); + }; + }, [python]); + return python && state?.python === python ? state.index : undefined; +} + +/** PyPI projects looked up this session, by normalised name; `null` when PyPI has none. */ +const pypiCache = new Map(); + +/** The PyPI project named exactly `name`, asked `delay` ms after the name last changed. */ +function usePypi(name: string | null, delay: number) { + const [state, setState] = useState<{ name: string; error: string } | null>(null); + const [, setDone] = useState(0); + const [tick, setTick] = useState(0); + const cached = name ? pypiCache.get(normalize(name)) : undefined; + useEffect(() => { + if (!name || pypiCache.has(normalize(name))) return; + let live = true; + let running = false; + const request = nextRequestId(); + const timer = setTimeout(() => { + running = true; + call(commands.pypiPackage(name, request)) + .then( + (found) => { + pypiCache.set(normalize(name), found); + if (live) setDone((n) => n + 1); + }, + (e: unknown) => live && !isCancelled(e) && setState({ name, error: message(e) }), + ) + .finally(() => (running = false)); + }, delay); + return () => { + live = false; + clearTimeout(timer); + if (running) void commands.cancelRequest(request); + }; + }, [name, delay, tick]); + const error = name && cached === undefined && state?.name === name ? state.error : null; + return { + found: cached ?? null, + error, + loading: !!name && cached === undefined && !error, + retry: () => { + setState(null); + setTick((t) => t + 1); + }, + }; +} + +export function PackagesView() { + const tx = useTx(); + const { root, container, python, snapshot, resolved, retry } = useInterpreter(); + const local = usePythonPackages(python); + const customIndex = useCustomIndex(python); + // Names go to pypi.org on their own only when installing uses PyPI too. + const auto = customIndex === null; + const [asked, setAsked] = useState(null); + const [detailsOf, setDetailsOf] = useState(null); + const packages = container ? snapshot?.packages : local.packages; + const error = container ? snapshot?.error : local.error; + const [query, setQuery] = useState(""); + const [selected, setSelected] = useState(null); + const [job, setJob] = useState(null); + const [log, setLog] = useState([]); + const [jobError, setJobError] = useState(null); + + const name = query.trim(); + const searchable = !container && isPackageName(name); + const search = usePypi(searchable && (auto || asked === name) ? name : null, 300); + const rows = useMemo( + () => listRows(packages ?? [], local.newer, search.found, query), + [packages, local.newer, search.found, query], + ); + // By name, so a package stays selected when installing it moves it out of the PyPI section. + const active = rows.findIndex((r) => r.kind !== "section" && normalize(r.name) === selected); + const row = rows[active]; + const picked = row && row.kind !== "section" ? row : null; + // The search already asked PyPI about the package it found. + const fromSearch = !!picked && !!search.found && normalize(search.found.name) === normalize(picked.name); + // An installed package's name is sent to PyPI only when asked for: it may be a private one. + const wanted = !!picked && (picked.kind === "pypi" || detailsOf === normalize(picked.name)); + const details = usePypi(picked && !container && !fromSearch && wanted ? picked.name : null, 200); + const info = fromSearch ? search : details; + + const run = (op: Op, requirement: string) => { + if (!python || job) return; + const request = nextRequestId(); + const channel = new Channel(); + channel.onmessage = (line) => setLog((l) => [...l.slice(-400), line]); + setLog([]); + setJobError(null); + setJob({ op, target: requirement, cancel: () => void commands.cancelRequest(request) }); + call(commands.sdkPythonPip(python, requirement, op === "uninstall", op === "upgrade", request, channel)) + .catch((e: unknown) => setJobError(isCancelled(e) ? null : message(e))) + .finally(() => { + setJob(null); + // A failed or cancelled run can still have installed some of the packages. + local.reload(); + }); + }; + + if (resolved && !container && !python) { + return ( + + + + + } + > + Select an interpreter for this project to manage its packages. + + ); + } + + const loading = !resolved || local.loading || !!snapshot?.updating; + return ( + + +
+ setQuery(e.target.value)} + /> + + {python && ( + + {relativeTo(root, python)} + + )} + {(loading || local.checking || search.loading) && ( + + )} +
+ {error ? ( +
+ {error} +
+ ) : ( + + items={rows} + getKey={rowKey} + isSection={(r) => r.kind === "section"} + activeIndex={active} + onActiveChange={(i) => { + const r = rows[i]; + setSelected(r && r.kind !== "section" ? normalize(r.name) : null); + }} + aria-label={tx("Python packages")} + className={styles.list} + empty={ + !search.error && ( + + {loading ? ( + Loading packages… + ) : search.loading ? ( + Searching PyPI… + ) : name ? ( + No packages match + ) : ( + No packages installed + )} + + ) + } + renderSection={(r) => (r.kind === "section" && r.id === "installed" ? Installed : "PyPI")} + renderItem={(r) => + r.kind === "section" ? null : ( + + {r.name} + {r.kind === "installed" && {r.version}} + {r.latest && ( + + {r.kind === "installed" && } + {r.latest} + + )} + + ) + } + /> + )} + {local.checkFailed && ( +
+ Could not check for newer versions of the packages. +
+ )} + {searchable && !auto && customIndex !== undefined && asked !== name && ( +
+ + Installing uses another package index, so names are not sent to PyPI on their own. + {" "} + +
+ )} + {search.error && ( +
+ + Could not load package information from PyPI. + {" "} + +
+ )} +
+ + + {picked ? ( +
setDetailsOf(normalize(picked.name))} + readOnly={container} + busy={!!job || loading} + run={run} + /> + ) : ( + + Select a package to see its versions. + + )} + {container && ( +
+ Packages come from the container image and are read-only here. +
+ )} + {job && ( +
+ + + {job.op === "install" ? tx("Installing") : job.op === "upgrade" ? tx("Upgrading") : tx("Uninstalling")}{" "} + {job.target}… + + +
+ )} + {jobError && ( +
+ {jobError} +
+ )} + {log.length > 0 && ( +
+            {log.join("\n")}
+          
+ )} + + + ); +} + +/** `path` relative to `root` when it is inside it. */ +function relativeTo(root: string | null, path: string) { + const base = root?.replace(/[\\/]+$/, ""); + return base && path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path; +} + +function Details({ + row, + info, + asked, + onAsk, + readOnly, + busy, + run, +}: { + row: Exclude; + info: { found: PypiPackage | null; error: string | null; loading: boolean; retry: () => void }; + /** Whether PyPI was asked about this package. */ + asked: boolean; + onAsk: () => void; + readOnly: boolean; + busy: boolean; + run: (op: Op, requirement: string) => void; +}) { + const tx = useTx(); + const installed = row.kind === "installed" ? row.version : null; + const versions = info.found?.versions; + const [choice, setChoice] = useState(null); + // The installed version, else the newest release; a pre-release only when nothing else exists. + const preset = installed ?? (info.found?.latest || versions?.[0]) ?? null; + const version = choice ?? preset; + const options = useMemo(() => { + const all = versions ?? []; + return (version && !all.includes(version) ? [version, ...all] : all).map((v) => ({ + value: v, + label: v, + verbatim: true, + })); + }, [versions, version]); + + return ( +
+
+ {row.name} + {installed ?? Not installed} +
+ {info.found?.summary &&
{info.found.summary}
} + {!readOnly && !asked && ( +
+ +
+ )} + {asked && info.loading && ( +
+ Loading package information from PyPI… +
+ )} + {asked && info.error && ( +
+ + Could not load package information from PyPI. + {" "} + +
+ )} + {!readOnly && asked && !info.loading && !info.error && !info.found && ( +
+ This package is not on PyPI. +
+ )} + {!readOnly && ( +
+ {options.length > 0 && version && ( +