From 0b1a675fabc46452235c1e4e25a0438694e223f2 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 12:09:48 +0900 Subject: [PATCH] fix(python): install from disk never falls back to PyPI, editable only for a local directory (#6617) Install from Disk resolved only paths starting with '.', and pip runs in a temporary folder, so a bare name like 'mylib' installed the PyPI package of that name. A typed relative path is now sent as './...' (resolved against the project) and '~/' expands to the home folder, so pip always gets an absolute path. Editable installs are offered and accepted only for a local directory: an editable clone of a repository would land in pip's temporary folder. The version control dialog accepts only vcs+scheme:// URLs, and an archive disables editable. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-sdk/src/python.rs | 28 ++++++++++---- crates/ide-sdk/src/tests.rs | 31 ++++++++++++++++ docs/en/languages/python.mdx | 2 +- docs/zh/languages/python.mdx | 2 +- .../python-packages/PackagesView.test.tsx | 9 ++++- src/features/python-packages/PackagesView.tsx | 37 ++++++++++++++----- src/features/python-packages/model.test.ts | 33 ++++++++++++++++- src/features/python-packages/model.ts | 15 ++++++++ src/platform/locales/text/en.json | 1 - src/platform/locales/text/zh.json | 1 - 10 files changed, 137 insertions(+), 22 deletions(-) diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index 031de305a8..cd9c53ba68 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -426,7 +426,7 @@ pub(crate) fn neutral_dir() -> Option { } /// How packages of an interpreter are managed. -enum Installer { +pub(crate) enum Installer { Pip, /// `uv pip … --python `. Uv(PathBuf), @@ -453,7 +453,7 @@ fn installer(python: &Path) -> IdeResult { } /// `(program, args)` for a pip sub-command. -fn pip_command(python: &Path, installer: &Installer, sub: &[&str]) -> (PathBuf, Vec) { +pub(crate) fn pip_command(python: &Path, installer: &Installer, sub: &[&str]) -> (PathBuf, Vec) { match installer { Installer::Pip => { let mut args = vec!["-m".into(), "pip".into()]; @@ -570,8 +570,13 @@ pub(crate) fn parse_pip_list(out: &str) -> IdeResult> { } /// A requirement naming a local path (`.`, `./pkg`, `../lib[dev]`) made absolute -/// against `base` (the project root): pip runs in [`neutral_dir`], not the project. +/// against `base` (the project root), and `~/lib` against the home folder: pip runs in +/// [`neutral_dir`], not the project. pub(crate) fn resolve_requirement(requirement: &str, base: Option<&Path>) -> IdeResult { + if let Some(rest) = requirement.strip_prefix("~/").or_else(|| requirement.strip_prefix("~\\")) { + let home = dirs::home_dir().ok_or_else(|| IdeError::invalid("no home folder"))?; + return Ok(home.join(rest).to_string_lossy().into_owned()); + } if !requirement.starts_with('.') { return Ok(requirement.to_owned()); } @@ -625,8 +630,19 @@ pub fn install_package( return Err(IdeError::invalid("enter a package name or requirement")); } let requirement = resolve_requirement(requirement, project_root)?; + // An editable clone of a repository would go where pip runs, a temporary folder. + if editable && !Path::new(&requirement).is_absolute() { + return Err(IdeError::invalid("only a local directory can be installed in editable mode")); + } let installer = installer(python)?; let _busy = Busy::take(python)?; + let (program, args) = pip_command(python, &installer, &install_args(&requirement, upgrade, editable)); + let dir = neutral_dir(); + stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ()) +} + +/// The `install` sub-command for [`pip_command`]. +pub(crate) fn install_args(requirement: &str, upgrade: bool, editable: bool) -> Vec<&str> { let mut sub = vec!["install"]; if upgrade { sub.push("--upgrade"); @@ -634,10 +650,8 @@ pub fn install_package( if editable { sub.push("-e"); } - sub.push(&requirement); - let (program, args) = pip_command(python, &installer, &sub); - let dir = neutral_dir(); - stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ()) + sub.push(requirement); + sub } /// Run by the interpreter itself, so markers and PEP 440 specifiers are judged as pip would: diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 8595cb6130..1185d317b9 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -1901,6 +1901,37 @@ fn relative_requirements_resolve_against_the_project() { assert_eq!(resolve_requirement("./pkg", Some(root)).unwrap(), root.join("./pkg").to_string_lossy()); assert_eq!(resolve_requirement(".[dev]", Some(root)).unwrap(), root.join(".[dev]").to_string_lossy()); assert!(resolve_requirement("../lib", None).is_err()); + let home = dirs::home_dir().unwrap(); + assert_eq!(resolve_requirement("~/lib", Some(root)).unwrap(), home.join("lib").to_string_lossy()); +} + +#[test] +fn editable_installs_put_e_right_before_the_path() { + use crate::python::{Installer, install_args, pip_command}; + let python = Path::new("/env/bin/python"); + let sub = install_args("/work/lib", false, true); + let (program, args) = pip_command(python, &Installer::Pip, &sub); + assert_eq!(program, python); + assert_eq!(args, ["-m", "pip", "install", "-e", "/work/lib", "--disable-pip-version-check"]); + let (program, args) = pip_command(python, &Installer::Uv("/bin/uv".into()), &sub); + assert_eq!(program, Path::new("/bin/uv")); + assert_eq!(args, ["pip", "install", "--python", "/env/bin/python", "-e", "/work/lib"]); + assert_eq!(install_args("six", true, false), ["install", "--upgrade", "six"]); +} + +#[test] +fn only_a_local_directory_is_installed_in_editable_mode() { + let err = crate::python::install_package( + Path::new("/nonexistent/python"), + "git+https://github.com/benjaminp/six.git", + false, + true, + None, + &CancellationToken::new(), + &|_| {}, + ) + .unwrap_err(); + assert!(err.to_string().contains("editable"), "{err}"); } #[test] diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index c2d8c0baad..f609e12528 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -89,7 +89,7 @@ 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. +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; a relative path is relative to the project, and a name alone is a folder, never a PyPI package. With **Install as editable (-e)**, a project directory is installed in editable mode, so changes to its sources apply without reinstalling. Only a local directory can be editable: to edit a repository's code, clone it and install the clone from disk. Other options on the page: diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index 44bddc64e4..dcf2779dcc 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -89,7 +89,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml` 取得 PyPI 上的软件包信息后,详情面板还会列出项目链接(PyPI 页面、主页、文档、源码等)和 PyPI 上的项目说明:Markdown 格式会渲染显示,其他格式按纯文本显示。链接在浏览器中打开。 -工具栏中的 **+** 按钮可以从其他来源安装软件包:**从版本控制安装…** 接受仓库 URL(`git+https://…`;普通的 `https://`、`ssh://` 或 `git@host:path` URL 会按 Git 安装),**从磁盘安装…** 接受项目目录或 wheel、源码归档文件。勾选 **以可编辑模式安装 (-e)** 后,本地项目以可编辑模式安装,修改源码后无需重新安装即可生效;从版本控制以可编辑模式安装时,URL 末尾需要加上 `#egg=<名称>`。 +工具栏中的 **+** 按钮可以从其他来源安装软件包:**从版本控制安装…** 接受仓库 URL(`git+https://…`;普通的 `https://`、`ssh://` 或 `git@host:path` URL 会按 Git 安装),**从磁盘安装…** 接受项目目录或 wheel、源码归档文件;相对路径相对于项目,只写一个名称时也按文件夹处理,不会当作 PyPI 软件包。勾选 **以可编辑模式安装 (-e)** 后,项目目录以可编辑模式安装,修改源码后无需重新安装即可生效。只有本地目录可以以可编辑模式安装:要修改仓库中的代码,请先克隆仓库,再从磁盘安装克隆的目录。 页面上的其他选项: diff --git a/src/features/python-packages/PackagesView.test.tsx b/src/features/python-packages/PackagesView.test.tsx index d356fe739d..9689a4280a 100644 --- a/src/features/python-packages/PackagesView.test.tsx +++ b/src/features/python-packages/PackagesView.test.tsx @@ -132,6 +132,10 @@ describe("Python Packages", () => { 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" }); + // A name is not a repository, and editable is offered only for a local directory. + fireEvent.change(url, { target: { value: "requests" } }); + expect(screen.getByRole("button", { name: "Install" })).toBeDisabled(); + expect(screen.queryByRole("checkbox", { name: "Install as editable (-e)" })).toBeNull(); fireEvent.change(url, { target: { value: "https://github.com/benjaminp/six.git" } }); fireEvent.click(screen.getByRole("button", { name: "Install" })); expect(mocks.pip).toHaveBeenLastCalledWith( @@ -152,7 +156,10 @@ describe("Python Packages", () => { 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.change(path, { target: { value: "dist/mylib-0.1.0-py3-none-any.whl" } }); + expect(screen.getByRole("checkbox", { name: "Install as editable (-e)" })).toBeDisabled(); + // A bare name is a directory here, never a PyPI package. + 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( diff --git a/src/features/python-packages/PackagesView.tsx b/src/features/python-packages/PackagesView.tsx index 48da8487fd..1d6708ef3e 100644 --- a/src/features/python-packages/PackagesView.tsx +++ b/src/features/python-packages/PackagesView.tsx @@ -30,7 +30,18 @@ import { T, } from "@/ui"; import { editorService } from "@/workbench/contributions"; -import { isPackageName, listRows, normalize, requirementOf, rowKey, vcsRequirement, type Row } from "./model"; +import { + diskRequirement, + isArchive, + isPackageName, + isVcsUrl, + listRows, + normalize, + requirementOf, + rowKey, + vcsRequirement, + type Row, +} from "./model"; import styles from "./PythonPackages.module.css"; type Op = "install" | "upgrade" | "uninstall"; @@ -492,7 +503,11 @@ export function PackagesView() { type Source = "vcs" | "disk"; -/** A repository URL or a local directory or archive to install, as PyCharm's Advanced Package Install. */ +/** + * A repository URL or a local directory or archive to install, as PyCharm's Advanced Package + * Install. Only a local directory can be editable: an editable clone of a repository would go + * where pip runs, a temporary folder, unless the interpreter is a virtualenv, and uv can't do it. + */ function InstallFromDialog({ source, onClose, @@ -506,9 +521,11 @@ function InstallFromDialog({ const [value, setValue] = useState(""); const [editable, setEditable] = useState(false); const text = value.trim(); + const requirement = source === "vcs" ? vcsRequirement(text) : diskRequirement(text); // 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); + const valid = !!text && !text.startsWith("-") && (source === "disk" || isVcsUrl(requirement)); + const canEdit = source === "disk" && !isArchive(text); + const install = () => valid && onInstall(requirement, canEdit && editable); return ( )} - - {source === "vcs" && editable && ( -
- An editable install from version control needs the package name at the end of the URL: #egg=name. -
+ {source === "disk" && ( + )}
diff --git a/src/features/python-packages/model.test.ts b/src/features/python-packages/model.test.ts index 448e541059..4c0f11dfc1 100644 --- a/src/features/python-packages/model.test.ts +++ b/src/features/python-packages/model.test.ts @@ -1,5 +1,15 @@ import { describe, expect, it } from "vitest"; -import { isPackageName, listRows, normalize, requirementOf, rowKey, vcsRequirement } from "./model"; +import { + isPackageName, + listRows, + normalize, + requirementOf, + rowKey, + vcsRequirement, + diskRequirement, + isArchive, + isVcsUrl, +} from "./model"; const INSTALLED = [ { name: "requests", version: "2.31.0" }, @@ -83,3 +93,24 @@ describe("vcsRequirement", () => { expect(vcsRequirement("hg+https://hg.example.org/demo")).toBe("hg+https://hg.example.org/demo"); }); }); + +describe("install from version control or disk", () => { + it("accepts only version control URLs", () => { + expect(isVcsUrl(vcsRequirement("https://github.com/psf/requests.git"))).toBe(true); + expect(isVcsUrl("hg+https://hg.example.org/demo")).toBe(true); + expect(isVcsUrl(vcsRequirement("requests"))).toBe(false); + expect(isVcsUrl(vcsRequirement("file:///tmp/pkg"))).toBe(false); + }); + + it("never lets a typed path read as a PyPI name", () => { + expect(diskRequirement(" mylib ")).toBe("./mylib"); + expect(diskRequirement("pkgs/mylib")).toBe("./pkgs/mylib"); + expect(diskRequirement("src\\mylib")).toBe("./src\\mylib"); + for (const path of ["./mylib", "../lib", "/work/lib", "~/lib", "C:\\work\\lib", "\\\\server\\lib"]) { + expect(diskRequirement(path)).toBe(path); + } + expect(isArchive("dist/demo-1.0.tar.gz")).toBe(true); + expect(isArchive("dist/demo-1.0-py3-none-any.whl")).toBe(true); + expect(isArchive("pkgs/demo")).toBe(false); + }); +}); diff --git a/src/features/python-packages/model.ts b/src/features/python-packages/model.ts index 3c29aaf890..a10376074a 100644 --- a/src/features/python-packages/model.ts +++ b/src/features/python-packages/model.ts @@ -67,3 +67,18 @@ export function vcsRequirement(url: string) { const scp = /^([\w.-]+@[\w.-]+):(?!\/\/)(.+)$/.exec(text); return scp ? `git+ssh://${scp[1]}/${scp[2]}` : text; } + +/** Whether `url` (after {@link vcsRequirement}) is a version control URL pip can install. */ +export const isVcsUrl = (url: string) => /^(git|hg|svn|bzr)\+[a-z]+:\/\/\S+$/i.test(url); + +/** + * A path typed for Install from Disk, made explicit so pip never reads it as a PyPI name: a + * relative one starts with `./` (the host resolves it against the project, and `~/` against home). + */ +export function diskRequirement(path: string) { + const text = path.trim(); + return /^([./\\~]|[A-Za-z]:[\\/])/.test(text) ? text : `./${text}`; +} + +/** A wheel or source archive, which pip can install but not in editable mode. */ +export const isArchive = (path: string) => /\.(whl|zip|tar\.gz|tgz|tar\.bz2|tar\.xz)$/i.test(path.trim()); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 0337b8f423..16d3a9cac4 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1961,7 +1961,6 @@ "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 b737d8f9c4..48db59e91c 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2255,7 +2255,6 @@ "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": "安装软件包",