feat(python): show package documentation in the Python Packages tool window (#6600)

When the pane has a package's PyPI details (a search result, or an installed package after Show PyPI Details), it also shows the project's links (its PyPI page, home_page and project_urls; http(s) only, duplicates dropped) and its long description: rendered Markdown (sanitized, as in hover docs) when description_content_type is Markdown, plain text otherwise. Links open in the browser. Everything comes from the JSON API response the pane already loads.

Closes #6530

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 08:31:32 +08:00
1 джерело 0a8fea1876
коміт 3747a8a63f
11 files changed
+263 -2

No files matched your search

+56
Переглянути файл
@@ -20,6 +20,18 @@ pub struct PypiPackage {
pub latest: String,
/// Releases with files to install, most recently uploaded first; yanked ones left out.
pub versions: Vec<String>,
/// The project's long description (usually its README).
pub description: String,
/// Whether `description` is Markdown; otherwise reStructuredText or plain text.
pub markdown: bool,
/// The project's web links (Homepage, Documentation, Source, …); `http(s)` only.
pub links: Vec<PypiLink>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
pub struct PypiLink {
pub label: String,
pub url: String,
}
/// The JSON API URL of a project; `None` unless `name` is a valid distribution name (PEP 508).
@@ -47,6 +59,10 @@ pub fn parse_project(json: &str) -> Option<PypiPackage> {
version: String,
#[serde(default)]
yanked: bool,
description: Option<String>,
description_content_type: Option<String>,
home_page: Option<String>,
project_urls: Option<std::collections::BTreeMap<String, String>>,
}
#[derive(Deserialize)]
struct File {
@@ -66,11 +82,27 @@ pub fn parse_project(json: &str) -> Option<PypiPackage> {
.collect();
releases.sort_unstable_by(|a, b| b.cmp(a));
let info = project.info;
let web = |url: &str| url.starts_with("https://") || url.starts_with("http://");
let mut links: Vec<(String, String)> = info.home_page.into_iter().map(|url| ("Homepage".to_owned(), url)).collect();
// Sorted by label: serde_json's map doesn't keep the declared order.
links.extend(info.project_urls.unwrap_or_default());
let mut links: Vec<PypiLink> = links
.into_iter()
.map(|(label, url)| PypiLink { label: label.trim().to_owned(), url: url.trim().to_owned() })
.filter(|l| !l.label.is_empty() && web(&l.url))
.collect();
let mut seen = std::collections::HashSet::new();
links.retain(|l| seen.insert(l.url.trim_end_matches('/').to_owned()));
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(),
description: info.description.unwrap_or_default(),
markdown: info
.description_content_type
.is_some_and(|t| t.trim_start().to_ascii_lowercase().starts_with("text/markdown")),
links,
})
}
@@ -398,9 +430,33 @@ mod tests {
assert_eq!(project.summary, "");
assert_eq!(project.latest, "2.0");
assert_eq!(project.versions, ["2.1rc1", "2.0", "1.0"]);
assert_eq!((project.description.as_str(), project.markdown, project.links.len()), ("", false, 0));
assert_eq!(parse_project(r#"{"message": "Not Found"}"#), None);
}
#[test]
fn the_description_and_web_links_are_kept() {
let json = r##"{
"info": {"name": "demo", "summary": "s", "version": "1.0",
"description": "# Demo", "description_content_type": "text/markdown; charset=UTF-8; variant=GFM",
"home_page": "https://example.org/",
"project_urls": {"Source": "https://github.com/x/demo", "Home": "https://example.org",
"Chat": "irc://libera.chat/demo", " ": "https://example.org/blank"}},
"releases": {}
}"##;
let project = parse_project(json).unwrap();
assert_eq!(project.description, "# Demo");
assert!(project.markdown);
let links: Vec<_> = project.links.iter().map(|l| (l.label.as_str(), l.url.as_str())).collect();
assert_eq!(links, [("Homepage", "https://example.org/"), ("Source", "https://github.com/x/demo")]);
let rst = parse_project(
r#"{"info": {"name": "d", "version": "1", "description": "Demo\n====",
"description_content_type": null, "project_urls": null}}"#,
)
.unwrap();
assert!(!rst.markdown);
}
fn search(index: &NameIndex, query: &str, limit: usize) -> Vec<String> {
index.search(query, limit, &CancellationToken::new()).unwrap()
}
+2
Переглянути файл
@@ -87,6 +87,8 @@ The same page lists the installed packages of the selected interpreter. You can
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 in its search field to filter the list; PyPI projects whose names contain the text and that are not installed appear under **PyPI**, the exact name first, then names that start with the text. 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. PyPI has no search API, so the search runs on a copy of PyPI's list of project names: the first search downloads it (about 10 MB) into the IDE's cache, and a search a day later refreshes it; searching the copy sends nothing. Until it is there, or when it cannot be downloaded, a project is still found by its exact name. Only pypi.org is searched, not a private index configured for pip, although installing does use pip's configuration. The exact-name lookup sends what you type 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, the exact-name lookup and the search results wait until you click **Search PyPI for …**, since a private package may have a public namesake.
When it has a package's details from PyPI, the pane also lists the project's links (its PyPI page, homepage, documentation, source, …) and its description from PyPI: rendered when it is Markdown, as plain text otherwise. Links open in the browser.
Other options on the page:
- **Activate virtualenv** (section **Terminal**): new terminal sessions run the virtualenv's activate script.
+2
Переглянути файл
@@ -87,6 +87,8 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
**Python 软件包** 工具窗口(**视图 | 工具窗口**,或通过查找操作打开)可以在代码旁边管理同一批软件包。它会列出已安装的软件包并标出可升级的。在搜索框中输入文本可筛选列表;名称包含该文本且尚未安装的 PyPI 项目会显示在 **PyPI** 分组下,名称完全相同的排在最前,其次是以该文本开头的名称。选中软件包可查看摘要和版本,然后 **安装**(适合该解释器的最新版本,或您选择的版本)、**升级** 或 **卸载**。该窗口管理的是运行当前文件时使用的解释器(在工作区中为其所属成员的虚拟环境),并显示其路径。PyPI 没有搜索接口,因此搜索在 PyPI 项目名称列表的本地副本上进行:第一次搜索时会把它下载到 IDE 的缓存中(约 10 MB),一天之后的搜索会刷新它;在本地副本中搜索不会发送任何内容。在列表下载完成之前,或者无法下载时,仍然可以按精确名称找到项目。只搜索 pypi.org,不会查询为 pip 配置的私有索引,但安装时仍使用 pip 的配置。按精确名称查询时,输入的文本会发送到 pypi.org;已安装软件包的名称只有在点击 **显示 PyPI 详情** 时才会发送。如果 pip 或 uv 配置了从其他索引安装,按精确名称查询和搜索结果都要等到点击 **在 PyPI 中搜索 …** 之后才会出现,因为私有软件包可能在 PyPI 上有同名的公开项目。
取得 PyPI 上的软件包信息后,详情面板还会列出项目链接(PyPI 页面、主页、文档、源码等)和 PyPI 上的项目说明:Markdown 格式会渲染显示,其他格式按纯文本显示。链接在浏览器中打开。
页面上的其他选项:
- **激活 virtualenv**(**终端** 分组):新的终端会话会运行虚拟环境的激活脚本。
+17
Переглянути файл
@@ -1576,6 +1576,12 @@ export const commands = {
latest: string,
/** Releases with files to install, most recently uploaded first; yanked ones left out. */
versions: string[],
/** The project's long description (usually its README). */
description: string,
/** Whether `description` is Markdown; otherwise reStructuredText or plain text. */
markdown: boolean,
/** The project's web links (Homepage, Documentation, Source, …); `http(s)` only. */
links: PypiLink[],
} | null, IdeError>(__TAURI_INVOKE("pypi_package", { name, request })),
/**
* PyPI project names containing `query`, best match first, 51 at most (50 are shown). Answers from a cached copy of
@@ -12250,6 +12256,11 @@ export type PushTargetChoices = {
export type PushTargetState = "ready" | "diverged" | "fetchRequired";
export type PypiLink = {
label: string,
url: string,
};
export type PypiPackage = {
/** The name as PyPI spells it. */
name: string,
@@ -12258,6 +12269,12 @@ export type PypiPackage = {
latest: string,
/** Releases with files to install, most recently uploaded first; yanked ones left out. */
versions: string[],
/** The project's long description (usually its README). */
description: string,
/** Whether `description` is Markdown; otherwise reStructuredText or plain text. */
markdown: boolean,
/** The project's web links (Homepage, Documentation, Source, …); `http(s)` only. */
links: PypiLink[],
};
export type PytestFixtureAt = {
+30
Переглянути файл
@@ -11,8 +11,10 @@ const mocks = vi.hoisted(() => ({
container: vi.fn(),
index: vi.fn(),
cancel: vi.fn(),
openUrl: vi.fn(),
active: null as string | null,
}));
vi.mock("@/platform/openUrl", () => ({ openExternalUrl: mocks.openUrl }));
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -50,6 +52,9 @@ const SIX = {
summary: "Python 2 and 3 compatibility utilities",
latest: "1.17.0",
versions: ["1.17.0", "1.16.0"],
description: "# Six\n\nRead the [documentation](https://six.readthedocs.io/).<script>alert(1)</script>",
markdown: true,
links: [{ label: "Source", url: "https://github.com/benjaminp/six" }],
};
function open(interpreter = "") {
@@ -112,6 +117,30 @@ describe("Python Packages", () => {
await waitFor(() => expect(mocks.packages.mock.calls.filter((c) => c[1] === false)).toHaveLength(2));
});
it("shows a PyPI project's links and its Markdown description, opening links in the browser", async () => {
open();
await screen.findByText("urllib3");
search("six");
select(await screen.findByText("six"));
expect(await screen.findByRole("heading", { name: "Six" })).toBeInTheDocument();
expect(document.querySelector("script")).toBeNull();
const links = screen.getByRole("navigation", { name: "Project links" });
expect([...links.querySelectorAll("a")].map((a) => a.textContent)).toEqual(["PyPI", "Source"]);
fireEvent.click(screen.getByRole("link", { name: "PyPI" }));
fireEvent.click(screen.getByRole("link", { name: "documentation" }));
expect(mocks.openUrl.mock.calls).toEqual([["https://pypi.org/project/six/"], ["https://six.readthedocs.io/"]]);
});
it("shows a description that is not Markdown as text", async () => {
open();
await screen.findByText("urllib3");
mocks.pypi.mockResolvedValue(ok({ ...SIX, name: "docutils", description: "Docutils\n========", markdown: false }));
search("docutils");
select(await screen.findByText("docutils"));
expect((await screen.findByLabelText("Package description")).textContent).toBe("Docutils\n========");
expect(screen.queryByRole("heading")).toBeNull();
});
it("sends an installed package's name to PyPI only when asked, once per session", async () => {
open();
select(await screen.findByText("urllib3"));
@@ -120,6 +149,7 @@ describe("Python Packages", () => {
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();
expect(screen.getByRole("link", { name: "PyPI" })).toHaveAttribute("href", "https://pypi.org/project/urllib3/");
select(screen.getByText("requests"));
select(screen.getByText("urllib3"));
expect(screen.getByText("HTTP library")).toBeInTheDocument();
+44 -1
Переглянути файл
@@ -3,10 +3,12 @@
* 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 { useEffect, useMemo, useState, type MouseEvent } from "react";
import { useMarkupHtml } from "@/editor/lsp/markdown";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId, type PypiPackage, type PythonPackage } from "@/platform/ipc";
import { openExternalUrl } from "@/platform/openUrl";
import { dirname, useProject } from "@/platform/project";
import { usePythonPackages } from "@/platform/pythonPackages";
import {
@@ -576,6 +578,47 @@ function Details({
)}
</div>
)}
{asked && info.found && <Docs found={info.found} />}
</div>
);
}
/** Links open in the browser; a relative one has nothing to open and must not navigate the app. */
function openLink(e: MouseEvent) {
const a = (e.target as HTMLElement).closest("a");
if (!a) return;
e.preventDefault();
void openExternalUrl(a.getAttribute("href") ?? "");
}
/** The project's links and its description from PyPI: rendered when Markdown, else as text. */
function Docs({ found }: { found: PypiPackage }) {
const tx = useTx();
const html = useMarkupHtml({ kind: "markdown", value: found.markdown ? found.description : "" });
const links = [{ label: "PyPI", url: `https://pypi.org/project/${found.name}/` }, ...found.links];
return (
<>
<nav className={styles.links} aria-label={tx("Project links")} onClick={openLink}>
{links.map((l) => (
<a key={l.url} href={l.url} title={l.url}>
{l.label}
</a>
))}
</nav>
{found.description.trim() &&
(found.markdown ? (
<div
className={styles.doc}
role="document"
aria-label={tx("Package description")}
onClick={openLink}
dangerouslySetInnerHTML={{ __html: html }}
/>
) : (
<pre className={styles.plainDoc} aria-label={tx("Package description")}>
{found.description}
</pre>
))}
</>
);
}
+95
Переглянути файл
@@ -95,6 +95,101 @@
min-width: 140px;
}
.links {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
}
.links a,
.doc :global(a) {
color: var(--link);
text-decoration: none;
cursor: pointer;
}
.links a:hover,
.doc :global(a:hover) {
color: var(--link-hover);
text-decoration: underline;
}
/* The project description, styled like the Markdown preview. */
.doc,
.plainDoc {
padding-top: var(--space-2);
border-top: 1px solid var(--border);
line-height: 1.55;
overflow-wrap: anywhere;
user-select: text;
-webkit-user-select: text;
}
.plainDoc {
margin: 0;
font-family: var(--font-mono);
font-size: var(--fs-small);
white-space: pre-wrap;
color: var(--fg-secondary);
}
.doc :global(:is(h1, h2, h3, h4, h5, h6)) {
margin: 1em 0 0.5em;
color: var(--fg-strong);
line-height: 1.25;
}
.doc :global(h1) {
font-size: 1.5em;
}
.doc :global(h2) {
font-size: 1.3em;
}
.doc :global(h3) {
font-size: 1.15em;
}
.doc :global(:is(h1, h2)) {
padding-bottom: 0.25em;
border-bottom: 1px solid var(--border);
}
.doc > :first-child {
margin-top: 0;
}
.doc :global(:is(p, ul, ol, blockquote, pre, table)) {
margin: 0 0 0.9em;
}
.doc :global(code) {
font-family: var(--font-mono);
font-size: 0.9em;
padding: 0.1em 0.35em;
border-radius: var(--radius-small);
background: var(--bg-elev);
}
.doc :global(pre) {
padding: var(--space-2);
border-radius: var(--radius-control);
background: var(--bg-elev);
overflow: auto;
}
.doc :global(pre code) {
padding: 0;
background: none;
}
.doc :global(blockquote) {
padding: 0 1em;
border-left: 3px solid var(--border-strong);
color: var(--fg-secondary);
}
.doc :global(table) {
border-collapse: collapse;
}
.doc :global(:is(th, td)) {
padding: var(--space-1) var(--space-2);
border: 1px solid var(--border-strong);
}
.doc :global(img) {
max-width: 100%;
}
.doc :global(hr) {
border: none;
border-top: 1px solid var(--border);
margin: 1.2em 0;
}
.note {
color: var(--fg-subtle);
font-size: var(--fs-small);
+9 -1
Переглянути файл
@@ -5,7 +5,15 @@ const INSTALLED = [
{ name: "requests", version: "2.31.0" },
{ name: "typing_extensions", version: "4.12.0" },
];
const found = (name: string) => ({ name, summary: "", latest: "1.0", versions: ["1.0"] });
const found = (name: string) => ({
name,
summary: "",
latest: "1.0",
versions: ["1.0"],
description: "",
markdown: false,
links: [],
});
describe("package rows", () => {
it("lists the installed packages with their newer release", () => {
+2
Переглянути файл
@@ -284,6 +284,8 @@ describe("catalogs", () => {
/** Product names intentionally kept as written in every locale. */
const SAME_AS_ENGLISH = new Set([
"Flutter DevTools",
// The package index's name, as a project link in the Python Packages tool window.
"PyPI",
// Pub / Flutter command names on the pubspec.yaml banner.
"Pub get",
"Pub upgrade",
+3
Переглянути файл
@@ -4079,6 +4079,9 @@
"Install Version": "Install Version",
"Upgrade to {latest}": "Upgrade to {latest}",
"Show PyPI Details": "Show PyPI Details",
"Project links": "Project links",
"Package description": "Package description",
"PyPI": "PyPI",
"Search PyPI for {name}": "Search PyPI for {name}",
"Installing uses another package index, so names are not sent to PyPI on their own.": "Installing uses another package index, so names are not sent to PyPI on their own.",
"Smart Type": "Smart Type",
+3
Переглянути файл
@@ -10502,6 +10502,9 @@
"Install Version": "安装此版本",
"Upgrade to {latest}": "升级到 {latest}",
"Show PyPI Details": "显示 PyPI 详情",
"Project links": "项目链接",
"Package description": "包说明",
"PyPI": "PyPI",
"Search PyPI for {name}": "在 PyPI 中搜索 {name}",
"Installing uses another package index, so names are not sent to PyPI on their own.": "安装使用的是另一个软件包索引,因此不会自动把名称发送到 PyPI。",
"Smart Type": "智能类型",