From 2b9788a0674be49ecfc5d2bafb9d62b967cc9587 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 11:53:32 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(python):=20=E6=96=B0=E5=A2=9E=E6=89=8B?= =?UTF-8?q?=E5=8A=A8=E8=BF=90=E8=A1=8C=E9=85=8D=E7=BD=AE=E4=B8=8E=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 13 +- README.md | 11 +- docs/feature-matrix.md | 6 +- .../python_project_workflow_e2e_test.go | 214 ++++++++++++++++++ .../THIRD-PARTY-NOTICES.txt | 7 + .../l10n/zh-Hans.json | 26 +++ .../plugin.json | 55 +++++ .../scripts/dependencies.py | 108 +++++++++ scripts/package.mjs | 31 ++- scripts/package/archives.test.mjs | 3 + scripts/test.mjs | 43 ++++ vendor-lock.json | 8 + 12 files changed, 501 insertions(+), 24 deletions(-) create mode 100644 e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go create mode 100644 io.github.lithe-idea.python-support/scripts/dependencies.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e50db2..0c47a96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,7 +115,16 @@ jobs: path: dist - name: Install pytest for the host suite run: python -m pip install --disable-pip-version-check pytest - - name: Verify Python highlighting and current-file run on Lithe 0.8.9 - run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride)?)$' + - name: Verify Python highlighting, run configurations, and dependencies on Lithe 0.8.9 + run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride)?|ManualRunAndDependencies)$' - name: Run the full Python host suite on the pinned desktop + env: + GOFLAGS: -tags=vivahead + LITHE_PYTHON_VISUAL_DIR: ${{ runner.temp }}/python-workbench-screenshots run: PYTEST_PYTHON="$(command -v python)" node scripts/e2e-host.mjs + - name: Upload the Python workbench screenshots + uses: actions/upload-artifact@v4 + with: + name: python-workbench-screenshots + path: ${{ runner.temp }}/python-workbench-screenshots/*.png + if-no-files-found: error diff --git a/README.md b/README.md index d821b70..a0913be 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。 - 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划。默认使用项目选定的 Python;指定「Python 解释器覆盖」时,使用宿主解析的显式解释器。 - `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。 + - 在「运行/调试配置 → + → Python」手动配置脚本路径或模块名。可设置解释器选项、脚本参数、工作目录和环境变量。运行时沿用项目的 Python 工具链及解释器覆盖设置,支持选用 Conda、uv 和普通虚拟环境。 + - 构建面板的「依赖」显示所选解释器中已安装的 Python 包版本与依赖关系。展开或重新加载时读取发行包元数据,支持无 pip 的环境。包共享的子树只展开一次,循环依赖以叶节点结束。 - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 - `uv`(`uv.lock`):`uv sync`、`uv lock`。 - `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。 @@ -70,12 +72,13 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 ### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`) -声明式启动的语言服务器子进程、调试适配器和测试发现命令由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`。用户主动取消或停止不记录。 +声明式启动的语言服务器子进程、调试适配器、依赖查询和测试发现命令由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`。用户主动取消或停止不记录。 | `operation` | 声明来源 | 记录方 | 成功事件与级别 | 失败事件与级别 | 可能的 `host.*` 失败类别标识(`code`) | | --- | --- | --- | --- | --- | --- | | `languageServer/start` | `languageServers[]`(`pyrefly.resolveLaunch` 解析后的 `pyrefly lsp` 进程) | 启动前失败由桌面宿主记录;进入启动后经 `lsp.startServer.startupOperation` 交由 Core 记录唯一终态 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | | `debugAdapter/start` | `debugAdapters[]`(`debugpy`) | 桌面宿主(`op` 为调试会话 ID;用户停止与 Core 拒绝建会话不记录) | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | +| `lithe/build/dependencies` | `buildSystems[].dependencies`(读取所选解释器的包元数据) | 桌面宿主 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.commandFailed`、`host.timedOut`、`host.outputInvalid` | | `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand`(`pytest --collect-only`) | 桌面宿主 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.commandFailed`、`host.timedOut`、`host.outputInvalid` | ### 3. 上游子进程通道、隐私红线与原生日志文件 @@ -95,11 +98,13 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | 路径 | 归属与用途 | 生命周期 | 跨 Git Worktree 复用策略 | | --- | --- | --- | --- | -| `.cache/` | `scripts/package.mjs` 下载并经 SHA-256 校验的上游原始归档(`pyrefly` 6 平台压缩包、`debugpy` wheel、`tomli` wheel) | 本地持久化缓存(已被 `.gitignore` 忽略) | **可安全复制复用**(文件名含上游版本与平台,读取前强制校验 `vendor-lock.json` SHA-256;复制到新工作树 `.cache/`,勿跨并发打包共享写) | +| `.cache/` | `scripts/package.mjs` 下载并经 SHA-256 校验的上游原始归档(`pyrefly` 6 平台压缩包、`debugpy` wheel、`tomli` wheel、`packaging` wheel) | 本地持久化缓存(已被 `.gitignore` 忽略) | **可安全复制复用**(文件名含上游版本与平台,读取前强制校验 `vendor-lock.json` SHA-256;复制到新工作树 `.cache/`,勿跨并发打包共享写) | | `backend/target/` | Rust 后端编译输出,包含按平台目标区分的产物 | 随工作树保留,可重新由 Cargo 生成 | 不共享,构建时由固定的 Cargo.lock 和 Rust 目标重建。Cargo 使用全局 registry 与 Git 依赖下载缓存。 | | `.artifacts/stage/` | 打包过程中的单平台解包暂存目录 | 每次 `scripts/package.mjs` 按平台重建(`.gitignore` 忽略) | **不可复用**(构建中间产物,毫秒级重建) | | `.artifacts/lithe-host/` | `scripts/e2e-host.mjs` 检出的宿主稀疏工作树及其编译产物 | 本地按需保留(`.gitignore` 忽略) | 其内部 `.artifacts/desktop` 在同一操作系统、CPU 架构与相同 `PINNED_CORE_REVISION` 前提下可按宿主规则复制加速,不得跨工作树软链共用;任何运行时会话日志目录(`sessions//plugins/.../files/`)与状态目录严禁跨工作树复制 | | `grammars/python.first-line.json`(插件包内) | 插件的 TextMate 首行元数据。普通文件和按首行识别的脚本都沿用宿主的 `source.python` 高亮 | 构建时随 ZIP 打包,运行时只读,随插件版本更新或卸载 | 由插件源码随包生成,无运行时缓存 | +| `vendor/packaging/`(插件包内) | 依赖查询用的 PEP 508 解析器,版本和 SHA-256 见 `vendor-lock.json` | 构建阶段解包,运行时只读,随插件更新或卸载 | 按锁定的 wheel 重建 | +| 依赖查询报告 | 宿主为每次查询在插件的工作区状态目录分配临时文件 | 宿主读取并清理,运行结束后无需保留 | 不复制 | | `dist/` | 最终产出的 `python-support--.zip` 发布包 | 打包输出(`.gitignore` 忽略) | 按需重新运行 `node scripts/package.mjs` 生成 | ### 常用命令 @@ -137,5 +142,5 @@ node scripts/e2e-host.mjs --source /path/to/Lithe-IDEA --ref COMPATIBLE_HOST_COM ## 许可证(License) - 插件清单、Rust 后端、脚本、模板、图标与文档采用 [Apache-2.0](LICENSE) 许可协议。 -- 随包分发的第三方开源组件(Pyrefly `1.4.1`、debugpy `1.8.22`、Tomli `2.5.0`,均为 MIT 许可)完整版权声明与许可证全文见 [io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt](io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt) 及包内 `vendor/debugpy/ThirdPartyNotices.txt`。 +- 随包分发的第三方开源组件(Pyrefly `1.4.1`、debugpy `1.8.22`、Tomli `2.5.0`,均为 MIT 许可)完整版权声明与许可证全文见 [io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt](io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt) 及包内 `vendor/debugpy/ThirdPartyNotices.txt`。Packaging `25.0` 采用 Apache-2.0 或 BSD-2-Clause,原始许可证随包分发。 - Rust 后端的依赖及对应许可证由 `Cargo.lock` 固定,全文随包附在 `RUST-THIRD-PARTY-NOTICES.txt`。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 3b3239a..7a76819 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -18,6 +18,8 @@ | 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`) | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用项目 Python 或经宿主解析的显式解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | +| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用项目选定的解释器或插件解释器覆盖设置。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | +| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时读取所选 Python 环境中已安装的包、版本和依赖关系,解析 PEP 508 条件和可选依赖。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | @@ -28,9 +30,9 @@ ## 宿主版本与验证 -- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。 +- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1`、`runConfigurationTypes: 0` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。 - `e2e/host/lithe-host.json` 固定支持 TextMate 首行匹配的桌面主线提交 `645a3aee8`。 -- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮和当前文件运行,并在固定的桌面主线上运行完整宿主套件,额外覆盖项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。 +- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮、当前文件运行、手动运行配置和依赖树,并在固定的桌面主线上运行完整宿主套件,额外覆盖项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。 - macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。 - 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。 - 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go new file mode 100644 index 0000000..014885c --- /dev/null +++ b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go @@ -0,0 +1,214 @@ +package workbench + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestPythonSupportPluginManualRunAndDependencies(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + root = filepath.Join(root, "manual-run") + venv := filepath.Join(root, ".venv") + python := "python3" + executable := filepath.Join(venv, "bin", "python") + if runtime.GOOS == "windows" { + python = "python" + executable = filepath.Join(venv, "Scripts", "python.exe") + } + if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", venv).CombinedOutput(); err != nil { + t.Fatalf("create project environment: %v\n%s", err, output) + } + site, err := exec.CommandContext(ctx, executable, "-I", "-B", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))").Output() + if err != nil { + t.Fatal(err) + } + work := filepath.Join(root, "work") + if err := os.Mkdir(work, 0o700); err != nil { + t.Fatal(err) + } + write := func(path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + program := "import os, sys\nprint(sys.prefix)\nprint(os.getcwd())\nprint(sys.flags.dev_mode, os.environ['PROFILE_TEST'], repr(sys.argv[1:]))\n" + write(filepath.Join(root, "requirements.txt"), "root-demo==1.0\n") + write(filepath.Join(root, "manual script.py"), program) + write(filepath.Join(work, "manual_module.py"), program) + purelib := strings.TrimSpace(string(site)) + write(filepath.Join(purelib, "root_demo-1.0.dist-info", "METADATA"), "Name: root-demo\nVersion: 1.0\nRequires-Dist: child-demo\n") + write(filepath.Join(purelib, "child_demo-2.0.dist-info", "METADATA"), "Name: child-demo\nVersion: 2.0\n") + + kernel := core.NewClient() + preferences := store.At(t.TempDir()) + if err := preferences.Save(settingsFile, settings{Theme: themeDark}); err != nil { + t.Fatal(err) + } + trust, err := toolchain.ReadWorkspaceTrust(ctx, kernel, preferences.Dir(), root) + if err != nil { + t.Fatal(err) + } + if _, err := trust.Save(ctx, kernel, true, false); err != nil { + t.Fatal(err) + } + options := Options{ + Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences, + Languages: []string{"zh-Hans"}, + } + out := os.Getenv("LITHE_PYTHON_VISUAL_DIR") + openHarness := newHarnessWithOptions + var session *headless.Session + if out != "" { + if err := os.MkdirAll(out, 0o700); err != nil { + t.Fatal(err) + } + openHarness = func(t testing.TB, options Options) *harness { + return newHarnessWithDriver(t, options, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1280, 840 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + } + } + h := openHarness(t, options) + capture := func(t *testing.T, name string) { + t.Helper() + if session != nil { + // The console prints temporary fixture paths that are irrelevant to the screenshots. + h.app.post(func(a *App) { a.reduceChrome(core.SetChromeOpen(itemRun, false)) }) + h.settleChain() + if err := session.Screenshot(filepath.Join(out, name+".png")); err != nil { + t.Fatal(err) + } + } + } + installPythonArchive(t, ctx, h.app.plugins, pythonArchiveForE2E(t)) + h.open(root) + p := h.app.project + key := core.RunTypeKey{PluginID: pythonSupportPluginID, BuildSystemID: "python", Type: "python"} + h.app.post(func(a *App) { a.loadTitleRunConfigs(p) }) + awaitStateWithin(t, h, 10*time.Second, "the Python run kind and build instance", func() bool { + return p.runConfigs.runTypeKind(key) != nil && p.hasRunTypeInstance(key) + }) + + h.app.post(func(a *App) { + a.openRunConfigDialog(p, "") + p.runConfigs.dialog.newMenu = runConfigNewMenuToolbar + }) + capture(t, "python-run-menu") + + for _, target := range []struct{ kind, field, value string }{ + {"script", "script", "manual script.py"}, + {"module", "module", "manual_module"}, + } { + t.Run(target.kind, func(t *testing.T) { + dialog := &p.runConfigs.dialog + h.app.post(func(a *App) { + a.openRunConfigDialog(p, "") + a.addRunConfigDraft(p, declaredKind(key), map[string]json.RawMessage{ + "field:targetKind": json.RawMessage(`"` + target.kind + `"`), + }) + }) + var form *runConfigForm + awaitStateWithin(t, h, 10*time.Second, "the Python run editor", func() bool { + draft := dialog.drafts[dialog.selected] + if draft != nil { + form = draft.form + } + return form != nil && form.ready() && form.texts["field:"+target.field] != nil + }) + h.settle() + if !h.shows("运行目标") { + t.Fatal("the dialog does not show the localized Python run target") + } + label := "Manual Python " + target.kind + h.app.post(func(a *App) { + *form.texts["name"] = label + *form.texts["field:"+target.field] = target.value + *form.texts["field:interpreterOptions"] = "-X dev" + *form.texts["workingDirectory"] = "work" + *form.texts["programArguments"] = `"two words" plain` + form.environment = []*runConfigVariable{{name: "PROFILE_TEST", value: "present"}} + a.runConfigFormEdited(p, form) + }) + awaitStateWithin(t, h, 10*time.Second, "the edited Python run form", func() bool { return !form.refreshing }) + capture(t, "python-run-"+target.kind) + applyDialog(t, h, p, runConfigDialogRun) + output := awaitProcessRun(t, h, p, label, nil).output.all() + for _, want := range []string{venv, work, "True present ['two words', 'plain']"} { + if !strings.Contains(output, want) { + t.Fatalf("run output misses %q:\n%s", want, output) + } + } + }) + } + + var instance *buildInstance + awaitStateWithin(t, h, 10*time.Second, "the Python model with a project", func() bool { + for index := range p.build.instances { + candidate := &p.build.instances[index] + if candidate.BuildSystemID == "python" && candidate.modelLoaded && len(candidate.Model.Projects) == 1 { + instance = candidate + return true + } + } + return false + }) + h.app.post(func(a *App) { a.reduceChrome(core.SetChromeOpen(itemBuild, true)) }) + var section buildRow + awaitStateWithin(t, h, 10*time.Second, "the Dependencies section in the Build panel", func() bool { + rows, _ := h.app.buildTreeRows(p) + for _, row := range rows { + if row.node != nil && row.node.Kind == core.BuildTreeDependencies && p.build.instances[row.instance].ID == instance.ID { + section = row + return true + } + } + return false + }) + h.app.post(func(a *App) { + p.setBuildOpen(buildOpenKey(instance.ID, section.node.Key), buildOpenState{open: true, dependencies: true}) + }) + var dependencies *buildDependencies + awaitStateWithin(t, h, 10*time.Second, "the installed Python package in the Build panel", func() bool { + rows, _ := h.app.buildTreeRows(p) + for _, row := range rows { + if row.kind == buildRowDependency && row.label == "root-demo:1.0" { + dependencies = p.build.dependencies[buildDependencyKey(instance.ID, section.node.ProjectID)] + return true + } + } + return false + }) + h.app.post(func(a *App) { dependencies.open["0"] = true }) + awaitStateWithin(t, h, 10*time.Second, "the transitive package in the Build panel", func() bool { + return h.shows("child-demo:2.0") + }) + capture(t, "python-dependency-tree") +} diff --git a/io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt b/io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt index 64f9f7a..db64bb5 100644 --- a/io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt +++ b/io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt @@ -87,3 +87,10 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------- +4. Packaging 25.0 (https://github.com/pypa/packaging) +------------------------------------------------------------------------------- + +Packaging is dual-licensed under Apache-2.0 or BSD-2-Clause. The upstream +licenses are included in vendor/packaging-25.0.dist-info/licenses/. diff --git a/io.github.lithe-idea.python-support/l10n/zh-Hans.json b/io.github.lithe-idea.python-support/l10n/zh-Hans.json index 61d838f..21d7947 100644 --- a/io.github.lithe-idea.python-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.python-support/l10n/zh-Hans.json @@ -1,5 +1,31 @@ { "$schema": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/plugin-l10n.schema.json", + "runConfigurationTypes": { + "python": { + "python": { + "displayName": "Python", + "description": "使用当前项目选定的解释器运行 Python 脚本或模块。", + "fields": { + "targetKind": { + "title": "运行目标", + "options": { + "script": "脚本", + "module": "模块" + } + }, + "script": { "title": "脚本路径" }, + "module": { + "title": "模块名", + "description": "通过 -m 传给 Python 的点分隔导入名称。" + }, + "interpreterOptions": { + "title": "解释器选项", + "description": "放在脚本或模块之前的 Python 选项。" + } + } + } + } + }, "settings": { "pythonExecutable": { "title": "Python 解释器覆盖路径", diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index bcb0ad3..59ff102 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -19,6 +19,7 @@ "languages": 0, "outputLinkMatchers": 0, "projectGenerators": 0, + "runConfigurationTypes": 0, "settings": 0, "toolDefinitions": 0, "toolchainProviders": 0 @@ -543,6 +544,60 @@ ] } ], + "runConfigurationTypes": [ + { + "id": "python", + "displayName": "Python", + "description": "Run a Python script or module with the interpreter selected for this project.", + "icon": { "path": "icons/python.svg" }, + "fields": [ + { + "id": "targetKind", + "title": "Run target", + "kind": "choice", + "default": "script", + "choices": [ + { "value": "script", "title": "Script" }, + { "value": "module", "title": "Module" } + ] + }, + { + "id": "script", + "title": "Script path", + "kind": "file", + "required": true, + "visibleWhen": { "field": "targetKind", "equals": "script" } + }, + { + "id": "module", + "title": "Module name", + "description": "A dotted import name passed to Python with -m.", + "kind": "text", + "placeholder": "package.module", + "required": true, + "visibleWhen": { "field": "targetKind", "equals": "module" }, + "arguments": ["-m", "${value}"] + }, + { + "id": "interpreterOptions", + "title": "Interpreter options", + "description": "Options passed to Python before the script or module.", + "kind": "arguments", + "placeholder": "-X dev" + } + ], + "arguments": ["${field:interpreterOptions}", "${field:script}", "${field:module}", "${userArguments}"] + } + ], + "dependencies": { + "source": "command", + "scopes": ["project"], + "arguments": ["-E", "-B", "${pluginDir}/scripts/dependencies.py", "${outputFile}"], + "output": "outputFile", + "decoder": "litheDependencies", + "executesProjectCode": true, + "mayUseNetwork": false + }, "run": [ { "id": "main", diff --git a/io.github.lithe-idea.python-support/scripts/dependencies.py b/io.github.lithe-idea.python-support/scripts/dependencies.py new file mode 100644 index 0000000..230d05a --- /dev/null +++ b/io.github.lithe-idea.python-support/scripts/dependencies.py @@ -0,0 +1,108 @@ +"""Adapt the selected interpreter's installed distribution metadata to Lithe's build tree.""" + +import json +import sys +import warnings +from collections import deque +from importlib import metadata +from pathlib import Path + +# Run with -E -B to ignore inherited PYTHONPATH and still inspect the selected +# interpreter's normal site directories. Resolve PEP 508 with the bundled parser, +# even in a pip-free environment. Remove its path before discovering packages. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "vendor")) +try: + from packaging.requirements import InvalidRequirement, Requirement + from packaging.utils import InvalidName, canonicalize_name +finally: + sys.path.pop(0) + + +# Leave room for the host's JSON nesting and dependency count limits. +MAX_DEPTH = 48 +MAX_NODES = 10_000 + + +def installed_graph(): + packages = {} + for distribution in metadata.distributions(): + info = distribution.metadata + name = info.get("Name") + if not name: + continue + try: + key = canonicalize_name(name, validate=True) + except InvalidName: + warnings.warn("ignoring invalid installed distribution name", stacklevel=2) + continue + # importlib.metadata yields distributions in import path order. + packages.setdefault(key, (name, info)) + if len(packages) > MAX_NODES: + raise ValueError("litheDependencies: maximum dependency count exceeded") + + dependencies = {key: set() for key in packages} + requirements = {} + for key, (name, info) in packages.items(): + requirements[key] = [] + for raw in info.get_all("Requires-Dist") or []: + try: + requirement = Requirement(raw) + except InvalidRequirement: + warnings.warn(f"{name}: invalid Requires-Dist metadata", stacklevel=2) + continue + child = canonicalize_name(requirement.name) + if child in packages: + requirements[key].append((child, requirement)) + + # Evaluate PEP 508 markers in this interpreter. Follow explicitly requested + # extras transitively. An installed package alone does not imply an extra. + pending = deque((key, "") for key in packages) + visited = set(pending) + while pending: + key, extra = pending.popleft() + for child, requirement in requirements[key]: + if requirement.marker and not requirement.marker.evaluate({"extra": extra}): + continue + dependencies[key].add(child) + for child_extra in requirement.extras: + state = (child, canonicalize_name(child_extra)) + if state not in visited: + visited.add(state) + pending.append(state) + + return packages, dependencies + + +def dependency_tree(packages, dependencies): + expanded = set() + nodes = 0 + + def tree_node(key, depth=0): + nonlocal nodes + nodes += 1 + if nodes > MAX_NODES: + raise ValueError("litheDependencies: maximum dependency count exceeded") + name, info = packages[key] + node = {"name": name, "children": []} + if version := info.get("Version"): + node["version"] = version + if key not in expanded and depth < MAX_DEPTH: + # Expand each package once. Shared dependencies and cycles remain + # visible as leaf references, with no exponential tree growth. + expanded.add(key) + node["children"] = [ + tree_node(child, depth + 1) for child in sorted(dependencies[key]) + ] + return node + + required = set().union(*dependencies.values()) + roots = [tree_node(key) for key in sorted(packages.keys() - required)] + # A disconnected cycle has no root. This also preserves branches beyond the + # host depth limit by starting their unexpanded nodes at the top level. + roots.extend(tree_node(key) for key in sorted(packages) if key not in expanded) + return {"format": "litheDependencies", "version": 0, "dependencies": roots} + + +if __name__ == "__main__": + result = dependency_tree(*installed_graph()) + Path(sys.argv[1]).write_text(json.dumps(result), encoding="utf-8") diff --git a/scripts/package.mjs b/scripts/package.mjs index 66cacf0..1d47bf0 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -161,20 +161,16 @@ export async function packagePlatforms({ platforms, expectTag, cleanDist = false } mkdirSync(distDir, { recursive: true }); - const debugpySpec = lock.wheels.debugpy; - const tomliSpec = lock.wheels.tomli; - const debugpyWheel = await ensureCachedArtifact({ - cacheDir, - filename: debugpySpec.filename, - url: debugpySpec.url, - expectedSha256: debugpySpec.sha256, - }); - const tomliWheel = await ensureCachedArtifact({ - cacheDir, - filename: tomliSpec.filename, - url: tomliSpec.url, - expectedSha256: tomliSpec.sha256, - }); + const wheels = new Map(); + for (const name of ["debugpy", "tomli", "packaging"]) { + const spec = lock.wheels[name]; + wheels.set(name, await ensureCachedArtifact({ + cacheDir, + filename: spec.filename, + url: spec.url, + expectedSha256: spec.sha256, + })); + } const notices = dependencyNotices(ROOT); const built = []; @@ -221,10 +217,11 @@ export async function packagePlatforms({ platforms, expectTag, cleanDist = false writeFileSync(noticesDest, notices, "utf8"); chmodSync(noticesDest, 0o644); - // Extract debugpy and tomli into vendor/. const vendorDir = join(stagePackageDir, "vendor"); - extractWheelSubtree(debugpyWheel, "debugpy", vendorDir); - extractWheelSubtree(tomliWheel, "tomli", vendorDir); + for (const [name, wheel] of wheels) { + extractWheelSubtree(wheel, name, vendorDir); + } + extractWheelSubtree(wheels.get("packaging"), `packaging-${lock.wheels.packaging.version}.dist-info/licenses`, vendorDir); const relZipPath = `dist/${ASSET_PREFIX}-${baseManifest.version}-${platform}.zip`; const absZipPath = resolve(ROOT, relZipPath); diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index 6587528..e4147a6 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -103,10 +103,13 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla `${PACKAGE_ID}/scripts/build_provider.py`, `${PACKAGE_ID}/scripts/run_entrypoint.py`, `${PACKAGE_ID}/scripts/discover_tests.py`, + `${PACKAGE_ID}/scripts/dependencies.py`, `${PACKAGE_ID}/scripts/debugpy_adapter.py`, `${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`, `${PACKAGE_ID}/vendor/debugpy/ThirdPartyNotices.txt`, `${PACKAGE_ID}/vendor/tomli/__init__.py`, + `${PACKAGE_ID}/vendor/packaging/requirements.py`, + `${PACKAGE_ID}/vendor/packaging-${lock.wheels.packaging.version}.dist-info/licenses/LICENSE`, `${PACKAGE_ID}/templates/python/project/pyproject.toml`, `${PACKAGE_ID}/templates/python/project/dot-gitignore`, `${PACKAGE_ID}/templates/python/sample/main.py`, diff --git a/scripts/test.mjs b/scripts/test.mjs index 4959f7b..2580d00 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -309,6 +309,48 @@ try { const pluginManifest = JSON.parse(readFileSync(join(unpackedPluginDir, "plugin.json"), "utf8")); + await check("dependency command reads installed packages from a pip-free Python environment", () => { + const environment = join(scratch, "dependency environment"); + run(pythonCmd, ["-m", "venv", "--without-pip", environment]); + const python = process.platform === "win32" + ? join(environment, "Scripts", "python.exe") + : join(environment, "bin", "python"); + const packages = run(python, ["-I", "-B", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"]).trim(); + const metadata = (name, version, requirements = []) => { + const directory = join(packages, `${name}-${version}.dist-info`); + mkdirSync(directory); + writeFileSync(join(directory, "METADATA"), [ + "Metadata-Version: 2.1", + `Name: ${name}`, + `Version: ${version}`, + ...requirements.map((requirement) => `Requires-Dist: ${requirement}`), + "", + ].join("\n")); + }; + metadata("App", "1.0", ["Lib_core[Speed] >= 1", 'Inactive; python_version < "3.0"']); + metadata("lib-core", "1.2", ['Fast; extra == "speed"', 'Inactive; extra == "test"']); + metadata("Fast", "2.0"); + metadata("Inactive", "3.0"); + metadata("CycleA", "4.0", ["CycleB"]); + metadata("CycleB", "5.0", ["CycleA"]); + + const treeFile = join(scratch, "dependencies.json"); + const declaration = pluginManifest.buildSystems.find(({ id }) => id === "python").dependencies; + assert.equal(declaration.output, "outputFile"); + assert.equal(declaration.decoder, "litheDependencies"); + const args = declaration.arguments.map((arg) => + arg.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", treeFile)); + run(python, args, { cwd: scratch }); + const leaf = (name, version, children = []) => ({ name, version, children }); + assert.deepEqual(JSON.parse(readFileSync(treeFile, "utf8")), { + format: "litheDependencies", version: 0, dependencies: [ + leaf("App", "1.0", [leaf("lib-core", "1.2", [leaf("Fast", "2.0")])]), + leaf("Inactive", "3.0"), + leaf("CycleA", "4.0", [leaf("CycleB", "5.0", [leaf("CycleA", "4.0")])]), + ], + }); + }); + await check("Unix and Windows plugin.json + zh-Hans.json satisfy M3 contract invariants", () => { const metadata = JSON.parse(readFileSync(join(unpackedPluginDir, "grammars", "python.first-line.json"), "utf8")); assert.deepEqual(Object.keys(metadata), ["firstLineMatch"]); @@ -362,6 +404,7 @@ try { "languages", "outputLinkMatchers", "projectGenerators", + "runConfigurationTypes", "settings", "toolDefinitions", "toolchainProviders", diff --git a/vendor-lock.json b/vendor-lock.json index 895b064..28472f7 100644 --- a/vendor-lock.json +++ b/vendor-lock.json @@ -64,6 +64,14 @@ "filename": "tomli-2.5.0-py3-none-any.whl", "url": "https://files.pythonhosted.org/packages/60/3f/3e3f8fd0919249b0200c80fbc4f9a1e70be19f9883da71dfb7f8b9ab8aca/tomli-2.5.0-py3-none-any.whl", "sha256": "32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b" + }, + "packaging": { + "version": "25.0", + "license": "Apache-2.0 OR BSD-2-Clause", + "repository": "https://github.com/pypa/packaging", + "filename": "packaging-25.0-py3-none-any.whl", + "url": "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", + "sha256": "29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484" } } } From 80411438a3d61573f3435edea720a7ad50311b5f Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 12:37:31 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(python):=20=E8=AF=86=E5=88=AB=E4=BB=85?= =?UTF-8?q?=E6=9C=89=20Conda=20=E6=B8=85=E5=8D=95=E7=9A=84=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/feature-matrix.md | 2 +- .../workbench/python_project_workflow_e2e_test.go | 13 +++++++++---- io.github.lithe-idea.python-support/plugin.json | 8 ++++++-- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a0913be..40e0902 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。 - 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划。默认使用项目选定的 Python;指定「Python 解释器覆盖」时,使用宿主解析的显式解释器。 - `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。 + - 仅用 `environment.yml` 或 `environment.yaml` 管理 Conda 环境的项目也会识别为 Python 构建实例。 - 在「运行/调试配置 → + → Python」手动配置脚本路径或模块名。可设置解释器选项、脚本参数、工作目录和环境变量。运行时沿用项目的 Python 工具链及解释器覆盖设置,支持选用 Conda、uv 和普通虚拟环境。 - 构建面板的「依赖」显示所选解释器中已安装的 Python 包版本与依赖关系。展开或重新加载时读取发行包元数据,支持无 pip 的环境。包共享的子树只展开一次,循环依赖以叶节点结束。 - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 7a76819..6ea737b 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -19,7 +19,7 @@ | 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用项目 Python 或经宿主解析的显式解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | | 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用项目选定的解释器或插件解释器覆盖设置。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | -| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时读取所选 Python 环境中已安装的包、版本和依赖关系,解析 PEP 508 条件和可选依赖。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | +| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时读取所选 Python 环境中已安装的包、版本和依赖关系,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | diff --git a/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go index 014885c..fbda9b6 100644 --- a/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go @@ -54,7 +54,8 @@ func TestPythonSupportPluginManualRunAndDependencies(t *testing.T) { } } program := "import os, sys\nprint(sys.prefix)\nprint(os.getcwd())\nprint(sys.flags.dev_mode, os.environ['PROFILE_TEST'], repr(sys.argv[1:]))\n" - write(filepath.Join(root, "requirements.txt"), "root-demo==1.0\n") + // A Conda environment file is this workspace's only build marker. + write(filepath.Join(root, "environment.yml"), "name: manual-run\ndependencies:\n - python\n") write(filepath.Join(root, "manual script.py"), program) write(filepath.Join(work, "manual_module.py"), program) purelib := strings.TrimSpace(string(site)) @@ -169,18 +170,22 @@ func TestPythonSupportPluginManualRunAndDependencies(t *testing.T) { }) } - var instance *buildInstance + var instanceIndex int awaitStateWithin(t, h, 10*time.Second, "the Python model with a project", func() bool { for index := range p.build.instances { candidate := &p.build.instances[index] if candidate.BuildSystemID == "python" && candidate.modelLoaded && len(candidate.Model.Projects) == 1 { - instance = candidate + instanceIndex = index return true } } return false }) - h.app.post(func(a *App) { a.reduceChrome(core.SetChromeOpen(itemBuild, true)) }) + instance := &p.build.instances[instanceIndex] + h.app.post(func(a *App) { + a.selectBuildInstance(p, instanceIndex) + a.reduceChrome(core.SetChromeOpen(itemBuild, true)) + }) var section buildRow awaitStateWithin(t, h, 10*time.Second, "the Dependencies section in the Build panel", func() bool { rows, _ := h.app.buildTreeRows(p) diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 59ff102..aa86acf 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -483,7 +483,9 @@ "displayName": "Python", "icon": { "path": "icons/python.svg" }, "detection": { - "markers": ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt"] + "markers": [ + "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "environment.yml", "environment.yaml" + ] }, "invocation": { "executables": [ @@ -737,7 +739,9 @@ ] }, "sync": { - "watch": ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt"] + "watch": [ + "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "environment.yml", "environment.yaml" + ] }, "layout": { "excluded": [".venv", "venv", ".conda"], From a18cfab0ee8a061b30ffef7c4e6a4ba1c7335153 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 14:58:24 +0800 Subject: [PATCH 3/3] fix(python): isolate dependency inspection from user site --- README.md | 2 +- docs/feature-matrix.md | 2 +- .../plugin.json | 2 +- .../scripts/dependencies.py | 6 +-- scripts/test.mjs | 39 +++++++++++++++---- 5 files changed, 38 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 40e0902..5da3d92 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the - `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。 - 仅用 `environment.yml` 或 `environment.yaml` 管理 Conda 环境的项目也会识别为 Python 构建实例。 - 在「运行/调试配置 → + → Python」手动配置脚本路径或模块名。可设置解释器选项、脚本参数、工作目录和环境变量。运行时沿用项目的 Python 工具链及解释器覆盖设置,支持选用 Conda、uv 和普通虚拟环境。 - - 构建面板的「依赖」显示所选解释器中已安装的 Python 包版本与依赖关系。展开或重新加载时读取发行包元数据,支持无 pip 的环境。包共享的子树只展开一次,循环依赖以叶节点结束。 + - 构建面板的「依赖」显示所选解释器中已安装的 Python 包版本与依赖关系。展开或重新加载时用 `python -I -B` 读取发行包元数据,跳过用户级 site-packages 及其启动钩子,支持无 pip 的环境。包共享的子树只展开一次,循环依赖以叶节点结束。 - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 - `uv`(`uv.lock`):`uv sync`、`uv lock`。 - `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 6ea737b..9f9742d 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -19,7 +19,7 @@ | 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用项目 Python 或经宿主解析的显式解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | | 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用项目选定的解释器或插件解释器覆盖设置。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | -| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时读取所选 Python 环境中已安装的包、版本和依赖关系,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | +| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时用 `python -I -B` 读取所选 Python 环境中已安装的包、版本和依赖关系,跳过用户级 site-packages 及其启动钩子,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index aa86acf..a0bf80b 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -594,7 +594,7 @@ "dependencies": { "source": "command", "scopes": ["project"], - "arguments": ["-E", "-B", "${pluginDir}/scripts/dependencies.py", "${outputFile}"], + "arguments": ["-I", "-B", "${pluginDir}/scripts/dependencies.py", "${outputFile}"], "output": "outputFile", "decoder": "litheDependencies", "executesProjectCode": true, diff --git a/io.github.lithe-idea.python-support/scripts/dependencies.py b/io.github.lithe-idea.python-support/scripts/dependencies.py index 230d05a..91f48de 100644 --- a/io.github.lithe-idea.python-support/scripts/dependencies.py +++ b/io.github.lithe-idea.python-support/scripts/dependencies.py @@ -7,9 +7,9 @@ from importlib import metadata from pathlib import Path -# Run with -E -B to ignore inherited PYTHONPATH and still inspect the selected -# interpreter's normal site directories. Resolve PEP 508 with the bundled parser, -# even in a pip-free environment. Remove its path before discovering packages. +# The manifest uses -I -B to skip user-site startup hooks and bytecode writes. +# Use the bundled PEP 508 parser even in pip-free environments, and remove its +# path before discovering distributions so bundled packages stay out of the tree. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "vendor")) try: from packaging.requirements import InvalidRequirement, Requirement diff --git a/scripts/test.mjs b/scripts/test.mjs index 2580d00..3cf87ea 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -26,7 +26,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, dirname, join, normalize, resolve } from "node:path"; +import { basename, dirname, join, normalize, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { readZipEntries } from "./lib/archive.mjs"; import { backendPath } from "./lib/backend.mjs"; @@ -308,6 +308,34 @@ try { } const pluginManifest = JSON.parse(readFileSync(join(unpackedPluginDir, "plugin.json"), "utf8")); + const dependencyCommand = pluginManifest.buildSystems.find(({ id }) => id === "python").dependencies; + const dependencyArguments = (outputFile) => dependencyCommand.arguments.map((arg) => + arg.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", outputFile)); + + await check("dependency command skips user-site startup hooks", () => { + const environment = join(scratch, "dependency environment with shared site"); + run(pythonCmd, ["-I", "-B", "-m", "venv", "--without-pip", "--system-site-packages", environment]); + const python = process.platform === "win32" + ? join(environment, "Scripts", "python.exe") + : join(environment, "bin", "python"); + const userBase = join(scratch, "dependency user base"); + const env = { ...process.env, PYTHONUSERBASE: userBase }; + const userSite = run(python, ["-E", "-B", "-c", "import site; assert site.ENABLE_USER_SITE; print(site.getusersitepackages())"], { + cwd: scratch, env, + }).trim(); + assert.ok(userSite.startsWith(userBase + sep), "expected a user site under the test's PYTHONUSERBASE"); + mkdirSync(userSite, { recursive: true }); + writeFileSync(join(userSite, "usercustomize.py"), [ + "from pathlib import Path", + 'Path(__file__).with_name("user-site-hook-ran").touch()', + "", + ].join("\n")); + + const treeFile = join(scratch, "isolated-dependencies.json"); + run(python, dependencyArguments(treeFile), { cwd: scratch, env }); + assert.equal(existsSync(join(userSite, "user-site-hook-ran")), false, "usercustomize.py was executed"); + assert.equal(JSON.parse(readFileSync(treeFile, "utf8")).format, "litheDependencies"); + }); await check("dependency command reads installed packages from a pip-free Python environment", () => { const environment = join(scratch, "dependency environment"); @@ -335,12 +363,9 @@ try { metadata("CycleB", "5.0", ["CycleA"]); const treeFile = join(scratch, "dependencies.json"); - const declaration = pluginManifest.buildSystems.find(({ id }) => id === "python").dependencies; - assert.equal(declaration.output, "outputFile"); - assert.equal(declaration.decoder, "litheDependencies"); - const args = declaration.arguments.map((arg) => - arg.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", treeFile)); - run(python, args, { cwd: scratch }); + assert.equal(dependencyCommand.output, "outputFile"); + assert.equal(dependencyCommand.decoder, "litheDependencies"); + run(python, dependencyArguments(treeFile), { cwd: scratch }); const leaf = (name, version, children = []) => ({ name, version, children }); assert.deepEqual(JSON.parse(readFileSync(treeFile, "utf8")), { format: "litheDependencies", version: 0, dependencies: [