feat(python): install packages from version control or a local directory (#6601)

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 <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 08:37:01 +08:00
1 джерело 3747a8a63f
коміт ddea7e5ec5
15 files changed
+237 -14

No files matched your search

+12 -2
Переглянути файл
@@ -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<String>,
) -> 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;
+7 -2
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -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=<name>` at the end of the URL.
Other options on the page:
- **Activate virtualenv** (section **Terminal**): new terminal sessions run the virtualenv's activate script.
+2
Переглянути файл
@@ -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**(**终端** 分组):新的终端会话会运行虚拟环境的激活脚本。
+5 -2
Переглянути файл
@@ -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<string | null, IdeError>(__TAURI_INVOKE("sdk_python_package_index", { python, request })),
sdkPythonPackages: (python: string, outdated: boolean, request: RequestId) => typedError<PythonPackage[], IdeError>(__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<string>) => typedError<null, IdeError>(__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<string>) => typedError<null, IdeError>(__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<ProjectInterpreter[], IdeError>(__TAURI_INVOKE("sdk_python_project_interpreters")),
/** `sys.path` of the interpreter `python`, for All Interpreters › Show Paths. */
+1 -1
Переглянути файл
@@ -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)}`);
}
+1 -1
Переглянути файл
@@ -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) {
+52 -1
Переглянути файл
@@ -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<typeof import("@/ui")>()),
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<typeof import("@/platform/ipc")>();
@@ -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(),
);
+98 -3
Переглянути файл
@@ -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<Job | null>(null);
const [log, setLog] = useState<string[]>([]);
const [jobError, setJobError] = useState<string | null>(null);
const [installFrom, setInstallFrom] = useState<Source | null>(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<string>();
@@ -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 && (
<IconButton
icon="plus"
size="small"
title="Install from Version Control or Disk"
disabled={!python || !!job}
onClick={(e) => {
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 && (
<span className={styles.interpreter} title={python}>
{relativeTo(root, python)}
@@ -456,10 +476,85 @@ export function PackagesView() {
</pre>
)}
</SplitPanel>
{installFrom && (
<InstallFromDialog
source={installFrom}
onClose={() => setInstallFrom(null)}
onInstall={(requirement, editable) => {
setInstallFrom(null);
run("install", requirement, editable);
}}
/>
)}
</SplitGroup>
);
}
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 (
<Dialog
open
title={source === "vcs" ? "Install from Version Control" : "Install from Disk"}
onClose={onClose}
width={520}
buttons={[
{ label: tx("Cancel"), role: "cancel" },
{ label: tx("Install"), role: "default", onClick: install, disabled: !valid },
]}
>
<div className={styles.installFrom}>
<div className={styles.field}>
<Input
autoFocus
value={value}
placeholder={
source === "vcs" ? "git+https://github.com/owner/project.git" : tx("Project directory or archive")
}
aria-label={source === "vcs" ? "Repository URL" : "Path"}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && install()}
/>
{source === "disk" && (
<Button
onClick={() =>
void choosePath({ directory: true, title: tx("Project Directory") }).then(
(path) => path && setValue(path),
)
}
>
<T>Browse</T>
</Button>
)}
</div>
<Checkbox checked={editable} onChange={setEditable} label="Install as editable (-e)" />
{source === "vcs" && editable && (
<div className={styles.note}>
<T>An editable install from version control needs the package name at the end of the URL: #egg=name.</T>
</div>
)}
</div>
</Dialog>
);
}
/** `path` relative to `root` when it is inside it. */
function relativeTo(root: string | null, path: string) {
const base = root?.replace(/[\\/]+$/, "");
+14
Переглянути файл
@@ -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;
}
+12 -1
Переглянути файл
@@ -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("[email protected]:psf/requests.git")).toBe("git+ssh://[email protected]/psf/requests.git");
expect(vcsRequirement("git+https://github.com/psf/[email protected]#egg=requests")).toBe(
"git+https://github.com/psf/[email protected]#egg=requests",
);
expect(vcsRequirement("hg+https://hg.example.org/demo")).toBe("hg+https://hg.example.org/demo");
});
});
+11
Переглянути файл
@@ -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;
}
+1 -1
Переглянути файл
@@ -186,7 +186,7 @@ export function pip(
onLine: (line: string) => void,
): Streamed<null> {
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,
);
}
+10
Переглянути файл
@@ -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",
+9
Переглянути файл
@@ -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": "安装软件包",