From ddea7e5ec58da8a76140c27aad6f073c7a4a1630 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 09:37:01 +0900 Subject: [PATCH] feat(python): install packages from version control or a local directory (#6601) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A + button in the Python Packages tool window offers Install from Version Control… and Install from Disk… (with Browse), both with Install as editable (-e). A plain https://, ssh://, git:// or git@host:path URL gets pip's git+ form; git+… and other vcs+ URLs pass as they are. sdk_python_pip takes an editable flag that adds -e (pip and uv pip); text starting with - is still refused, so no other pip option can be passed. Closes #6531 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/sdk.rs | 14 ++- crates/ide-sdk/src/python.rs | 9 +- docs/en/languages/python.mdx | 2 + docs/zh/languages/python.mdx | 2 + src/bindings.ts | 7 +- src/features/dependencies/python.ts | 2 +- src/features/django/stubs.ts | 2 +- .../python-packages/PackagesView.test.tsx | 53 ++++++++- src/features/python-packages/PackagesView.tsx | 101 +++++++++++++++++- .../python-packages/PythonPackages.module.css | 14 +++ src/features/python-packages/model.test.ts | 13 ++- src/features/python-packages/model.ts | 11 ++ src/features/settings/languages/api.ts | 2 +- src/platform/locales/text/en.json | 10 ++ src/platform/locales/text/zh.json | 9 ++ 15 files changed, 237 insertions(+), 14 deletions(-) diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index b4cc0116f..bd682c4a4 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -432,7 +432,8 @@ pub async fn sdk_python_package_index( result } -/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`. +/// Installs (`uninstall = false`, in editable mode with `editable`) or removes a package; output +/// streams through `on_output`. #[allow(clippy::too_many_arguments)] #[command(trust = outside_restricted)] pub async fn sdk_python_pip( @@ -442,6 +443,7 @@ pub async fn sdk_python_pip( requirement: String, uninstall: bool, upgrade: bool, + editable: bool, request: RequestId, on_output: Channel, ) -> IdeResult<()> { @@ -455,7 +457,15 @@ pub async fn sdk_python_pip( if uninstall { ide_sdk::python::uninstall_package(&python, &requirement, &cancel, &send) } else { - ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send) + ide_sdk::python::install_package( + &python, + &requirement, + upgrade, + editable, + project_root.as_deref(), + &cancel, + &send, + ) } }) .await; diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index dee3b1a57..031de305a 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -608,12 +608,14 @@ 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`. +/// Installs (or upgrades, with `upgrade`) a requirement such as `requests` or `django==5.0`, +/// a VCS URL or a local path, in editable mode (`-e`) with `editable`; relative paths +/// (`./pkg`) are resolved against `project_root`. pub fn install_package( python: &Path, requirement: &str, upgrade: bool, + editable: bool, project_root: Option<&Path>, cancel: &CancellationToken, on_line: &dyn Fn(String), @@ -629,6 +631,9 @@ pub fn install_package( if upgrade { sub.push("--upgrade"); } + if editable { + sub.push("-e"); + } sub.push(&requirement); let (program, args) = pip_command(python, &installer, &sub); let dir = neutral_dir(); diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 24ff5d674..c2d8c0baa 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -89,6 +89,8 @@ The **Python Packages** tool window (**View | Tool Windows**, or Find Action) ma 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. +The **+** button in its toolbar installs a package from elsewhere: **Install from Version Control…** takes a repository URL (`git+https://…`; a plain `https://`, `ssh://` or `git@host:path` URL is installed with Git), **Install from Disk…** a project directory or a wheel or source archive. With **Install as editable (-e)**, a local project is installed in editable mode, so changes to its sources apply without reinstalling; an editable install from version control needs `#egg=` at the end of the URL. + 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 4a2e0398b..44bddc64e 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -89,6 +89,8 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml` 取得 PyPI 上的软件包信息后,详情面板还会列出项目链接(PyPI 页面、主页、文档、源码等)和 PyPI 上的项目说明:Markdown 格式会渲染显示,其他格式按纯文本显示。链接在浏览器中打开。 +工具栏中的 **+** 按钮可以从其他来源安装软件包:**从版本控制安装…** 接受仓库 URL(`git+https://…`;普通的 `https://`、`ssh://` 或 `git@host:path` URL 会按 Git 安装),**从磁盘安装…** 接受项目目录或 wheel、源码归档文件。勾选 **以可编辑模式安装 (-e)** 后,本地项目以可编辑模式安装,修改源码后无需重新安装即可生效;从版本控制以可编辑模式安装时,URL 末尾需要加上 `#egg=<名称>`。 + 页面上的其他选项: - **激活 virtualenv**(**终端** 分组):新的终端会话会运行虚拟环境的激活脚本。 diff --git a/src/bindings.ts b/src/bindings.ts index d8ac8cc04..70d291303 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1924,8 +1924,11 @@ export const commands = { /** 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 })), + /** + * Installs (`uninstall = false`, in editable mode with `editable`) or removes a package; output + * streams through `on_output`. + */ + sdkPythonPip: (python: string, requirement: string, uninstall: boolean, upgrade: boolean, editable: boolean, request: RequestId, onOutput: Channel) => typedError(__TAURI_INVOKE("sdk_python_pip", { python, requirement, uninstall, upgrade, editable, request, onOutput })), /** The Python interpreters of the recently opened projects, each with its project. */ sdkPythonProjectInterpreters: () => typedError(__TAURI_INVOKE("sdk_python_project_interpreters")), /** `sys.path` of the interpreter `python`, for All Interpreters › Show Paths. */ diff --git a/src/features/dependencies/python.ts b/src/features/dependencies/python.ts index 33cf78276..4fb510ceb 100644 --- a/src/features/dependencies/python.ts +++ b/src/features/dependencies/python.ts @@ -82,7 +82,7 @@ export async function installRequirements(python: string, requirements: readonly current = nextRequestId(); try { // oxlint-disable-next-line no-await-in-loop -- installs are one at a time with a shared cancellable request and progress - await call(commands.sdkPythonPip(python, requirement, false, false, current, channel)); + await call(commands.sdkPythonPip(python, requirement, false, false, false, current, channel)); } catch (e) { if (!cancelled) failures.push(`${requirement}: ${e instanceof Error ? e.message : String(e)}`); } diff --git a/src/features/django/stubs.ts b/src/features/django/stubs.ts index 58193fef5..e34c097ab 100644 --- a/src/features/django/stubs.ts +++ b/src/features/django/stubs.ts @@ -47,7 +47,7 @@ async function install() { line.trim() && upsertTask({ id, title, message: line.trim(), fraction: null, done: false, cancel }); upsertTask({ id, title, message: null, fraction: null, done: false, cancel }); try { - await call(commands.sdkPythonPip(python, STUBS, false, false, request, channel)); + await call(commands.sdkPythonPip(python, STUBS, false, false, false, request, channel)); // The type checker reads installed packages when it starts. await Promise.all(["basedpyright", "pyright"].map((n) => call(commands.lspRestartNamed(n)).catch(() => {}))); } catch (e) { diff --git a/src/features/python-packages/PackagesView.test.tsx b/src/features/python-packages/PackagesView.test.tsx index 9ffe6b0bf..d356fe739 100644 --- a/src/features/python-packages/PackagesView.test.tsx +++ b/src/features/python-packages/PackagesView.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ProjectInfo } from "@/platform/ipc"; @@ -11,10 +11,18 @@ const mocks = vi.hoisted(() => ({ container: vi.fn(), index: vi.fn(), cancel: vi.fn(), + menu: vi.fn(), openUrl: vi.fn(), active: null as string | null, })); vi.mock("@/platform/openUrl", () => ({ openExternalUrl: mocks.openUrl })); +// The context menu host is not mounted here: pick menu items by label instead. +vi.mock("@/ui", async (importOriginal) => ({ + ...(await importOriginal()), + showContextMenu: mocks.menu, +})); +const pick = (label: string) => + (mocks.menu.mock.lastCall![1] as { label: string; run: () => void }[]).find((i) => i.label === label)!.run(); vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} })); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); @@ -110,6 +118,7 @@ describe("Python Packages", () => { "six", false, false, + false, expect.anything(), expect.anything(), ); @@ -117,6 +126,46 @@ describe("Python Packages", () => { await waitFor(() => expect(mocks.packages.mock.calls.filter((c) => c[1] === false)).toHaveLength(2)); }); + it("installs a repository URL or a local directory, in editable mode when asked", async () => { + open(); + await screen.findByText("urllib3"); + fireEvent.click(screen.getByRole("button", { name: "Install from Version Control or Disk" })); + act(() => pick("Install from Version Control…")); + const url = await screen.findByRole("textbox", { name: "Repository URL" }); + fireEvent.change(url, { target: { value: "https://github.com/benjaminp/six.git" } }); + fireEvent.click(screen.getByRole("button", { name: "Install" })); + expect(mocks.pip).toHaveBeenLastCalledWith( + "/p/.venv/bin/python", + "git+https://github.com/benjaminp/six.git", + false, + false, + false, + expect.anything(), + expect.anything(), + ); + await waitFor(() => + expect(screen.getByRole("button", { name: "Install from Version Control or Disk" })).toBeEnabled(), + ); + + fireEvent.click(screen.getByRole("button", { name: "Install from Version Control or Disk" })); + act(() => pick("Install from Disk…")); + const path = await screen.findByRole("textbox", { name: "Path" }); + fireEvent.change(path, { target: { value: "--index-url=https://evil.example" } }); + expect(screen.getByRole("button", { name: "Install" })).toBeDisabled(); + fireEvent.change(path, { target: { value: "./mylib" } }); + fireEvent.click(screen.getByRole("checkbox", { name: "Install as editable (-e)" })); + fireEvent.click(screen.getByRole("button", { name: "Install" })); + expect(mocks.pip).toHaveBeenLastCalledWith( + "/p/.venv/bin/python", + "./mylib", + false, + false, + true, + expect.anything(), + expect.anything(), + ); + }); + it("shows a PyPI project's links and its Markdown description, opening links in the browser", async () => { open(); await screen.findByText("urllib3"); @@ -246,6 +295,7 @@ describe("Python Packages", () => { "requests", false, true, + false, expect.anything(), expect.anything(), ); @@ -256,6 +306,7 @@ describe("Python Packages", () => { "requests", true, false, + false, expect.anything(), expect.anything(), ); diff --git a/src/features/python-packages/PackagesView.tsx b/src/features/python-packages/PackagesView.tsx index cf7c5cc63..48da8487f 100644 --- a/src/features/python-packages/PackagesView.tsx +++ b/src/features/python-packages/PackagesView.tsx @@ -8,11 +8,14 @@ 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 { choosePath } from "@/platform/choosePath"; import { openExternalUrl } from "@/platform/openUrl"; import { dirname, useProject } from "@/platform/project"; import { usePythonPackages } from "@/platform/pythonPackages"; import { Button, + Checkbox, + Dialog, EmptyState, Icon, IconButton, @@ -23,10 +26,11 @@ import { SplitGroup, SplitHandle, SplitPanel, + showContextMenu, T, } from "@/ui"; import { editorService } from "@/workbench/contributions"; -import { isPackageName, listRows, normalize, requirementOf, rowKey, type Row } from "./model"; +import { isPackageName, listRows, normalize, requirementOf, rowKey, vcsRequirement, type Row } from "./model"; import styles from "./PythonPackages.module.css"; type Op = "install" | "upgrade" | "uninstall"; @@ -227,6 +231,7 @@ export function PackagesView() { const [job, setJob] = useState(null); const [log, setLog] = useState([]); const [jobError, setJobError] = useState(null); + const [installFrom, setInstallFrom] = useState(null); const name = query.trim(); const searchable = !container && isPackageName(name); @@ -249,7 +254,7 @@ export function PackagesView() { const details = usePypi(picked && !container && !fromSearch && wanted ? picked.name : null, 200); const info = fromSearch ? search : details; - const run = (op: Op, requirement: string) => { + const run = (op: Op, requirement: string, editable = false) => { if (!python || job) return; const request = nextRequestId(); const channel = new Channel(); @@ -257,7 +262,7 @@ export function PackagesView() { setLog([]); setJobError(null); setJob({ op, target: requirement, cancel: () => void commands.cancelRequest(request) }); - call(commands.sdkPythonPip(python, requirement, op === "uninstall", op === "upgrade", request, channel)) + call(commands.sdkPythonPip(python, requirement, op === "uninstall", op === "upgrade", editable, request, channel)) .catch((e: unknown) => setJobError(isCancelled(e) ? null : message(e))) .finally(() => { setJob(null); @@ -306,6 +311,21 @@ export function PackagesView() { disabled={loading || !!job} onClick={container ? retry : local.reload} /> + {!container && ( + { + const r = e.currentTarget.getBoundingClientRect(); + showContextMenu({ x: r.left, y: r.bottom + 2 }, [ + { label: "Install from Version Control…", run: () => setInstallFrom("vcs") }, + { label: "Install from Disk…", run: () => setInstallFrom("disk") }, + ]); + }} + /> + )} {python && ( {relativeTo(root, python)} @@ -456,10 +476,85 @@ export function PackagesView() { )} + {installFrom && ( + setInstallFrom(null)} + onInstall={(requirement, editable) => { + setInstallFrom(null); + run("install", requirement, editable); + }} + /> + )} ); } +type Source = "vcs" | "disk"; + +/** A repository URL or a local directory or archive to install, as PyCharm's Advanced Package Install. */ +function InstallFromDialog({ + source, + onClose, + onInstall, +}: { + source: Source; + onClose: () => void; + onInstall: (requirement: string, editable: boolean) => void; +}) { + const tx = useTx(); + const [value, setValue] = useState(""); + const [editable, setEditable] = useState(false); + const text = value.trim(); + // pip would read a leading `-` as one of its options. + const valid = !!text && !text.startsWith("-"); + const install = () => valid && onInstall(source === "vcs" ? vcsRequirement(text) : text, editable); + return ( + +
+
+ setValue(e.target.value)} + onKeyDown={(e) => e.key === "Enter" && install()} + /> + {source === "disk" && ( + + )} +
+ + {source === "vcs" && editable && ( +
+ An editable install from version control needs the package name at the end of the URL: #egg=name. +
+ )} +
+
+ ); +} + /** `path` relative to `root` when it is inside it. */ function relativeTo(root: string | null, path: string) { const base = root?.replace(/[\\/]+$/, ""); diff --git a/src/features/python-packages/PythonPackages.module.css b/src/features/python-packages/PythonPackages.module.css index c82828de9..071a8e959 100644 --- a/src/features/python-packages/PythonPackages.module.css +++ b/src/features/python-packages/PythonPackages.module.css @@ -226,3 +226,17 @@ user-select: text; -webkit-user-select: text; } + +.installFrom { + display: flex; + flex-direction: column; + gap: var(--space-2); +} +.field { + display: flex; + gap: var(--space-1-5); +} +.field > :first-child { + flex: 1; + min-width: 0; +} diff --git a/src/features/python-packages/model.test.ts b/src/features/python-packages/model.test.ts index fdfc98a76..448e54105 100644 --- a/src/features/python-packages/model.test.ts +++ b/src/features/python-packages/model.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { isPackageName, listRows, normalize, requirementOf, rowKey } from "./model"; +import { isPackageName, listRows, normalize, requirementOf, rowKey, vcsRequirement } from "./model"; const INSTALLED = [ { name: "requests", version: "2.31.0" }, @@ -72,3 +72,14 @@ describe("names and requirements", () => { expect(requirementOf("six", null)).toBe("six"); }); }); + +describe("vcsRequirement", () => { + it("installs a repository URL with Git unless it names a VCS", () => { + expect(vcsRequirement(" https://github.com/psf/requests.git ")).toBe("git+https://github.com/psf/requests.git"); + expect(vcsRequirement("git@github.com:psf/requests.git")).toBe("git+ssh://git@github.com/psf/requests.git"); + expect(vcsRequirement("git+https://github.com/psf/requests@v2.32.0#egg=requests")).toBe( + "git+https://github.com/psf/requests@v2.32.0#egg=requests", + ); + expect(vcsRequirement("hg+https://hg.example.org/demo")).toBe("hg+https://hg.example.org/demo"); + }); +}); diff --git a/src/features/python-packages/model.ts b/src/features/python-packages/model.ts index 239bf195d..3c29aaf89 100644 --- a/src/features/python-packages/model.ts +++ b/src/features/python-packages/model.ts @@ -56,3 +56,14 @@ export function listRows( /** `name==version`, or the bare name for the newest release. */ export const requirementOf = (name: string, version: string | null) => (version ? `${name}==${version}` : name); + +/** + * What pip installs for a repository URL: `git+https://…` and other `vcs+` forms as they are, a + * plain `https://`, `ssh://` or `git://` URL and scp-like `git@host:path` as Git. + */ +export function vcsRequirement(url: string) { + const text = url.trim(); + if (/^(https?|ssh|git):\/\//i.test(text)) return `git+${text}`; + const scp = /^([\w.-]+@[\w.-]+):(?!\/\/)(.+)$/.exec(text); + return scp ? `git+ssh://${scp[1]}/${scp[2]}` : text; +} diff --git a/src/features/settings/languages/api.ts b/src/features/settings/languages/api.ts index f691d1a81..cfe563a46 100644 --- a/src/features/settings/languages/api.ts +++ b/src/features/settings/languages/api.ts @@ -186,7 +186,7 @@ export function pip( onLine: (line: string) => void, ): Streamed { return streamed( - (req, ch) => call(commands.sdkPythonPip(python, requirement, op === "uninstall", op === "upgrade", req, ch)), + (req, ch) => call(commands.sdkPythonPip(python, requirement, op === "uninstall", op === "upgrade", false, req, ch)), onLine, ); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index b018f5d12..daaf47e7c 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1946,6 +1946,16 @@ "The built-in One Dark theme was removed; the plugin provides it and its variants.": "The built-in One Dark theme was removed; the plugin provides it and its variants.", "Get more themes": "Get more themes", "Install": "Install", + "Install from Version Control or Disk": "Install from Version Control or Disk", + "Install from Version Control…": "Install from Version Control…", + "Install from Disk…": "Install from Disk…", + "Install from Version Control": "Install from Version Control", + "Install from Disk": "Install from Disk", + "Project directory or archive": "Project directory or archive", + "Repository URL": "Repository URL", + "Project Directory": "Project Directory", + "Install as editable (-e)": "Install as editable (-e)", + "An editable install from version control needs the package name at the end of the URL: #egg=name.": "An editable install from version control needs the package name at the end of the URL: #egg=name.", "Open while it streams": "Open while it streams", "Always open": "Always open", "Folded": "Folded", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c37727872..39cf3033b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2241,6 +2241,15 @@ "Inspection progress": "检查进度", "Inspection results": "检查结果", "Install": "安装", + "Install from Version Control or Disk": "从版本控制或磁盘安装", + "Install from Version Control…": "从版本控制安装…", + "Install from Disk…": "从磁盘安装…", + "Install from Version Control": "从版本控制安装", + "Install from Disk": "从磁盘安装", + "Project directory or archive": "项目目录或归档文件", + "Project Directory": "项目目录", + "Install as editable (-e)": "以可编辑模式安装 (-e)", + "An editable install from version control needs the package name at the end of the URL: #egg=name.": "从版本控制以可编辑模式安装时,URL 末尾需要写上包名:#egg=name。", "Install Docker Desktop, OrbStack, Colima or the Docker Engine and make sure": "请安装 Docker Desktop、OrbStack、Colima 或 Docker Engine,并确保", "Install Language Server / Debugger": "安装语言服务器/调试器", "Install Package": "安装软件包",