From 5a73f7f12bf1a2dc3ed1b281bb6cdb8d1a49b59a Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:35:51 +0800 Subject: [PATCH 1/6] feat(python): package interpreter discovery and Pyrefly bootstrap --- .cargo/config.toml | 13 + .github/workflows/ci.yml | 23 +- .github/workflows/package.yml | 70 ++ .gitignore | 2 + README.md | 45 +- backend/Cargo.lock | 329 ++++++++ backend/Cargo.toml | 19 + backend/src/discovery.rs | 290 +++++++ backend/src/discovery/metadata.rs | 207 +++++ backend/src/discovery/project.rs | 259 +++++++ backend/src/inspect.rs | 47 ++ backend/src/main.rs | 25 + backend/src/pyrefly.rs | 128 +++ backend/src/requirements.rs | 130 ++++ docs/feature-matrix.md | 16 +- .../python_support_plugin_e2e_test.go | 211 +++-- e2e/host/lithe-host.json | 6 +- .../plugin.json | 31 +- .../scripts/backend.py | 177 ----- .../scripts/lithe_rpc.py | 170 +--- .../scripts/toolchain_provider.py | 727 ------------------ scripts/lib/backend.mjs | 74 ++ scripts/package.mjs | 10 + scripts/package/archives.test.mjs | 32 +- scripts/test.mjs | 161 ++-- 25 files changed, 1910 insertions(+), 1292 deletions(-) create mode 100644 .cargo/config.toml create mode 100644 .github/workflows/package.yml create mode 100644 backend/Cargo.lock create mode 100644 backend/Cargo.toml create mode 100644 backend/src/discovery.rs create mode 100644 backend/src/discovery/metadata.rs create mode 100644 backend/src/discovery/project.rs create mode 100644 backend/src/inspect.rs create mode 100644 backend/src/main.rs create mode 100644 backend/src/pyrefly.rs create mode 100644 backend/src/requirements.rs delete mode 100644 io.github.lithe-idea.python-support/scripts/backend.py delete mode 100644 io.github.lithe-idea.python-support/scripts/toolchain_provider.py create mode 100644 scripts/lib/backend.mjs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..59f0f82 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,13 @@ +# The package-local backend must start without a separately installed CRT. +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +[target.aarch64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +# The bundled musl targets use Rust's linker, including for local cross-builds. +[target.x86_64-unknown-linux-musl] +linker = "rust-lld" + +[target.aarch64-unknown-linux-musl] +linker = "rust-lld" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d951b5..ae36c7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,10 @@ permissions: jobs: package: + uses: ./.github/workflows/package.yml + + verify-store: + needs: package runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -17,9 +21,14 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Build all 6 platform archives - run: node scripts/package.mjs - - name: Verify release archives + - uses: actions/download-artifact@v4 + with: + pattern: python-support-archive-* + merge-multiple: true + path: dist + - name: Verify six release archives + env: + LITHE_EXPECT_ALL_ARCHIVES: "1" run: node --test --test-timeout=60000 scripts/package/*.test.mjs - name: Validate against Lithe Store rules run: | @@ -37,12 +46,6 @@ jobs: } process.exit(failed ? 1 : 0); " - - name: Upload built platform archives - uses: actions/upload-artifact@v4 - with: - name: python-support-archives - path: dist/python-support-*.zip - if-no-files-found: error commands: needs: package @@ -72,7 +75,7 @@ jobs: run: python -m pip install --disable-pip-version-check pytest - uses: actions/download-artifact@v4 with: - name: python-support-archives + name: python-support-archive-${{ matrix.platform }} path: dist - name: Unpack Windows archive under a path with spaces if: runner.os == 'Windows' diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml new file mode 100644 index 0000000..4cfb10e --- /dev/null +++ b/.github/workflows/package.yml @@ -0,0 +1,70 @@ +name: Package Python Support + +on: + workflow_call: + inputs: + tag: + type: string + required: false + +permissions: + contents: read + +jobs: + package: + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - os: macos-latest + platform: darwin-arm64 + target: aarch64-apple-darwin + - os: macos-15-intel + platform: darwin-x64 + target: x86_64-apple-darwin + - os: ubuntu-latest + platform: linux-x64 + target: x86_64-unknown-linux-musl + - os: ubuntu-24.04-arm + platform: linux-arm64 + target: aarch64-unknown-linux-musl + - os: windows-latest + platform: windows-x64 + target: x86_64-pc-windows-msvc + - os: windows-11-arm + platform: windows-arm64 + target: aarch64-pc-windows-msvc + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Configure Rust + shell: bash + env: + TARGET: ${{ matrix.target }} + run: | + rustup toolchain install 1.87 --profile minimal --target "$TARGET" + rustup override set 1.87 + - name: Test backend + run: cargo test --locked --manifest-path backend/Cargo.toml + - name: Assemble plugin archive + shell: bash + env: + PLATFORM: ${{ matrix.platform }} + TAG: ${{ inputs.tag }} + run: | + args=(--platform "$PLATFORM") + if [[ -n "$TAG" ]]; then + args+=(--expect-tag "$TAG") + fi + node scripts/package.mjs "${args[@]}" + - name: Verify archive + run: node --test --test-timeout=60000 scripts/package/archives.test.mjs + - uses: actions/upload-artifact@v4 + with: + name: python-support-archive-${{ matrix.platform }} + path: dist/python-support-*-${{ matrix.platform }}.zip + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 1245915..3c2c02d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ dist/ **/__pycache__/ *.py[cod] + +/backend/target/ diff --git a/README.md b/README.md index 07deecd..ab15821 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Python Support for Lithe (`io.github.lithe-idea.python-support`) -Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, and a zero-compilation pure-Python (`python -I -B`) plugin backend and build provider. +Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, a packaged Rust backend for interpreter discovery and language-server startup, and a Python build provider for model, run, and pytest integration. 遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。 @@ -11,13 +11,14 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA 1. **语言与编辑器基础(`languages: python`)** - 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。 2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)** - - 启动语言服务器前,宿主需要能够发现 Python 3.9 或更高版本以执行启动解析后端。宿主会传入可用于自动启动的解释器路径,项目内环境交由 Pyrefly 按自身规则发现。 - - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),6 个平台发布包共享同一套纯 Python(`python -I -B`)插件后端 `scripts/backend.py`。 + - 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。 + - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。 - `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。 - 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。 -3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchain_provider.py`)** +3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchainProviders: 0`)** - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。 - - `scripts/toolchain_provider.py` 完整实现 `litheToolchains`(`toolchains/query`)协议(支持 `~/.conda/environments.txt`、`CONDA_ENVS_PATH`、`UV_PYTHON_INSTALL_DIR`、`PYENV_ROOT`、Poetry 与 Pipenv 外部虚拟环境、`.python-version` 与 `pyproject.toml` `requires-python`)。当前桌面宿主通过清单中的 `toolDefinitions` 发现已安装解释器。提供者协议可独立验证,在桌面端启用还需要宿主支持 `toolchainProviders`、清单声明以及满足 Core 自举契约的打包运行时。 + - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。宿主观察这些输入并在变化后重新查询。 + - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。 4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)** - `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载: - `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置; @@ -37,27 +38,27 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA ## 日志接线说明(Structured Logging v2 Wiring) -本插件 `0.2.0` 包含纯 Python 插件后端(`scripts/backend.py`)、构建提供者(`scripts/build_provider.py`)与声明式贡献,全部诊断严格遵循 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。 +插件包含包内 Rust SDK 后端、构建提供者(`scripts/build_provider.py`)与声明式贡献,诊断通过 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。 ### 1. 后端与构建 Provider 协议接线(统一通道:`plugins/io.github.lithe-idea.python-support/host`) -`scripts/lithe_rpc.py` 实现 stdio JSON-RPC 2.0 协议帧传输,与宿主代记的声明式贡献共用同一个结构化日志通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`): -- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;握手成功后将 Python 层 `sys.stdout` 重定向到 `sys.stderr`,确保 `stdout` 仅输出合法 `Content-Length` JSON-RPC 帧。 +Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 发送结构化诊断,与宿主代记的声明式贡献共用通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`): +- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;两种后端的 `stdout` 均只输出 `Content-Length` JSON-RPC 帧。 - **请求级 `operationId` 关联与时序**:所有 `lithe/log` 通知严格在对应 JSON-RPC 响应帧发出**之前**写入 `stdout`,携带宿主请求传入的 `operationID`(回退为受控请求 ID),确保 Core 将诊断精确关联到活跃操作。 -- **取消不记失败**:收到 `$/cancelRequest` 时立即终止关联子进程组(POSIX `os.killpg` / Windows `taskkill /T /F`),返回 `-32800` 且**不发送** `operationFinished` 或 `operationFailed`。 +- **取消不记失败**:收到 `$/cancelRequest` 时停止扫描或终止构建子进程组(POSIX 进程组 / Windows Job Object),返回 `-32800` 且不发送 `operationFinished` 或 `operationFailed`。 | `operation` | 所属进程 | 成功事件与级别 | 降级 / 恢复事件(`WARN`) | 失败事件与级别(`ERROR`) | 受控 `code` 类别标识 | | --- | --- | --- | --- | --- | --- | -| `initialize` | `backend.py` / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | `plugins.operation.fallback_selected`(`code: "functions_unavailable"`,当宿主未协商 `litheFunctions` 时) | 握手失败由 Core / 宿主记录 | `functions_unavailable` | -| `pyrefly.resolveLaunch` | `backend.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` | -| `python.inspectEnvironment` | `backend.py` | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`internal_error` | +| `initialize` | Rust 后端 / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | — | 握手失败由 Core / 宿主记录 | 宿主协议错误 | +| `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` | +| `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` | | `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` | | `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出条数、大小或无法表示为有效选择器而省略的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` | | `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` | | `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` | | `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` | -> 注:`toolchains/query` 的错误码与超时由工具链契约(`plugin.toolchain.*`)结构化返回并由宿主工具链层统一观测;因 Core `plugin_logging` 操作白名单未纳入 `toolchains/query`,后端不为其额外发送 `lithe/log` 以避免产生 `plugins.diagnostics.rejected`。 +`toolchains/query` 是高频只读操作,成功由 SDK 返回事实。取消、读取失败、扫描超限与不安全输入通过 `plugin.toolchain.*` 结构化返回。宿主工具链层观察并处理查询及解码失败。协议 v0 的 SDK 无该操作的诊断回调。 ### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`) @@ -72,7 +73,7 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA | 组件 / 命令 | v2 结构化通道或原生文件位置 | 级别、限流、脱敏与清理策略 | | --- | --- | --- | -| `backend.py` / `build_provider.py`(纯 Python 后端与构建 Provider) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 | +| Rust 后端 / `build_provider.py` | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 | | `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 | | `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 | | `pytest`、构建任务与项目生成 | 构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `lithe/build/discoverTests` 将 `pytest` 缓存重定向至 `${workspaceStateDir}`;进程 `stdout`、用户测试代码与环境变量值仅进入协议进度流或报告文件,绝不进入 v2 结构化诊断日志。 | @@ -86,34 +87,42 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA | 路径 | 归属与用途 | 生命周期 | 跨 Git Worktree 复用策略 | | --- | --- | --- | --- | | `.cache/` | `scripts/package.mjs` 下载并经 SHA-256 校验的上游原始归档(`pyrefly` 6 平台压缩包、`debugpy` wheel、`tomli` 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/`)与状态目录严禁跨工作树复制 | | `dist/` | 最终产出的 `python-support--.zip` 发布包 | 打包输出(`.gitignore` 忽略) | 按需重新运行 `node scripts/package.mjs` 生成 | ### 常用命令 +打包需要 Node.js 与 Rust 1.87,并由 `backend/Cargo.lock` 固定依赖。SDK 固定到 Core 的 Git 提交。Linux 目标使用 musl,Windows 使用 MSVC 并静态链接 C 运行库,macOS 使用系统链接器。发布使用 CI 的六平台构建矩阵。 + 插件测试使用真实 pytest。将 pytest 安装到 `PYTHON` 对应的环境,或通过 `PYTEST_PYTHON` 指定已安装 pytest 的解释器。 ```bash # 打包当前开发平台(例如 macOS Apple Silicon) node scripts/package.mjs --platform darwin-arm64 -# 打包全部 6 个目标平台(darwin-arm64, darwin-x64, windows-x64, windows-arm64, linux-x64, linux-arm64) +# 本机具备全部六种 Rust 目标和链接器时打包全部平台 node scripts/package.mjs # 校验 dist/ 下构建产物的目录安全性、Windows 文件名/大小写兼容性与清单一致性 node --test --test-timeout=60000 scripts/package/*.test.mjs -# 运行契约不变量检查、backend/build_provider/toolchain_provider 协议单测、pyrefly LSP 解释器注入与回退、pytest 动态发现与执行、debugpy 调试及只读包哈希不变断言 +# 运行 Rust 规则测试、打包后端协议验证及真实 Pyrefly / pytest / debugpy 工作流 +cargo test --locked --manifest-path backend/Cargo.toml node scripts/test.mjs -# 针对真实 Lithe 桌面宿主与 Rust Core 运行端到端集成测试 +# 使用 e2e/host/lithe-host.json 固定的兼容桌面候选 node scripts/e2e-host.mjs + +# 也可使用另一个兼容的本地检出和提交 +node scripts/e2e-host.mjs --source /path/to/Lithe-IDEA --ref COMPATIBLE_HOST_COMMIT ``` --- ## 许可证(License) -- 插件清单、脚本、模板、图标与文档采用 [Apache-2.0](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`。 +- Rust 后端的依赖及对应许可证由 `Cargo.lock` 固定,全文随包附在 `RUST-THIRD-PARTY-NOTICES.txt`。 diff --git a/backend/Cargo.lock b/backend/Cargo.lock new file mode 100644 index 0000000..fee9c6e --- /dev/null +++ b/backend/Cargo.lock @@ -0,0 +1,329 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "lithe-plugin-sdk" +version = "0.4.0" +source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust.git?rev=e56af624d3f615982f90c6249f7aa43c9b3b218e#e56af624d3f615982f90c6249f7aa43c9b3b218e" +dependencies = [ + "base64", + "serde", + "serde_json", +] + +[[package]] +name = "lithe-python-backend" +version = "0.1.0" +dependencies = [ + "base64", + "dunce", + "lithe-plugin-sdk", + "pep440_rs", + "serde_json", + "sha2", + "toml", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pep440_rs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31095ca1f396e3de32745f42b20deef7bc09077f918b085307e8eab6ddd8fb9c" +dependencies = [ + "once_cell", + "serde", + "unicode-width", + "unscanny", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unscanny" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9df2af067a7953e9c3831320f35c1cc0600c30d44d9f7a12b01db1cd88d6b47" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/backend/Cargo.toml b/backend/Cargo.toml new file mode 100644 index 0000000..d8154f0 --- /dev/null +++ b/backend/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "lithe-python-backend" +version = "0.1.0" +edition = "2021" +rust-version = "1.87" +license = "Apache-2.0" +publish = false + +[dependencies] +base64 = "0.22" +dunce = "1" +lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust.git", rev = "e56af624d3f615982f90c6249f7aa43c9b3b218e" } +pep440_rs = "0.7" +serde_json = "1" +sha2 = "0.10" +toml = "0.9" + +[profile.release] +strip = "symbols" diff --git a/backend/src/discovery.rs b/backend/src/discovery.rs new file mode 100644 index 0000000..52e531a --- /dev/null +++ b/backend/src/discovery.rs @@ -0,0 +1,290 @@ +//! Collects bounded, read-only Python environment facts for the host resolver. + +mod metadata; +mod project; + +use self::metadata::{canonical_directory, read_text, Metadata, Source}; +use lithe_plugin_sdk::toolchains::{ + ToolchainInstallation, ToolchainQuery, ToolchainQueryError, ToolchainQueryResult, + ToolchainStatement, +}; +use lithe_plugin_sdk::Cancellation; +use pep440_rs::Version; +use std::collections::{BTreeMap, BTreeSet}; +use std::env; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +type Failure = ToolchainQueryError; +type Result = std::result::Result; + +const MAX_SCAN_ENTRIES: usize = 16384; +const MAX_INSTALLATIONS: usize = 512; +const MAX_WATCH_PATHS: usize = 256; +const MAX_PATH_BYTES: usize = 4096; +const PROVIDER_TOOL: &str = "python"; + +struct Installation { + home: String, + names: BTreeSet, + version: Version, +} + +struct Snapshot<'a> { + cancelled: &'a Cancellation, + workspace: Option, + scan_entries: usize, + installations: BTreeMap, + watch: BTreeSet, + statements: Vec, +} + +pub(crate) fn query( + request: &ToolchainQuery, + cancelled: &Cancellation, +) -> Result { + cancelled.check()?; + if request.tools.as_slice() != [PROVIDER_TOOL] { + return Err(Failure::InvalidParams); + } + let workspace = request + .workspace + .as_ref() + .map(|workspace| { + let root = + canonical_directory(Path::new(&workspace.root))?.ok_or(Failure::UnsafePath)?; + let directory = canonical_directory(&root.join(&workspace.directory))? + .filter(|directory| directory.starts_with(&root)) + .ok_or(Failure::UnsafePath)?; + Ok::<_, Failure>((root, directory)) + }) + .transpose()?; + let mut snapshot = Snapshot { + cancelled, + workspace: workspace.as_ref().map(|(root, _)| root.clone()), + scan_entries: 0, + installations: BTreeMap::new(), + watch: BTreeSet::new(), + statements: Vec::new(), + }; + + let user_home = env::home_dir().filter(|path| path.is_absolute()); + if let Some(home) = &user_home { + snapshot.conda_registry(&home.join(".conda/environments.txt"))?; + } + if let Some(paths) = env::var_os("CONDA_ENVS_PATH") { + for path in env::split_paths(&paths).filter(|path| path.is_absolute()) { + snapshot.scan(&path, Source::Conda)?; + } + } + if let Some(prefix) = absolute_env("CONDA_PREFIX") { + snapshot.observe(&prefix, Source::Conda)?; + snapshot.scan(&prefix.join("envs"), Source::Conda)?; + } + if let Some(uv) = uv_root(user_home.as_deref()) { + snapshot.scan(&uv, Source::Uv)?; + } + if let Some(pyenv) = pyenv_root(user_home.as_deref()) { + snapshot.scan(&pyenv.join("versions"), Source::Pyenv)?; + } + if let Some(poetry) = poetry_root(user_home.as_deref()) { + snapshot.scan(&poetry, Source::Poetry)?; + } + if let Some(pipenv) = pipenv_root(user_home.as_deref()) { + snapshot.scan(&pipenv, Source::Pipenv)?; + } + if let Some((root, directory)) = workspace { + project::read(&mut snapshot, &root, &directory)?; + } + cancelled.check()?; + Ok(ToolchainQueryResult { + installations: snapshot + .installations + .into_values() + .map(|installation| ToolchainInstallation { + tool: PROVIDER_TOOL.to_owned(), + version: installation.version.to_string(), + home: installation.home, + }) + .collect(), + statements: snapshot.statements, + watch: snapshot.watch.into_iter().collect(), + }) +} + +impl Snapshot<'_> { + fn watch(&mut self, path: &Path) -> Result<()> { + self.watch.insert(wire_path(path)?); + if self.watch.len() > MAX_WATCH_PATHS { + return Err(Failure::LimitExceeded); + } + Ok(()) + } + + fn step(&mut self) -> Result<()> { + self.cancelled.check()?; + self.scan_entries += 1; + if self.scan_entries > MAX_SCAN_ENTRIES { + return Err(Failure::LimitExceeded); + } + Ok(()) + } + + fn conda_registry(&mut self, path: &Path) -> Result<()> { + self.watch(path)?; + if let Some(registry) = read_text(path, None)? { + for line in registry + .lines() + .map(str::trim) + .filter(|line| !line.starts_with('#')) + { + self.step()?; + let path = Path::new(line); + if path.is_absolute() { + self.observe(path, Source::Conda)?; + } + } + } + Ok(()) + } + + fn scan(&mut self, root: &Path, source: Source) -> Result<()> { + self.watch(root)?; + let Some(root) = canonical_directory(root)? else { + return Ok(()); + }; + if self + .workspace + .as_ref() + .is_some_and(|workspace| root.starts_with(workspace)) + { + return Ok(()); + } + for entry in std::fs::read_dir(root).map_err(metadata::io_failure)? { + self.step()?; + let entry = entry.map_err(metadata::io_failure)?; + if !entry.file_name().as_encoded_bytes().starts_with(b".") { + self.observe(&entry.path(), source)?; + } + } + Ok(()) + } + + fn observe(&mut self, candidate: &Path, source: Source) -> Result<()> { + let Some(home) = canonical_directory(candidate)? else { + return Ok(()); + }; + if self + .workspace + .as_ref() + .is_some_and(|root| home.starts_with(root)) + { + return Ok(()); + } + let names: BTreeSet<_> = [candidate, &home] + .into_iter() + .filter_map(Path::file_name) + .map(OsString::from) + .collect(); + if let Some(existing) = self.installations.get_mut(&home) { + existing.names.extend(names); + return Ok(()); + } + if !metadata::has_safe_executable(&home)? { + return Ok(()); + } + let Some(Metadata { version, input }) = + metadata::version(&home, candidate, source, || self.step())? + else { + return Ok(()); + }; + // A directory watch covers manager additions/removals. The version + // source is observed separately when it can change in place. + if let Some(input) = input { + self.watch(&input)?; + } + let wire_home = wire_path(&home)?; + self.installations.insert( + home, + Installation { + home: wire_home, + names, + version, + }, + ); + if self.installations.len() > MAX_INSTALLATIONS { + return Err(Failure::LimitExceeded); + } + Ok(()) + } +} + +fn wire_path(path: &Path) -> Result { + path.to_str() + .filter(|value| { + path.is_absolute() + && value.len() <= MAX_PATH_BYTES + && !value.chars().any(char::is_control) + }) + .map(str::to_owned) + .ok_or(Failure::UnsafePath) +} + +fn absolute_env(key: &str) -> Option { + env::var_os(key) + .map(PathBuf::from) + .filter(|path| path.is_absolute()) +} + +fn uv_root(home: Option<&Path>) -> Option { + absolute_env("UV_PYTHON_INSTALL_DIR").or_else(|| { + if cfg!(windows) { + absolute_env("APPDATA").map(|path| path.join("uv/data/python")) + } else { + absolute_env("XDG_DATA_HOME") + .or_else(|| home.map(|path| path.join(".local/share"))) + .map(|path| path.join("uv/python")) + } + }) +} + +fn pyenv_root(home: Option<&Path>) -> Option { + absolute_env("PYENV_ROOT").or_else(|| { + home.map(|path| { + path.join(if cfg!(windows) { + ".pyenv/pyenv-win" + } else { + ".pyenv" + }) + }) + }) +} + +fn poetry_root(home: Option<&Path>) -> Option { + absolute_env("POETRY_VIRTUALENVS_PATH").or_else(|| { + let cache = absolute_env("POETRY_CACHE_DIR").or_else(|| { + if cfg!(target_os = "macos") { + home.map(|path| path.join("Library/Caches/pypoetry")) + } else if cfg!(windows) { + absolute_env("LOCALAPPDATA").map(|path| path.join("pypoetry/Cache")) + } else { + absolute_env("XDG_CACHE_HOME") + .or_else(|| home.map(|path| path.join(".cache"))) + .map(|path| path.join("pypoetry")) + } + }); + cache.map(|path| path.join("virtualenvs")) + }) +} + +fn pipenv_root(home: Option<&Path>) -> Option { + absolute_env("WORKON_HOME").or_else(|| { + home.map(|path| { + path.join(if cfg!(windows) { + ".virtualenvs" + } else { + ".local/share/virtualenvs" + }) + }) + }) +} diff --git a/backend/src/discovery/metadata.rs b/backend/src/discovery/metadata.rs new file mode 100644 index 0000000..14ea3e8 --- /dev/null +++ b/backend/src/discovery/metadata.rs @@ -0,0 +1,207 @@ +//! Captures version metadata without executing any candidate interpreter. + +use super::{Failure, Result}; +use crate::requirements::{managed_release, numeric_release}; +use pep440_rs::Version; +use serde_json::Value; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +const MAX_SOURCE_BYTES: u64 = 256 * 1024; + +#[derive(Clone, Copy)] +pub(super) enum Source { + Conda, + Uv, + Pyenv, + Poetry, + Pipenv, +} + +pub(super) struct Metadata { + pub(super) version: Version, + pub(super) input: Option, +} + +pub(super) fn io_failure(_: io::Error) -> Failure { + // This is a failure reading the manager's data, distinct from a trust + // denial for the query itself. Core can fall back to lower sources. + Failure::ProviderUnavailable +} + +fn optional(result: io::Result) -> Result> { + match result { + Ok(value) => Ok(Some(value)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(io_failure(error)), + } +} + +pub(super) fn canonical_directory(path: &Path) -> Result> { + let Some(path) = optional(dunce::canonicalize(path))? else { + return Ok(None); + }; + Ok(optional(fs::metadata(&path))? + .filter(|metadata| metadata.is_dir()) + .map(|_| path)) +} + +pub(super) fn canonical_file(path: &Path, within: Option<&Path>) -> Result> { + let Some(path) = optional(dunce::canonicalize(path))? else { + return Ok(None); + }; + if within.is_some_and(|root| !path.starts_with(root)) { + return Ok(None); + } + Ok(optional(fs::metadata(&path))? + .filter(|metadata| metadata.is_file()) + .map(|_| path)) +} + +pub(super) fn read_text(path: &Path, within: Option<&Path>) -> Result> { + let Some(path) = canonical_file(path, within)? else { + return Ok(None); + }; + let Some(file) = optional(File::open(path))? else { + return Ok(None); + }; + let mut data = Vec::new(); + file.take(MAX_SOURCE_BYTES + 1) + .read_to_end(&mut data) + .map_err(io_failure)?; + if data.len() as u64 > MAX_SOURCE_BYTES { + return Err(Failure::LimitExceeded); + } + String::from_utf8(data) + .map(Some) + .map_err(|_| Failure::ProviderUnavailable) +} + +pub(super) fn has_safe_executable(home: &Path) -> Result { + let layouts = if cfg!(windows) { + ["Scripts/python.exe", "python.exe"] + } else { + ["bin/python3", "bin/python"] + }; + for layout in layouts { + let path = home.join(layout); + let Some(canonical) = optional(dunce::canonicalize(&path))? else { + continue; + }; + // Core checks the first present layout and rejects an escaping target. + // Skipping that target and looking for a second layout would emit a + // candidate the host cannot validate. + if !canonical.starts_with(home) { + return Ok(false); + } + let Some(metadata) = optional(fs::metadata(canonical))? else { + continue; + }; + #[cfg(unix)] + let executable = { + use std::os::unix::fs::PermissionsExt; + metadata.permissions().mode() & 0o111 != 0 + }; + #[cfg(not(unix))] + let executable = true; + return Ok(metadata.is_file() && executable); + } + Ok(false) +} + +pub(super) fn version( + home: &Path, + candidate: &Path, + source: Source, + step: impl FnMut() -> Result<()>, +) -> Result> { + let venv_cfg = home.join("pyvenv.cfg"); + if let Some(config) = read_text(&venv_cfg, Some(home))? { + let version = config + .lines() + .filter_map(|line| line.split_once('=')) + .filter(|(key, _)| matches!(key.trim(), "version" | "version_info")) + .find_map(|(_, version)| parse_release(version.trim())); + if let Some(version) = version { + return Ok(Some(Metadata { + version, + input: Some(venv_cfg), + })); + } + } + + if matches!(source, Source::Conda) { + return conda_version(home, step); + } + if !matches!(source, Source::Uv | Source::Pyenv) { + return Ok(None); + } + let version = [home, candidate].into_iter().find_map(|path| { + path.file_name()? + .to_str() + .and_then(managed_release)? + .parse() + .ok() + }); + Ok(version.map(|version| Metadata { + version, + input: None, + })) +} + +fn conda_version(home: &Path, mut step: impl FnMut() -> Result<()>) -> Result> { + let Some(directory) = canonical_directory(&home.join("conda-meta"))? + .filter(|directory| directory.starts_with(home)) + else { + return Ok(None); + }; + let mut python = None; + for entry in fs::read_dir(directory).map_err(io_failure)? { + step()?; + let entry = entry.map_err(io_failure)?; + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + if !name + .strip_prefix("python-") + .is_some_and(|rest| rest.starts_with(|character: char| character.is_ascii_digit())) + || !name.ends_with(".json") + { + continue; + } + let path = entry.path(); + let Some(contents) = read_text(&path, Some(home))? else { + continue; + }; + let record: Value = + serde_json::from_str(&contents).map_err(|_| Failure::ProviderUnavailable)?; + if record["name"] != "python" { + continue; + } + let Some(version) = record["version"].as_str().and_then(parse_release) else { + continue; + }; + if python + .as_ref() + .is_some_and(|(previous, _)| *previous != version) + { + return Err(Failure::ProviderUnavailable); + } + if python.as_ref().is_none_or(|(_, previous)| path < *previous) { + python = Some((version, path)); + } + } + Ok(python.map(|(version, input)| Metadata { + version, + input: Some(input), + })) +} + +fn parse_release(value: &str) -> Option { + // Keep a valid prerelease as a prerelease rather than treating its numeric + // prefix as an installed final release. + value + .parse() + .ok() + .filter(|_: &Version| numeric_release(value).is_some()) +} diff --git a/backend/src/discovery/project.rs b/backend/src/discovery/project.rs new file mode 100644 index 0000000..c9aba9c --- /dev/null +++ b/backend/src/discovery/project.rs @@ -0,0 +1,259 @@ +//! Reads the nearest manager declarations without importing workspace code. + +use super::{ + metadata::canonical_file, read_text, wire_path, Failure, Result, Snapshot, PROVIDER_TOOL, +}; +use crate::requirements::{matches_version_file, Constraint}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use lithe_plugin_sdk::toolchains::{ToolchainScope, ToolchainStatement, ToolchainStatementKind}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +const MAX_ANCESTORS: usize = 64; +const MAX_REQUEST_BYTES: usize = 512; + +pub(super) fn read(snapshot: &mut Snapshot<'_>, root: &Path, directory: &Path) -> Result<()> { + for (index, ancestor) in directory.ancestors().enumerate() { + snapshot.cancelled.check()?; + if index == MAX_ANCESTORS { + return Err(Failure::LimitExceeded); + } + let version = version_file(snapshot, root, ancestor)?; + project_file(snapshot, root, ancestor, version)?; + if ancestor == root { + break; + } + } + Ok(()) +} + +fn version_file( + snapshot: &mut Snapshot<'_>, + root: &Path, + directory: &Path, +) -> Result> { + let path = directory.join(".python-version"); + snapshot.watch(&path)?; + let Some(source) = source(&path, root)? else { + return Ok(None); + }; + let Some(text) = read_text(&source, Some(root))? else { + return Ok(None); + }; + let request = text + .lines() + .filter_map(|line| line.split('#').next()) + .flat_map(str::split_ascii_whitespace) + .next(); + Ok(request.map(|request| (source, request.to_owned()))) +} + +fn project_file( + snapshot: &mut Snapshot<'_>, + root: &Path, + directory: &Path, + selected_version: Option<(PathBuf, String)>, +) -> Result<()> { + let project_path = directory.join("pyproject.toml"); + let poetry_lock = directory.join("poetry.lock"); + let pipfile = directory.join("Pipfile"); + for path in [&project_path, &poetry_lock, &pipfile] { + snapshot.watch(path)?; + } + + let mut project_name = None; + let mut project_requirement = None; + if let Some(source) = source(&project_path, root)? { + if let Some(text) = read_text(&source, Some(root))? { + let project: toml::Table = text.parse().map_err(|_| Failure::ProviderUnavailable)?; + let metadata = project.get("project"); + let poetry = project.get("tool").and_then(|tool| tool.get("poetry")); + project_name = metadata + .and_then(|table| text_value(table, "name")) + .or_else(|| poetry.and_then(|table| text_value(table, "name"))) + .map(str::to_owned); + let poetry_range = poetry + .and_then(|table| table.get("dependencies")) + .and_then(|table| text_value(table, "python")); + let range = metadata.and_then(|table| text_value(table, "requires-python")); + if let Some((request, constraint)) = range + .map(|range| (range, Constraint::project(range))) + .or_else(|| poetry_range.map(|range| (range, Constraint::poetry(range)))) + { + project_requirement = Some((source, request.to_owned(), constraint)); + } + } + } + + let allows_version = |version: &pep440_rs::Version| { + project_requirement + .as_ref() + .is_none_or(|(_, _, constraint)| { + constraint + .as_ref() + .is_some_and(|value| value.contains(version)) + }) + }; + // Core treats separate version declarations from one directory as + // alternatives. A manager pin and the project's compatibility range apply + // together, so publish one request anchored at the file selecting the version. + if let Some((source, request)) = selected_version { + let installation = choose(snapshot, |candidate| { + allows_version(&candidate.version) + && candidate + .names + .iter() + .filter_map(|name| name.to_str()) + .any(|name| matches_version_file(&request, name, &candidate.version)) + }); + statement( + snapshot, + &source, + &request, + installation, + ToolchainStatementKind::Declaration, + "compatible", + )?; + } else if let Some((source, request, _)) = &project_requirement { + let installation = choose(snapshot, |candidate| allows_version(&candidate.version)); + statement( + snapshot, + source, + request, + installation, + ToolchainStatementKind::Declaration, + "native", + )?; + } + + if let Some(source) = source(&poetry_lock, root)? { + let prefix = poetry_prefix(directory, project_name.as_deref()); + if let Some(home) = choose(snapshot, |candidate| { + candidate + .names + .iter() + .filter_map(|name| name.to_str()) + .any(|name| name.starts_with(&prefix)) + && allows_version(&candidate.version) + }) { + statement( + snapshot, + &source, + &prefix, + Some(home), + ToolchainStatementKind::Environment, + "native", + )?; + } + } + if let Some(source) = source(&pipfile, root)? { + let name = pipenv_name(directory); + if let Some(home) = choose(snapshot, |candidate| { + candidate.names.contains(std::ffi::OsStr::new(&name)) + }) { + statement( + snapshot, + &source, + &name, + Some(home), + ToolchainStatementKind::Environment, + "native", + )?; + } + } + Ok(()) +} + +fn source(path: &Path, root: &Path) -> Result> { + // A linked declaration can point to arbitrary files and no longer + // identifies this project's declared watch pattern. Only read the exact + // expected filename in the canonical workspace directory. + Ok(canonical_file(path, Some(root))?.filter(|canonical| canonical == path)) +} + +fn text_value<'a>(table: &'a toml::Value, key: &str) -> Option<&'a str> { + table + .get(key)? + .as_str() + .map(str::trim) + .filter(|value| !value.is_empty()) +} + +fn choose( + snapshot: &Snapshot<'_>, + mut matches: impl FnMut(&super::Installation) -> bool, +) -> Option { + let mut best: Option<&super::Installation> = None; + let mut tied = false; + for candidate in snapshot + .installations + .values() + .filter(|candidate| matches(candidate)) + { + match best.map(|value| value.version.cmp(&candidate.version)) { + Some(std::cmp::Ordering::Greater) => {} + Some(std::cmp::Ordering::Equal) => tied = true, + _ => { + best = Some(candidate); + tied = false; + } + } + } + best.filter(|_| !tied) + .map(|candidate| candidate.home.clone()) +} + +fn statement( + snapshot: &mut Snapshot<'_>, + source: &Path, + request: &str, + installation: Option, + kind: ToolchainStatementKind, + reader: &str, +) -> Result<()> { + if request.len() > MAX_REQUEST_BYTES || request.chars().any(char::is_control) { + return Err(Failure::LimitExceeded); + } + snapshot.statements.push(ToolchainStatement { + tool: PROVIDER_TOOL.to_owned(), + scope: ToolchainScope::Project, + source: wire_path(source)?, + request: request.to_owned(), + installation, + kind, + reader: reader.to_owned(), + }); + Ok(()) +} + +fn pipenv_name(directory: &Path) -> String { + let name = directory.file_name().unwrap_or_default().to_string_lossy(); + let name: String = sanitize(&name).chars().take(42).collect(); + let hash = Sha256::digest(directory.to_string_lossy().as_bytes()); + format!("{name}-{}", URL_SAFE_NO_PAD.encode(&hash[..6])) +} + +fn poetry_prefix(directory: &Path, name: Option<&str>) -> String { + let name = name.unwrap_or_else(|| { + directory + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or_default() + }); + let name: String = sanitize(&name.to_lowercase()).chars().take(42).collect(); + let path = directory.to_string_lossy(); + let normalized = if cfg!(windows) { + path.to_lowercase() + } else { + path.into_owned() + }; + let hash = Sha256::digest(normalized.as_bytes()); + format!("{name}-{}-py", URL_SAFE_NO_PAD.encode(&hash[..6])) +} + +fn sanitize(name: &str) -> String { + name.replace( + [' ', '$', '`', '!', '*', '@', '"', '\\', '\r', '\n', '\t'], + "_", + ) +} diff --git a/backend/src/inspect.rs b/backend/src/inspect.rs new file mode 100644 index 0000000..961d407 --- /dev/null +++ b/backend/src/inspect.rs @@ -0,0 +1,47 @@ +//! Reports environment metadata associated with an explicit interpreter path. + +use lithe_plugin_sdk::{Context, FunctionError, PluginError}; +use serde_json::{json, Value}; +use std::path::Path; + +pub(crate) const FUNCTION: &str = "python.inspectEnvironment"; + +pub(crate) fn environment(params: Value, context: &Context) -> Result { + context.check_cancelled()?; + let path = params["executable"] + .as_str() + .filter(|value| value.len() <= 4096 && !value.chars().any(char::is_control)) + .map(Path::new) + .filter(|path| path.is_absolute()) + .ok_or_else(|| { + PluginError::new( + "python.invalidExecutable", + "Executable must be an absolute path.", + ) + })?; + let directory = path.parent().unwrap_or(path); + let home = directory + .file_name() + .and_then(|name| name.to_str()) + .filter(|name| name.eq_ignore_ascii_case("bin") || name.eq_ignore_ascii_case("scripts")) + .and_then(|_| directory.parent()) + .unwrap_or(directory); + let venv = metadata_matches(&home.join("pyvenv.cfg"), |metadata| metadata.is_file())?; + let conda = metadata_matches(&home.join("conda-meta"), |metadata| metadata.is_dir())?; + context.check_cancelled()?; + Ok(json!({ "executable": path, "isVirtualEnv": venv || conda })) +} + +fn metadata_matches( + path: &Path, + predicate: impl FnOnce(std::fs::Metadata) -> bool, +) -> Result { + match std::fs::metadata(path) { + Ok(metadata) => Ok(predicate(metadata)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(_) => Err(PluginError::new( + "python.environmentUnavailable", + "Interpreter environment is unavailable.", + )), + } +} diff --git a/backend/src/main.rs b/backend/src/main.rs new file mode 100644 index 0000000..ed26c84 --- /dev/null +++ b/backend/src/main.rs @@ -0,0 +1,25 @@ +//! Package-local startup for the Python plugin's language server and toolchain provider. + +mod discovery; +mod inspect; +mod pyrefly; +mod requirements; + +use lithe_plugin_sdk::Backend; + +fn main() { + let mut backend = Backend::new("python-support-backend"); + let launch = pyrefly::LaunchResolver::default(); + backend + .function("pyrefly.resolveLaunch", move |params, context| { + launch.resolve(params, context) + }) + .expect("the Pyrefly function ID is valid") + .function(inspect::FUNCTION, inspect::environment) + .expect("the inspect function ID is valid") + .suppress_success_diagnostics(inspect::FUNCTION) + .expect("the inspect function is registered") + .toolchain_provider("python", discovery::query) + .expect("the Python provider ID is valid"); + std::process::exit(backend.listen()); +} diff --git a/backend/src/pyrefly.rs b/backend/src/pyrefly.rs new file mode 100644 index 0000000..b2ea86c --- /dev/null +++ b/backend/src/pyrefly.rs @@ -0,0 +1,128 @@ +//! Produces the packaged Pyrefly launch and its settings using the host's interpreter hint. + +use lithe_plugin_sdk::{Context, FunctionError, PluginError}; +use serde_json::{json, Value}; +use std::collections::VecDeque; +use std::sync::Mutex; + +const OPERATION: &str = "pyrefly.resolveLaunch"; +const MAX_TRACKED_WORKSPACES: usize = 128; + +#[derive(Default)] +pub(crate) struct LaunchResolver { + degraded: Mutex>, +} + +impl LaunchResolver { + pub(crate) fn resolve(&self, params: Value, context: &Context) -> Result { + context.check_cancelled()?; + if params["serverID"] != "python" { + return Err(PluginError::new( + "python.unknownServer", + "Unsupported language server identifier.", + ) + .into()); + } + let path = match params["platform"]["os"].as_str() { + Some("windows" | "win32") => "bin/pyrefly.exe", + None if cfg!(windows) => "bin/pyrefly.exe", + _ => "bin/pyrefly", + }; + let settings = ¶ms["settings"]; + let diagnostic_mode = + enum_setting(settings, "diagnosticMode", &["openFilesOnly", "workspace"]); + let mut python = json!({ + "pyrefly": { + "typeCheckingMode": enum_setting(settings, "typeCheckingMode", &["default", "auto", "basic", "strict", "all", "off"]), + "displayTypeErrors": enum_setting(settings, "displayTypeErrors", &["force-on", "default", "error-missing-imports", "force-off"]), + "diagnosticMode": diagnostic_mode, + }, + "analysis": { + "diagnosticMode": diagnostic_mode, + "autoImportCompletions": settings["autoImportCompletions"].as_bool().unwrap_or(true), + "completeFunctionParens": settings["completeFunctionParens"].as_bool().unwrap_or(false), + "importFormat": enum_setting(settings, "importFormat", &["absolute", "relative"]), + }, + }); + let hint = interpreter_hint(¶ms["tools"]); + if let Ok(Some(executable)) = hint { + python["pythonPath"] = json!(executable); + } + let key = context + .workspace_context() + .map(|workspace| workspace.context_id()) + .or_else(|| { + params["workspaceStateDirectory"] + .as_str() + .filter(|path| path.len() <= 4096) + }) + .unwrap_or_default(); + if hint.is_err() { + self.remember_degradation(key); + context + .diagnostics() + .degraded(OPERATION, "invalid_tool_hint", Some(1))?; + } else if self.take_degradation(key) { + context + .diagnostics() + .recovered(OPERATION, "tool_hint_restored", Some(1))?; + } + + Ok(json!({ + "executable": {"kind": "packaged", "path": path}, + "arguments": ["lsp"], + "workspaceConfiguration": {"python": python}, + })) + } + + fn remember_degradation(&self, key: &str) { + let mut degraded = self + .degraded + .lock() + .unwrap_or_else(|error| error.into_inner()); + degraded.retain(|old| old != key); + if degraded.len() == MAX_TRACKED_WORKSPACES { + degraded.pop_front(); + } + degraded.push_back(key.to_owned()); + } + + fn take_degradation(&self, key: &str) -> bool { + let mut degraded = self + .degraded + .lock() + .unwrap_or_else(|error| error.into_inner()); + let previous = degraded.len(); + degraded.retain(|old| old != key); + degraded.len() != previous + } +} + +fn enum_setting<'a>(settings: &'a Value, key: &str, allowed: &[&'a str]) -> &'a str { + settings[key] + .as_str() + .filter(|value| allowed.contains(value)) + .unwrap_or(allowed[0]) +} + +fn interpreter_hint(tools: &Value) -> Result, ()> { + let executable = match tools { + Value::Null => return Ok(None), + Value::Object(tools) => match tools.get("python") { + Some(Value::Object(tool)) => tool.get("executable"), + None | Some(Value::Null) => return Ok(None), + _ => return Err(()), + }, + _ => return Err(()), + }; + match executable { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) if path.is_empty() => Ok(None), + Some(Value::String(path)) + if path.len() <= 4096 && path.trim() == path && !path.chars().any(char::is_control) => + { + Ok(Some(path)) + } + _ => Err(()), + } +} diff --git a/backend/src/requirements.rs b/backend/src/requirements.rs new file mode 100644 index 0000000..c170143 --- /dev/null +++ b/backend/src/requirements.rs @@ -0,0 +1,130 @@ +//! Python version declarations and constraints interpreted by their originating manager. + +use pep440_rs::{Version, VersionSpecifiers}; +use std::str::FromStr; + +pub(crate) fn numeric_release(value: &str) -> Option<&str> { + let limit = value + .find(|character: char| !character.is_ascii_digit() && character != '.') + .unwrap_or(value.len()); + let release = &value[..limit]; + let parts: Vec<_> = release.split('.').collect(); + (parts.len() >= 2 && parts.len() <= 4 && parts.iter().all(|part| part.parse::().is_ok())) + .then_some(release) +} + +pub(crate) fn managed_release(name: &str) -> Option<&str> { + let release = name + .strip_prefix("cpython-") + .or_else(|| name.strip_prefix("pypy-")) + .unwrap_or(name); + let numeric = numeric_release(release)?; + // Release names must not turn a prerelease or a non-version environment + // name into a different, installed final release. + (release == numeric + || (release.len() != name.len() && release[numeric.len()..].starts_with('-'))) + .then_some(numeric) +} + +pub(crate) struct Constraint(Vec); + +impl Constraint { + pub(crate) fn project(requirement: &str) -> Option { + Some(Self(vec![requirement.parse().ok()?])) + } + + pub(crate) fn poetry(requirement: &str) -> Option { + let mut ranges = Vec::new(); + for alternative in requirement.split("||") { + let terms = alternative + .split(',') + .map(str::trim) + .filter(|term| !term.is_empty() && *term != "*") + .map(poetry_term) + .collect::>>()?; + ranges.push(terms.join(",").parse().ok()?); + } + Some(Self(ranges)) + } + + pub(crate) fn contains(&self, version: &Version) -> bool { + self.0.iter().any(|range| range.contains(version)) + } +} + +fn poetry_term(term: &str) -> Option { + let Some(version) = term.strip_prefix('^').or_else(|| { + term.strip_prefix('~') + .filter(|version| !version.starts_with('=')) + }) else { + return Some( + if term.starts_with(|character: char| character.is_ascii_digit()) { + format!("=={term}") + } else { + term.to_owned() + }, + ); + }; + let version = Version::from_str(version.trim()).ok()?; + let release = version.release(); + let pivot = if term.starts_with('^') { + release + .iter() + .position(|part| *part != 0) + .unwrap_or(release.len() - 1) + } else { + usize::from(release.len() >= 2) + }; + let mut upper = release[..=pivot].to_vec(); + upper[pivot] = upper[pivot].checked_add(1)?; + let upper = upper + .iter() + .map(u64::to_string) + .collect::>() + .join("."); + Some(format!(">={version},<{upper}")) +} + +pub(crate) fn matches_version_file(wanted: &str, name: &str, version: &Version) -> bool { + if wanted == name { + return true; + } + let wanted = wanted.strip_prefix("cpython-").unwrap_or(wanted); + let Some(wanted) = Version::from_str(wanted).ok().filter(|value| { + !value.any_prerelease() + && wanted + .bytes() + .all(|byte| byte.is_ascii_digit() || byte == b'.') + }) else { + return false; + }; + version.release().starts_with(wanted.release()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_pep440_compatible_and_excluded_versions() { + let range = Constraint::project("~=3.12.1, !=3.12.4").unwrap(); + for (version, matches) in [("3.12.2", true), ("3.12.4", false), ("3.13", false)] { + assert_eq!(range.contains(&version.parse().unwrap()), matches); + } + assert!(Constraint::project("^3.12").is_none()); + } + + #[test] + fn poetry_disjunction_and_tilde_follow_release_precision() { + let range = Constraint::poetry("~3.11 || ^4.0, !=4.1").unwrap(); + for (version, matches) in [ + ("3.11.8", true), + ("3.12", false), + ("4.0", true), + ("4.1", false), + ("5.0", false), + ] { + assert_eq!(range.contains(&version.parse().unwrap()), matches); + } + } +} diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 4d0f8f7..663561b 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -1,11 +1,11 @@ # Python Support 功能矩阵(Feature Matrix) -本文档维护 `io.github.lithe-idea.python-support`(`v0.2.0`)插件在 6 个目标发布平台上的实现与真实执行验证状态(插件功能矩阵与测试证据仅在本插件仓库维护,不进入宿主仓库)。 +本文档维护 `io.github.lithe-idea.python-support`插件在 6 个目标发布平台上的实现与真实执行验证状态(插件功能矩阵与测试证据仅在本插件仓库维护,不进入宿主仓库)。 ## 状态定义 - `✅ 已验证`:已在目标平台实机完成打包安装、真实上游二进制/运行时进程执行及宿主端到端测试验证。 -- `⏳ 待实机验证(pending)`:已在 `plugin.json`、脚本与对应平台归档(`dist/python-support-0.2.0-.zip`)中完成实现,并通过归档路径/大小写安全检查、Lithe Store 规则校验以及 Unix/Windows 双清单真实 Core `ValidatePluginManifest` 契约校验;但尚未在对应 OS/架构实机或 CI runner 上执行原生子进程工作流,严禁在未实跑前标为已验证。 +- `⏳ 待实机验证(pending)`:已在 `plugin.json`、脚本与对应平台归档(`dist/python-support--.zip`)中完成实现,并通过归档路径/大小写安全检查、Lithe Store 规则校验以及 Unix/Windows 双清单真实 Core `ValidatePluginManifest` 契约校验;但尚未在对应 OS/架构实机或 CI runner 上执行原生子进程工作流,严禁在未实跑前标为已验证。 - `🚧 待宿主开放(blocked on host capability)`:插件端协议与代码已完整实现并通过真实 Core 解码验证,待桌面宿主开放对应能力版本后启用清单声明。 ## 跨平台能力与验证矩阵 @@ -13,7 +13,7 @@ | 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) | | --- | --- | --- | --- | --- | --- | --- | --- | | 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ 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` | -| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 纯 Python(`python -I -B`)stdio JSON-RPC 后端 `scripts/backend.py`(协商 `litheLogging` 0 与 `litheFunctions` 0);`pyrefly.resolveLaunch` 按 `platform.os` 返回包内 `bin/pyrefly`(Unix)或 `bin/pyrefly.exe`(Windows)与 `["lsp"]`,在宿主传入 `tools.python.executable` 时自动注入 `workspaceConfiguration.python.pythonPath`(支持项目外 conda / uv / pyenv 解释器),缺失或未信任项目环境时优雅省略 `pythonPath` 回退 `pyrefly 1.4.1` 原生 `.venv` 发现 | ✅ 已验证 | ⏳ pending(`macos-x86_64` 二进制与纯 Python 后端已打包校验) | ⏳ pending(`bin/pyrefly.exe` 平台分支已通过 Core `DecodePluginLanguageServerLaunch` 校验) | ⏳ pending(`musl` 二进制与纯 Python 后端已打包校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/lithe_rpc.py`
`io.github.lithe-idea.python-support/scripts/backend.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 工具链与环境自动发现 (`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` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `lithe/build/discoverTests` 通过有界可取消 `pytest --collect-only` 收集函数、测试类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,按条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0);`lithe/build/test` 支持精确 node ID 与 JUnit 类名重跑,单个用例须带套件、`lithe/build/progress` 流式输出及 `.pytest_cache/lithe-junit.xml` 解码;保留 `pip install -r requirements.txt` 与 `mypy` 任务 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `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` | @@ -22,10 +22,10 @@ | 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ 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` | | 新建项目向导 (`projectGenerators`) | `python-project`:选择并固定项目级 `python` 工具链(`pinAs: "project"`),可选 `none` / `venv (.venv)` / `uv (.venv)` 与示例代码生成(Windows 自动将 `python3` 命令切换为 `python`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(Windows 清单 `python` 命令切换已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/templates/python/`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/projectgen/python_integration_test.go` | | 国际化 (`l10n`) | 英文默认文案 + `l10n/zh-Hans.json` 简体中文完整设置与分组翻译 | ✅ 已验证 | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/l10n/zh-Hans.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 工具链 Provider 协议 (`litheToolchains` / `toolchains/query`) | `scripts/toolchain_provider.py` 与 `backend.py` 已完整实现 `toolchains/query`(解析 `~/.conda/environments.txt`、`CONDA_ENVS_PATH`、`UV_PYTHON_INSTALL_DIR`、`PYENV_ROOT`、Poetry/Pipenv 外部虚拟环境、`.python-version` 与 `pyproject.toml` `requires-python`,严格排除工作区内目录并通过真实 Core `toolchains.decodeReply` 校验);清单层待桌面宿主开放 `toolchainProviders` 后启用(见下方前置说明) | 🚧 待宿主开放 `toolchainProviders`(后端协议与 Core 解码已在 `darwin-arm64` 实测通过) | 🚧 待宿主开放 `toolchainProviders` | 🚧 待宿主开放 `toolchainProviders` | 🚧 待宿主开放 `toolchainProviders` | `2026-11-18`(协议与 Core 解码验证) | `io.github.lithe-idea.python-support/scripts/toolchain_provider.py`
`io.github.lithe-idea.python-support/scripts/backend.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 工具链提供者 (`litheToolchains` / `toolchains/query`) | 包内 Rust 后端在全局与项目上下文读取 Conda 登记、uv、pyenv、Poetry/Pipenv 环境以及项目版本声明。安装、要求与观察路径作为事实交回宿主验证。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/discovery.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -## `toolchainProviders` 宿主前置条件说明 +## 宿主版本与验证 -1. **桌面宿主能力门禁**:`Lithe-core-rust` 已支持 `toolchainProviders: 0`(`litheToolchains` 的 `toolchains/query` 与 `toolchains.decodeReply`),但当前桌面宿主 `desktop/internal/pluginhost/pluginhost.go` 的 `Declared()` 尚未声明 `toolchainProviders`。若在 `plugin.json` 中直接写入 `"requires": {"toolchainProviders": 0}`,当前桌面宿主安装校验会拒绝安装整个插件。 -2. **自举约束**:Core 清单校验(`validate_packaged_provider_backend`)要求声明 `toolchainProviders` 的插件后端必须使用包内可执行文件(`packaged`)或包内自带运行时(`packagedRuntime`)自举,不能依赖所要发现的外部 `tool: "python"` 启动。 -3. **当前落地方案**:桌面宿主通过 `toolDefinitions` 中的 16 条声明式规则和新增的 `.conda` 项目环境候选发现解释器。独立协议测试协商 `experimental.litheToolchains` 并验证 `toolchains/query` 响应。正式接线仍需桌面宿主开放能力、清单声明及打包后端自举,当前安装包通过固定宿主校验。 +- 插件要求 `toolchainProviders: 0`。已发布的 Lithe 桌面 v0.8.6 无此能力,仅用于此前版本的回归。当前归档须在宣布该能力的兼容候选宿主上验收。 +- 候选宿主测试使用实际安装的插件、Conda 登记表和外部解释器副本,覆盖项目要求变更后切换解释器、全局候选、原生项目解释器信任及包文件哈希。 +- 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go index 2a10afb..cfcd37d 100644 --- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go @@ -76,6 +76,13 @@ func toWindowsVariantManifest(t *testing.T, unixManifest []byte) []byte { if err := json.Unmarshal(unixManifest, &doc); err != nil { t.Fatal(err) } + if backend, ok := doc["backend"].(map[string]any); ok { + if launch, ok := backend["launch"].(map[string]any); ok { + if path, ok := launch["path"].(string); ok && !strings.HasSuffix(path, ".exe") { + launch["path"] = path + ".exe" + } + } + } generators, _ := doc["projectGenerators"].([]any) for _, rawGen := range generators { gen, _ := rawGen.(map[string]any) @@ -136,6 +143,33 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() + providerHome := t.TempDir() + if canonical, err := filepath.EvalSymlinks(providerHome); err == nil { + providerHome = canonical + } + t.Setenv("HOME", providerHome) + t.Setenv("USERPROFILE", providerHome) + // Keep the provider's fixture independent of installed manager configurations. + for _, name := range []string{"APPDATA", "LOCALAPPDATA", "CONDA_ENVS_PATH", "CONDA_PREFIX", "UV_PYTHON_INSTALL_DIR", "PYENV_ROOT", "POETRY_VIRTUALENVS_PATH", "POETRY_CACHE_DIR", "WORKON_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME"} { + t.Setenv(name, "") + } + registeredHomes := []string{ + filepath.Join(providerHome, "registered-python-one"), + filepath.Join(providerHome, "registered-python-replacement"), + } + for _, home := range registeredHomes { + if out, err := exec.CommandContext(ctx, systemPython, "-m", "venv", "--copies", "--without-pip", home).CombinedOutput(); err != nil { + t.Fatalf("create regular-file external environment: %v\n%s", err, out) + } + } + registryDir := filepath.Join(providerHome, ".conda") + if err := os.MkdirAll(registryDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(registryDir, "environments.txt"), []byte(strings.Join(registeredHomes, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + kernel := core.NewClient() appStore := store.At(t.TempDir()) service, err := pluginservice.Open(kernel, appStore, filepath.Join(t.TempDir(), "Lithe Plugins")) @@ -235,7 +269,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("unexpected l10n rejections: %+v", settingsState.Localization.Rejected) } - // 4. Plan backend-resolved language server (Pyrefly), call real backend.py pyrefly.resolveLaunch + // 4. Plan backend-resolved language server (Pyrefly), call the packaged Pyrefly launch resolver // with and without tools.python.executable, decode via Core, and run pyrefly --version. stateDir := t.TempDir() wsStateDir := t.TempDir() @@ -685,8 +719,62 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("unexpected output links: %+v", links) } - // 8. Verify .venv toolchain resolution (including workspace trust gating) AND Core toolchains.decodeReply - // validation of scripts/toolchain_provider.py output! + // 8. Drive the real host's declared provider before creating a project-local .venv. + providerHost, ok := any(service).(interface { + ToolchainOptions(string, toolchain.Options) toolchain.Options + }) + if !ok { + t.Fatal("the pinned host lacks on-demand toolchain providers; use a compatible desktop revision") + } + service.Contexts.Open(workspace) + t.Cleanup(func() { service.Contexts.Close(workspace) }) + manifestSet := []json.RawMessage{normalizedManifest} + const providerID = pythonSupportPluginID + ":python" + pinFile := filepath.Join(workspace, ".python-version") + for _, expected := range registeredHomes { + if err := os.WriteFile(pinFile, []byte(filepath.Base(expected)+"\n"), 0o644); err != nil { + t.Fatal(err) + } + snapshot, err := toolchain.Load(ctx, kernel, workspace, ".", manifestSet, + providerHost.ToolchainOptions(workspace, toolchain.Options{Home: providerHome, Environment: map[string]string{}})) + if err != nil { + t.Fatalf("load provider toolchain: %v", err) + } + if len(snapshot.Tools) != 1 || snapshot.Tools[0].Effective == nil { + t.Fatalf("no effective project interpreter: %+v", snapshot.Tools) + } + selection := snapshot.Tools[0].Effective + if selection.Home == nil { + t.Fatalf("provider selection has no installation home: %+v", selection) + } + actual, actualErr := os.Stat(*selection.Home) + wanted, wantedErr := os.Stat(expected) + if actualErr != nil || wantedErr != nil || !os.SameFile(actual, wanted) || selection.Provider != providerID { + t.Fatalf("provider selection = %+v, want %s from %s", selection, expected, providerID) + } + } + global, err := toolchain.Load(ctx, kernel, "", ".", manifestSet, + providerHost.ToolchainOptions("", toolchain.Options{Global: true, Home: providerHome, Environment: map[string]string{}})) + if err != nil { + t.Fatalf("load global provider toolchains: %v", err) + } + if len(global.Tools) != 1 { + t.Fatalf("expected one global tool, got %+v", global.Tools) + } + for _, expected := range registeredHomes { + wanted, err := os.Stat(expected) + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(global.Tools[0].Installations, func(installation core.ToolchainInstallation) bool { + actual, err := os.Stat(installation.Home) + return err == nil && os.SameFile(actual, wanted) && installation.Provider == providerID + }) { + t.Fatalf("global provider did not register %s: %+v", expected, global.Tools[0]) + } + } + + // Verify .venv resolution retains its project trust gate. venvCmd := exec.CommandContext(ctx, systemPython, "-m", "venv", ".venv") venvCmd.Dir = workspace if out, err := venvCmd.CombinedOutput(); err != nil { @@ -733,123 +821,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { } } - // Verify real Core toolchains.decodeReply accepts scripts/toolchain_provider.py query_python_toolchains output. - extUvRoot := t.TempDir() - if resolvedExt, evalErr := filepath.EvalSymlinks(extUvRoot); evalErr == nil { - extUvRoot = resolvedExt - } - extPyHome := filepath.Join(extUvRoot, "cpython-3.12.6") - extPyBinDir := filepath.Join(extPyHome, "bin") - extPyExe := filepath.Join(extPyBinDir, "python3") - if runtime.GOOS == "windows" { - extPyBinDir = filepath.Join(extPyHome, "Scripts") - extPyExe = filepath.Join(extPyBinDir, "python.exe") - } - if err := os.MkdirAll(extPyBinDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(extPyExe, []byte("#!/bin/sh\necho Python 3.12.6\n"), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(extPyHome, "pyvenv.cfg"), []byte("version_info = 3.12.6\n"), 0o644); err != nil { - t.Fatal(err) - } - - tcReqParams := map[string]any{ - "operationID": "tc-core-e2e-1", - "generation": 1, - "providerID": "python", - "authority": map[string]any{"kind": "local"}, - "tools": []string{"python"}, - "workspace": map[string]any{"rootID": "ws-1", "root": workspace, "directory": "."}, - "context": map[string]any{"contextID": "ctx-e2e-1", "generation": 1}, - } - tcReqParamsJSON, _ := json.Marshal(tcReqParams) - pySnippet := fmt.Sprintf( - "import json, sys; sys.path.insert(0, %q); from pathlib import Path; from lithe_rpc import CallContext, CancelToken, DiagnosticsReporter; from toolchain_provider import query_python_toolchains, TOOLCHAIN_PROVIDER_DECLARATION; params = json.loads(sys.argv[1]); ctx = CallContext(cancel_token=CancelToken(), diagnostics=DiagnosticsReporter(lambda _: None, lambda _: True), suppress_cb=lambda: None); out = query_python_toolchains(params, ctx, home_dir=Path(%q), environ={'UV_PYTHON_INSTALL_DIR': %q}); print(json.dumps({'decl': TOOLCHAIN_PROVIDER_DECLARATION, 'reply': out}))", - filepath.Join(installedDir, "scripts"), - extUvRoot, - extUvRoot, - ) - tcOutBytes, err := exec.CommandContext(ctx, systemPython, "-I", "-B", "-c", pySnippet, string(tcReqParamsJSON)).CombinedOutput() - if err != nil { - t.Fatalf("running toolchain_provider.py failed: %v\n%s", err, tcOutBytes) - } - var tcBundle struct { - Decl json.RawMessage `json:"decl"` - Reply json.RawMessage `json:"reply"` - } - if err := json.Unmarshal(tcOutBytes, &tcBundle); err != nil { - t.Fatalf("unmarshaling toolchain_provider output: %v\n%s", err, tcOutBytes) - } - - // Build an in-memory manifest variant declaring toolchainProviders + packaged backend so Core toolchains.decodeReply - // checks every field, path, installation, and statement emitted by toolchain_provider.py! - var tcManifestMap map[string]any - if err := json.Unmarshal(normalizedManifest, &tcManifestMap); err != nil { - t.Fatal(err) - } - reqMap, _ := tcManifestMap["requires"].(map[string]any) - reqMap["toolchainProviders"] = 0 - perms, _ := tcManifestMap["permissions"].([]any) - tcManifestMap["permissions"] = append(perms, "toolchains.provide") - tcManifestMap["backend"] = map[string]any{ - "launch": map[string]any{"kind": "packaged", "path": expectedPyreflyRel}, - } - tcManifestMap["toolchainProviders"] = []any{tcBundle.Decl} - tcManifestBytes, _ := json.Marshal(tcManifestMap) - tcRegistryInput, err := toolchain.RegistryInput([]json.RawMessage{tcManifestBytes}) - if err != nil { - t.Fatal(err) - } - - pyprojectPath := filepath.Join(workspace, "pyproject.toml") - pyVerPath := filepath.Join(workspace, ".python-version") - condaTxtPath := filepath.Join(extUvRoot, ".conda", "environments.txt") - fsFacts := []core.ToolchainFileFact{ - {Path: workspace, CanonicalPath: workspace, Kind: "directory"}, - {Path: extUvRoot, CanonicalPath: extUvRoot, Kind: "directory"}, - {Path: extPyHome, CanonicalPath: extPyHome, Kind: "directory"}, - {Path: extPyExe, CanonicalPath: extPyExe, Kind: "file", Executable: true}, - {Path: pyprojectPath, CanonicalPath: pyprojectPath, Kind: "file"}, - {Path: pyVerPath, CanonicalPath: pyVerPath, Kind: "missing"}, - {Path: condaTxtPath, CanonicalPath: condaTxtPath, Kind: "missing"}, - } - wireReq, _ := json.Marshal(map[string]any{ - "jsonrpc": "2.0", - "id": "req-1", - "method": "toolchains/query", - "params": tcReqParams, - }) - wireResp, _ := json.Marshal(map[string]any{ - "jsonrpc": "2.0", - "id": "req-1", - "result": tcBundle.Reply, - }) - var decodeReplyOutcome struct { - Status string `json:"status"` - Error *core.MarketplaceRejection `json:"error"` - Snapshot json.RawMessage `json:"snapshot"` - } - if err := kernel.Execute(ctx, "toolchains.decodeReply", core.ToolchainQuery{ - Registry: tcRegistryInput, - PluginID: pythonSupportPluginID, - Request: wireReq, - Response: wireResp, - CurrentGeneration: 1, - Filesystem: fsFacts, - Platform: toolchain.PlatformName(runtime.GOOS), - WorkspaceRoots: []string{workspace}, - }, &decodeReplyOutcome); err != nil { - t.Fatalf("toolchains.decodeReply failed: %v", err) - } - if decodeReplyOutcome.Status != "ok" { - t.Fatalf("toolchains.decodeReply rejected reply: status=%s err=%+v", decodeReplyOutcome.Status, decodeReplyOutcome.Error) - } - if !strings.Contains(string(decodeReplyOutcome.Snapshot), "3.12.6") { - t.Fatalf("expected decoded toolchain snapshot to include installation 3.12.6, got %s", decodeReplyOutcome.Snapshot) - } - // Shut down backend cleanly BEFORE checking package immutability so any shutdown write would be caught too! service.Host.Stop(pythonSupportPluginID) diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index ca0926a..fbfce81 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,12 +1,12 @@ { - "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "9f4d5fb0597fc54223d85b8f06c9a1032a161bf8", + "repository": "https://github.com/Mucheen/Lithe-IDEA.git", + "revision": "8b80afb5031f55daad5a769bca7126f9e632cf59", "packages": { "./internal/projectgen": "^TestPythonPlugin", "./internal/workbench": "^TestPythonSupportPlugin" }, "requiredEnvironment": { - "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-0.2.0-darwin-arm64.zip" + "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-1.0.0-darwin-arm64.zip" }, "repositoryEnvironment": { "LITHE_PLUGIN_PYTHON_DIR": "io.github.lithe-idea.python-support" diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 7f1f4e3..334f564 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.python-support", "displayName": "Python Support", - "version": "0.2.0", + "version": "1.0.0", "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -20,7 +20,8 @@ "outputLinkMatchers": 0, "projectGenerators": 0, "settings": 0, - "toolDefinitions": 0 + "toolDefinitions": 0, + "toolchainProviders": 0 }, "requiresTools": ["python"], "permissions": [ @@ -29,7 +30,8 @@ "debug.launch", "languageServer.launch", "process.build", - "project.generate" + "project.generate", + "toolchains.provide" ], "activationEvents": [ "onBuildSystem:conda", @@ -41,13 +43,9 @@ ], "backend": { "launch": { - "kind": "runtime", - "tool": "python", - "minimumVersion": "3.9", - "runtimeArguments": ["-I", "-B"], - "entry": "scripts/backend.py" - }, - "arguments": ["--state", "${stateDir}"] + "kind": "packaged", + "path": "bin/lithe-python-backend" + } }, "languages": [ { @@ -465,6 +463,19 @@ ] } ], + "toolchainProviders": [ + { + "id": "python", + "displayName": "Python Environments", + "tools": ["python"], + "watchFiles": [ + { "pattern": ".python-version", "reader": "compatible" }, + { "pattern": "pyproject.toml", "reader": "native" }, + { "pattern": "Pipfile", "reader": "native" }, + { "pattern": "poetry.lock", "reader": "native" } + ] + } + ], "buildSystems": [ { "id": "python", diff --git a/io.github.lithe-idea.python-support/scripts/backend.py b/io.github.lithe-idea.python-support/scripts/backend.py deleted file mode 100644 index bf5d9cd..0000000 --- a/io.github.lithe-idea.python-support/scripts/backend.py +++ /dev/null @@ -1,177 +0,0 @@ -import os -import sys - -# Never write bytecode into the installed read-only plugin package or user workspace. -sys.dont_write_bytecode = True -os.environ["PYTHONDONTWRITEBYTECODE"] = "1" - -import argparse -from pathlib import Path -import threading -from typing import Any, Optional - -# Ensure sibling scripts are importable under Python 3.11+ `-I` safe_path mode. -_SCRIPTS_DIR = str(Path(__file__).resolve().parent) -if _SCRIPTS_DIR not in sys.path: - sys.path.insert(0, _SCRIPTS_DIR) - -from lithe_rpc import CallContext, JsonRpcServer, PluginError # noqa: E402 -from toolchain_provider import query_python_toolchains # noqa: E402 - -_VALID_TYPE_CHECKING_MODES = frozenset({"default", "auto", "basic", "strict", "all", "off"}) -_VALID_DISPLAY_TYPE_ERRORS = frozenset({"force-on", "default", "error-missing-imports", "force-off"}) -_VALID_DIAGNOSTIC_MODES = frozenset({"openFilesOnly", "workspace"}) -_VALID_IMPORT_FORMATS = frozenset({"absolute", "relative"}) - - -def _enum_setting(settings: dict[str, Any], key: str, allowed: frozenset[str], default: str) -> str: - val = settings.get(key) - return val if isinstance(val, str) and val in allowed else default - - -def _bool_setting(settings: dict[str, Any], key: str, default: bool) -> bool: - val = settings.get(key) - return val if isinstance(val, bool) else default - - -def create_backend_server(*, state_dir: Optional[str] = None) -> JsonRpcServer: - server = JsonRpcServer(name="python-support-backend", version="0.2.0") - degraded_workspaces: set[str] = set() - degraded_lock = threading.Lock() - - def _workspace_key(params: dict[str, Any], ctx: CallContext) -> str: - if isinstance(ctx.workspace_context, dict) and isinstance(ctx.workspace_context.get("contextID"), str): - return ctx.workspace_context["contextID"] - ws_state = params.get("workspaceStateDirectory") - if isinstance(ws_state, str) and ws_state: - return ws_state - return state_dir or "default" - - def resolve_pyrefly_launch(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: - server_id = params.get("serverID") - if server_id != "python": - raise PluginError("python.unknownServer", "Unsupported language server identifier.") - - platform_info = params.get("platform") - if isinstance(platform_info, dict) and isinstance(platform_info.get("os"), str): - os_name = platform_info["os"].strip().lower() - else: - os_name = "windows" if sys.platform == "win32" else ("macos" if sys.platform == "darwin" else "linux") - - packaged_path = "bin/pyrefly.exe" if os_name in ("windows", "win32") else "bin/pyrefly" - - raw_settings = params.get("settings") - settings = raw_settings if isinstance(raw_settings, dict) else {} - - diagnostic_mode = _enum_setting(settings, "diagnosticMode", _VALID_DIAGNOSTIC_MODES, "openFilesOnly") - python_cfg: dict[str, Any] = { - "pyrefly": { - "typeCheckingMode": _enum_setting( - settings, - "typeCheckingMode", - _VALID_TYPE_CHECKING_MODES, - "default", - ), - "displayTypeErrors": _enum_setting( - settings, - "displayTypeErrors", - _VALID_DISPLAY_TYPE_ERRORS, - "force-on", - ), - "diagnosticMode": diagnostic_mode, - }, - "analysis": { - "diagnosticMode": diagnostic_mode, - "autoImportCompletions": _bool_setting(settings, "autoImportCompletions", True), - "completeFunctionParens": _bool_setting(settings, "completeFunctionParens", False), - "importFormat": _enum_setting(settings, "importFormat", _VALID_IMPORT_FORMATS, "absolute"), - }, - } - - ws_key = _workspace_key(params, ctx) - hint_degraded = False - tools = params.get("tools") - if tools is not None: - if not isinstance(tools, dict): - hint_degraded = True - elif "python" in tools and tools["python"] is not None: - py_tool = tools["python"] - if not isinstance(py_tool, dict): - hint_degraded = True - else: - raw_exec = py_tool.get("executable") - if raw_exec is None or raw_exec == "": - pass - elif ( - isinstance(raw_exec, str) - and raw_exec.strip() == raw_exec - and not any(ord(ch) < 32 or ord(ch) == 127 for ch in raw_exec) - and len(raw_exec.encode("utf-8")) <= 4096 - ): - python_cfg["pythonPath"] = raw_exec - else: - hint_degraded = True - - if hint_degraded: - with degraded_lock: - degraded_workspaces.add(ws_key) - ctx.diagnostics.degraded("pyrefly.resolveLaunch", "invalid_tool_hint", 1) - else: - was_degraded = False - with degraded_lock: - if ws_key in degraded_workspaces: - degraded_workspaces.remove(ws_key) - was_degraded = True - if was_degraded: - ctx.diagnostics.recovered("pyrefly.resolveLaunch", "tool_hint_restored", 1) - - return { - "executable": { - "kind": "packaged", - "path": packaged_path, - }, - "arguments": ["lsp"], - "workspaceConfiguration": { - "python": python_cfg, - }, - } - - def inspect_environment(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: - ctx.raise_if_cancelled() - raw_exec = params.get("executable") - if raw_exec is not None: - if ( - not isinstance(raw_exec, str) - or not raw_exec.strip() - or any(ord(ch) < 32 or ord(ch) == 127 for ch in raw_exec) - or not Path(raw_exec).is_absolute() - ): - raise PluginError("python.invalidExecutable", "Executable must be an absolute path.") - target = Path(raw_exec) - home = target.parent.parent if target.parent.name.lower() in ("bin", "scripts") else target.parent - return { - "executable": str(target), - "isVirtualEnv": (home / "pyvenv.cfg").is_file() or (home / "conda-meta").is_dir(), - } - return { - "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", - "isVirtualEnv": sys.prefix != getattr(sys, "base_prefix", sys.prefix), - } - - server.function("pyrefly.resolveLaunch", resolve_pyrefly_launch) - server.function("python.inspectEnvironment", inspect_environment) - server.suppress_success_diagnostics("python.inspectEnvironment") - server.toolchain_provider("python", query_python_toolchains) - return server - - -def main(argv: list[str]) -> int: - parser = argparse.ArgumentParser(add_help=False) - parser.add_argument("--state", dest="state_dir", default=None) - known, _ = parser.parse_known_args(argv[1:]) - server = create_backend_server(state_dir=known.state_dir) - return server.listen() - - -if __name__ == "__main__": - raise SystemExit(main(sys.argv)) diff --git a/io.github.lithe-idea.python-support/scripts/lithe_rpc.py b/io.github.lithe-idea.python-support/scripts/lithe_rpc.py index 86448fa..b87d10d 100644 --- a/io.github.lithe-idea.python-support/scripts/lithe_rpc.py +++ b/io.github.lithe-idea.python-support/scripts/lithe_rpc.py @@ -17,7 +17,6 @@ FUNCTIONS_VERSION = 0 BUILD_VERSIONS = (1, 0) LOGGING_VERSION = 0 -TOOLCHAINS_VERSION = 0 MAX_SAFE_INTEGER = 9_007_199_254_740_991 MAX_INCOMING_FRAME_BYTES = 16 * 1024 * 1024 @@ -37,19 +36,6 @@ ERROR_REQUEST_FAILED = -32000 ERROR_REQUEST_CANCELLED = -32800 -TOOLCHAIN_ERROR_CODES = { - "plugin.toolchain.methodUnavailable": -32601, - "plugin.toolchain.invalidParams": -32602, - "plugin.toolchain.cancelled": -32800, - "plugin.toolchain.permissionDenied": -32070, - "plugin.toolchain.authorityUnsupported": -32071, - "plugin.toolchain.timeout": -32072, - "plugin.toolchain.providerUnavailable": -32073, - "plugin.toolchain.invalidReply": -32074, - "plugin.toolchain.limitExceeded": -32075, - "plugin.toolchain.unsafePath": -32076, - "plugin.toolchain.operationExpired": -32077, -} KNOWN_LOGGING_OPERATIONS = frozenset({ "initialize", @@ -156,28 +142,6 @@ def __init__(self, code: str, message: str) -> None: self.user_message = bounded_utf8(message, MAX_ERROR_MESSAGE_BYTES) -class ToolchainQueryError(Exception): - """Typed JSON-RPC error matching shared/plugins/contract/v1/toolchains/README.md.""" - - def __init__( - self, - stable_code: str, - message: str, - operation_id: str, - provider_id: str, - details: Optional[dict[str, Any]] = None, - ) -> None: - if stable_code not in TOOLCHAIN_ERROR_CODES: - raise ValueError(f"Unknown toolchain error code: {stable_code!r}") - super().__init__(message) - self.stable_code = stable_code - self.rpc_code = TOOLCHAIN_ERROR_CODES[stable_code] - self.user_message = bounded_utf8(message, MAX_ERROR_MESSAGE_BYTES) or "Toolchain query failed." - self.operation_id = operation_id - self.provider_id = provider_id - self.details = details - - class FramingError(Exception): """Raised when the incoming stdio stream violates Content-Length framing.""" @@ -366,7 +330,7 @@ def terminal(self, operation: str, error_code: Optional[str], duration_ms: float class CallContext: - """Per-request execution context passed to function, build, and toolchain handlers.""" + """Per-request execution context passed to function and build handlers.""" def __init__( self, @@ -468,7 +432,7 @@ def encode_frame(payload: dict[str, Any]) -> bytes: class JsonRpcServer: """ Pure-Python Lithe plugin backend / build provider stdio JSON-RPC server. - Implements litheLogging 0, litheFunctions 0, litheBuild 0/1, and litheToolchains 0. + Implements litheLogging 0, litheFunctions 0, and litheBuild 0/1. """ def __init__(self, *, name: str, version: str = "0.2.0") -> None: @@ -476,7 +440,6 @@ def __init__(self, *, name: str, version: str = "0.2.0") -> None: self.version = version self._functions: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {} self._build_handlers: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {} - self._toolchain_providers: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {} self._quiet_success: set[str] = set() self._initialize_hooks: list[Callable[[dict[str, Any]], None]] = [] self._shutdown_hooks: list[Callable[[], None]] = [] @@ -487,7 +450,6 @@ def __init__(self, *, name: str, version: str = "0.2.0") -> None: self._early_diagnostics: list[dict[str, Any]] = [] self._functions_version: Optional[int] = None self._build_version: Optional[int] = None - self._selected_toolchain_providers: set[str] = set() self.initialize_params: Optional[dict[str, Any]] = None self._write_lock = threading.Lock() @@ -513,15 +475,6 @@ def build_handler(self, method: str, handler: Callable[[dict[str, Any], CallCont self._build_handlers[method] = handler return self - def toolchain_provider( - self, - provider_id: str, - handler: Callable[[dict[str, Any], CallContext], Any], - ) -> "JsonRpcServer": - if not _PROVIDER_ID_RE.match(provider_id): - raise ValueError(f"Invalid toolchain provider ID: {provider_id!r}") - self._toolchain_providers[provider_id] = handler - return self def suppress_success_diagnostics(self, operation: str) -> "JsonRpcServer": if operation not in KNOWN_LOGGING_OPERATIONS and operation not in self._functions: @@ -711,9 +664,7 @@ def _handle_request(self, req_id: Any, method: str, params: Any) -> None: return self._submit(req_id, self._invoke_build, method, params) return - if method == "toolchains/query" and self._selected_toolchain_providers: - self._submit(req_id, self._invoke_toolchain_query, params) - return + self._respond( req_id, @@ -789,14 +740,6 @@ def _offers(entry: Any, version: int) -> bool: self._functions_version = FUNCTIONS_VERSION if _offers(offered.get("litheFunctions"), FUNCTIONS_VERSION) else None - self._selected_toolchain_providers = set() - tc_offer = offered.get("litheToolchains") - if _offers(tc_offer, TOOLCHAINS_VERSION) and isinstance(tc_offer, dict): - raw_providers = tc_offer.get("providers") - if isinstance(raw_providers, list) and len(raw_providers) <= 8: - for p_id in raw_providers: - if isinstance(p_id, str) and p_id in self._toolchain_providers: - self._selected_toolchain_providers.add(p_id) try: for hook in self._initialize_hooks: @@ -830,11 +773,7 @@ def _offers(entry: Any, version: int) -> bool: "version": self._functions_version, "functions": [{"id": fn_id} for fn_id in sorted(self._functions)], } - if self._selected_toolchain_providers: - experimental["litheToolchains"] = { - "version": TOOLCHAINS_VERSION, - "providers": sorted(self._selected_toolchain_providers), - } + with self._state_lock: self._phase = "ready" @@ -1001,108 +940,7 @@ def _stop_reporting() -> None: emit_logging=True, ) - def _invoke_toolchain_query(self, req_id: Any, token: CancelToken, raw_params: Any) -> None: - if not isinstance(raw_params, dict): - self._respond( - req_id, - error={ - "code": ERROR_INVALID_PARAMS, - "message": "Malformed toolchain query params.", - "data": { - "code": "plugin.toolchain.invalidParams", - "operationID": "", - "providerID": "", - }, - }, - ) - return - - provider_id = raw_params.get("providerID") if isinstance(raw_params.get("providerID"), str) else "" - op_id = raw_params.get("operationID") if isinstance(raw_params.get("operationID"), str) else "" - if provider_id not in self._selected_toolchain_providers: - self._respond( - req_id, - error={ - "code": ERROR_METHOD_NOT_FOUND, - "message": "The requested toolchain provider is not active on this session.", - "data": { - "code": "plugin.toolchain.methodUnavailable", - "operationID": op_id, - "providerID": provider_id, - }, - }, - ) - return - handler = self._toolchain_providers[provider_id] - ctx = CallContext( - cancel_token=token, - diagnostics=self._make_diagnostics(request_operation_id(op_id, req_id)), - suppress_cb=lambda: None, - operation_id=op_id, - ) - try: - token.raise_if_cancelled() - result = handler(raw_params, ctx) - token.raise_if_cancelled() - self._respond(req_id, result=result) - except CancelledError: - self._respond( - req_id, - error={ - "code": ERROR_REQUEST_CANCELLED, - "message": "The toolchain query was cancelled.", - "data": { - "code": "plugin.toolchain.cancelled", - "operationID": op_id, - "providerID": provider_id, - }, - }, - ) - except ToolchainQueryError as tc_err: - data_obj: dict[str, Any] = { - "code": tc_err.stable_code, - "operationID": tc_err.operation_id, - "providerID": tc_err.provider_id, - } - if tc_err.details is not None: - data_obj["details"] = tc_err.details - self._respond( - req_id, - error={ - "code": tc_err.rpc_code, - "message": tc_err.user_message, - "data": data_obj, - }, - ) - except Exception as exc: - if token.cancelled: - self._respond( - req_id, - error={ - "code": ERROR_REQUEST_CANCELLED, - "message": "The toolchain query was cancelled.", - "data": { - "code": "plugin.toolchain.cancelled", - "operationID": op_id, - "providerID": provider_id, - }, - }, - ) - else: - self._write_stderr_category("toolchain_query_failed", type(exc).__name__) - self._respond( - req_id, - error={ - "code": -32073, - "message": "The toolchain provider failed unexpectedly.", - "data": { - "code": "plugin.toolchain.providerUnavailable", - "operationID": op_id, - "providerID": provider_id, - }, - }, - ) def _execute_tracked( self, *, diff --git a/io.github.lithe-idea.python-support/scripts/toolchain_provider.py b/io.github.lithe-idea.python-support/scripts/toolchain_provider.py deleted file mode 100644 index c5381d3..0000000 --- a/io.github.lithe-idea.python-support/scripts/toolchain_provider.py +++ /dev/null @@ -1,727 +0,0 @@ -import os -import sys - -# Never write bytecode into the installed read-only plugin package or user workspace. -sys.dont_write_bytecode = True -os.environ["PYTHONDONTWRITEBYTECODE"] = "1" - -import base64 -import glob -import hashlib -import json -from pathlib import Path -import re -from typing import Any, Optional - -# Ensure sibling scripts are importable under Python 3.11+ `-I` safe_path mode. -_SCRIPTS_DIR = str(Path(__file__).resolve().parent) -if _SCRIPTS_DIR not in sys.path: - sys.path.insert(0, _SCRIPTS_DIR) - -from build_model import _load_tomllib # noqa: E402 -from lithe_rpc import CallContext, ToolchainQueryError, run_bounded_process # noqa: E402 - -PROVIDER_ID = "python" -SUPPORTED_TOOLS = frozenset({"python", "io.github.lithe-idea.python-support:python"}) - -TOOLCHAIN_PROVIDER_DECLARATION = { - "id": PROVIDER_ID, - "displayName": "Python Environments (conda / uv / pyenv / Poetry / Pipenv)", - "tools": ["python"], - "watchFiles": [ - {"pattern": ".python-version", "reader": "compatible"}, - {"pattern": "pyproject.toml", "reader": "native"}, - {"pattern": "Pipfile", "reader": "native"}, - {"pattern": "poetry.lock", "reader": "native"}, - ], -} - -_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") -_VERSION_EXTRACT_RE = re.compile(r"(\d+(?:\.\d+)+)") -_SPEC_CLAUSE_RE = re.compile(r"^(~=|==|!=|<=|>=|<|>|\^)\s*v?(\d+(?:\.\d+)*(?:\.\*)?)$") - -_MAX_INSTALLATIONS = 512 -_MAX_STATEMENTS = 256 -_MAX_WATCH_PATHS = 256 -_MAX_PROBES = 24 -_MAX_DIR_ENTRIES = 1024 - - -def _is_valid_id(value: Any) -> bool: - return isinstance(value, str) and _IDENTIFIER_RE.match(value) is not None and not any(ord(c) < 32 or ord(c) == 127 for c in value) - - -def _is_valid_rel_dir(value: Any) -> bool: - if not isinstance(value, str) or not value or len(value.encode("utf-8")) > 2048: - return False - if any(ord(c) < 32 or ord(c) == 127 for c in value): - return False - if value == ".": - return True - if "\\" in value or ":" in value: - return False - return all(part not in ("", ".", "..") for part in value.split("/")) - - -def _parse_version_tuple(ver: str) -> Optional[tuple[int, ...]]: - m = re.match(r"^(\d+(?:\.\d+)*)", ver.strip()) - if not m: - return None - parts = [int(p) for p in m.group(1).split(".")] - if len(parts) > 8: - return None - return tuple(parts) - - -def _normalize_version_tuple(parts: tuple[int, ...]) -> tuple[int, ...]: - trimmed = list(parts) - while len(trimmed) > 1 and trimmed[-1] == 0: - trimmed.pop() - return tuple(trimmed) - - -def _compare_versions(left: tuple[int, ...], right: tuple[int, ...]) -> int: - nl = _normalize_version_tuple(left) - nr = _normalize_version_tuple(right) - if nl < nr: - return -1 - if nl > nr: - return 1 - return 0 - - -def _matches_clause(candidate: tuple[int, ...], op: str, raw_target: str) -> bool: - wildcard = raw_target.endswith(".*") - base_str = raw_target[:-2] if wildcard else raw_target - if not re.match(r"^\d+(?:\.\d+)*$", base_str): - return False - target = tuple(int(x) for x in base_str.split(".")) - - if wildcard: - prefix = candidate[: len(target)] - padded = prefix + (0,) * max(0, len(target) - len(prefix)) - if op == "==": - return padded == target - if op == "!=": - return padded != target - return False - - cmp_val = _compare_versions(candidate, target) - if op == "==": - return cmp_val == 0 - if op == "!=": - return cmp_val != 0 - if op == ">=": - return cmp_val >= 0 - if op == "<=": - return cmp_val <= 0 - if op == ">": - return cmp_val > 0 - if op == "<": - return cmp_val < 0 - if op == "~=": - if cmp_val < 0: - return False - upper = list(target[:-1]) if len(target) > 1 else [target[0]] - upper[-1] += 1 - return _compare_versions(candidate, tuple(upper)) < 0 - if op == "^": - if cmp_val < 0: - return False - upper_list = list(target) - bumped = False - for idx, val in enumerate(upper_list): - if val != 0: - upper_list = upper_list[: idx + 1] - upper_list[idx] = val + 1 - bumped = True - break - if not bumped: - upper_list[-1] += 1 - return _compare_versions(candidate, tuple(upper_list)) < 0 - return False - - -def matches_python_requirement(version_str: str, requirement: str) -> bool: - """Evaluates PEP 440 / Poetry / .python-version requirement expressions.""" - ver_tuple = _parse_version_tuple(version_str) - if ver_tuple is None: - return False - req = requirement.strip() - if not req or req == "*": - return True - - # Plain dotted version or prefix from .python-version (e.g. "3.12", "3.12.4", "cpython-3.12.4-macos"). - cleaned = req - if cleaned.startswith("cpython-"): - cleaned = cleaned[len("cpython-") :] - cleaned = cleaned.split("-", 1)[0] - if re.match(r"^\d+(?:\.\d+)*$", cleaned): - target = tuple(int(x) for x in cleaned.split(".")) - if len(target) <= 2: - padded = ver_tuple[: len(target)] + (0,) * max(0, len(target) - len(ver_tuple)) - return padded == target - return _compare_versions(ver_tuple, target) == 0 - - clauses = [c.strip() for c in req.split(",") if c.strip()] - if not clauses: - return False - for clause in clauses: - m = _SPEC_CLAUSE_RE.match(clause) - if not m: - return False - if not _matches_clause(ver_tuple, m.group(1), m.group(2)): - return False - return True - - -def _within_dir(path: Path, root: Path, case_sensitive: bool) -> bool: - p_str = str(path) - r_str = str(root) - if not case_sensitive: - p_str = p_str.lower() - r_str = r_str.lower() - r_norm = r_str.rstrip("/\\") - p_norm = p_str.rstrip("/\\") - if p_norm == r_norm: - return True - sep = "\\" if "\\" in r_norm else "/" - return p_norm.startswith(r_norm + sep) - - -def _executable_layouts_for_platform(platform_name: str) -> list[str]: - if platform_name == "windows": - return ["Scripts/python.exe", "python.exe"] - return ["bin/python3", "bin/python"] - - -def _read_metadata_version(home_dir: Path) -> Optional[str]: - """Reads Python version from pyvenv.cfg or conda-meta/python-*.json without spawning a process.""" - pyvenv_cfg = home_dir / "pyvenv.cfg" - if pyvenv_cfg.is_file(): - try: - for raw_line in pyvenv_cfg.read_text(encoding="utf-8", errors="ignore").splitlines(): - if "=" not in raw_line: - continue - k, v = (part.strip() for part in raw_line.split("=", 1)) - if k in ("version_info", "version"): - m = _VERSION_EXTRACT_RE.search(v) - if m: - parts = m.group(1).split(".")[:3] - return ".".join(parts) - except OSError: - pass - - conda_meta = home_dir / "conda-meta" - if conda_meta.is_dir(): - try: - for entry in sorted(conda_meta.iterdir()): - if entry.name.startswith("python-") and entry.name.endswith(".json") and entry.is_file(): - data = json.loads(entry.read_text(encoding="utf-8", errors="ignore")) - if isinstance(data, dict) and data.get("name") == "python" and isinstance(data.get("version"), str): - m = _VERSION_EXTRACT_RE.match(data["version"].strip()) - if m: - return m.group(1) - except Exception: - pass - - # uv python directory naming fallback: cpython-3.12.6-macos-aarch64-none - m_uv = re.match(r"^(?:cpython|pypy)-(\d+\.\d+(?:\.\d+)?)\b", home_dir.name) - if m_uv: - return m_uv.group(1) - - # pyenv versions directory naming fallback: 3.12.4 - if re.match(r"^\d+\.\d+\.\d+$", home_dir.name): - return home_dir.name - - return None - - -def _list_subdirs_bounded(parent: Path, pattern: str = "*") -> list[Path]: - if not parent.is_dir(): - return [] - found: list[Path] = [] - try: - count = 0 - for entry in sorted(parent.iterdir(), key=lambda p: p.name): - if count >= _MAX_DIR_ENTRIES: - break - count += 1 - if entry.name.startswith(".") and not pattern.startswith("."): - continue - if glob.fnmatch.fnmatch(entry.name, pattern) and entry.is_dir(): - found.append(entry) - except OSError: - pass - return found - - -def _pipenv_virtualenv_prefix(project_dir: Path) -> str: - clean_name = re.sub(r'[ $`!*@"\\\r\n\t]', "_", project_dir.name)[:42] - digest = hashlib.sha256(str(project_dir).encode("utf-8")).digest()[:6] - encoded = base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")[:8] - return f"{clean_name}-{encoded}" - - -def _poetry_virtualenv_prefix(project_dir: Path, project_name: Optional[str]) -> str: - raw_name = project_name or project_dir.name - sanitized = re.sub(r'[ $`!*@"\\\r\n\t]', "_", raw_name).lower() - norm_path = os.path.normcase(str(project_dir.resolve())) - digest = hashlib.sha256(norm_path.encode("utf-8")).hexdigest()[:8] - return f"{sanitized}-{digest}-py" - - -def query_python_toolchains( - params: dict[str, Any], - ctx: CallContext, - *, - home_dir: Optional[Path] = None, - environ: Optional[dict[str, str]] = None, - platform_name: Optional[str] = None, - extra_workspace_roots: Optional[list[Path]] = None, -) -> dict[str, Any]: - """ - Executes `toolchains/query` for Python installations and project requirements, - returning `{operationID, generation, providerID, installations, statements, watch}` - strictly conforming to shared/plugins/contract/v1/toolchains/README.md. - """ - op_id = params.get("operationID") if isinstance(params.get("operationID"), str) else "" - provider_id = params.get("providerID") if isinstance(params.get("providerID"), str) else PROVIDER_ID - generation = params.get("generation") - - if ( - not _is_valid_id(op_id) - or isinstance(generation, bool) - or not isinstance(generation, int) - or generation <= 0 - or provider_id != PROVIDER_ID - or "workspace" not in params - or "context" not in params - ): - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Invalid query identities or missing workspace/context envelope.", - op_id, - provider_id, - ) - - authority = params.get("authority") - if not isinstance(authority, dict) or not isinstance(authority.get("kind"), str): - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Malformed query authority.", - op_id, - provider_id, - ) - if authority["kind"] == "remote": - raise ToolchainQueryError( - "plugin.toolchain.authorityUnsupported", - "Remote toolchain authority is not supported.", - op_id, - provider_id, - ) - if authority["kind"] != "local" or set(authority.keys()) != {"kind"}: - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Unsupported local authority shape.", - op_id, - provider_id, - ) - - tools = params.get("tools") - if ( - not isinstance(tools, list) - or not (1 <= len(tools) <= 64) - or any(not isinstance(t, str) or t not in SUPPORTED_TOOLS for t in tools) - or len(set(tools)) != len(tools) - or tools != sorted(tools) - ): - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Invalid or undeclared tools in toolchain query.", - op_id, - provider_id, - ) - target_tool = tools[0] - - ws_param = params.get("workspace") - ctx_param = params.get("context") - workspace_root: Optional[Path] = None - queried_dir: Optional[Path] = None - - if ws_param is not None: - if ( - not isinstance(ctx_param, dict) - or not _is_valid_id(ctx_param.get("contextID")) - or isinstance(ctx_param.get("generation"), bool) - or not isinstance(ctx_param.get("generation"), int) - or ctx_param["generation"] <= 0 - ): - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Workspace toolchain queries require a valid context reference.", - op_id, - provider_id, - ) - if ( - not isinstance(ws_param, dict) - or not _is_valid_id(ws_param.get("rootID")) - or not isinstance(ws_param.get("root"), str) - or not _is_valid_rel_dir(ws_param.get("directory")) - ): - raise ToolchainQueryError( - "plugin.toolchain.invalidParams", - "Invalid workspace query parameters.", - op_id, - provider_id, - ) - raw_ws_root = Path(ws_param["root"]) - if not raw_ws_root.is_absolute() or not raw_ws_root.is_dir(): - raise ToolchainQueryError( - "plugin.toolchain.unsafePath", - "Workspace root must be an existing absolute directory.", - op_id, - provider_id, - ) - workspace_root = raw_ws_root.resolve() - rel_dir = ws_param["directory"] - target_dir = workspace_root if rel_dir == "." else (workspace_root / Path(*rel_dir.split("/"))) - if not target_dir.is_dir(): - raise ToolchainQueryError( - "plugin.toolchain.unsafePath", - "Queried workspace directory does not exist.", - op_id, - provider_id, - ) - queried_dir = target_dir.resolve() - - eff_platform = platform_name or ( - "windows" if sys.platform == "win32" else ("macos" if sys.platform == "darwin" else "linux") - ) - case_sensitive = eff_platform != "windows" - if workspace_root is not None and queried_dir is not None: - if not _within_dir(queried_dir, workspace_root, case_sensitive): - raise ToolchainQueryError( - "plugin.toolchain.unsafePath", - "Queried directory escapes workspace root.", - op_id, - provider_id, - ) - - eff_env = environ if environ is not None else dict(os.environ) - eff_home = (home_dir if home_dir is not None else Path.home()).resolve() - forbidden_roots: list[Path] = [] - if workspace_root is not None: - forbidden_roots.append(workspace_root) - for extra in extra_workspace_roots or []: - try: - forbidden_roots.append(extra.resolve()) - except OSError: - pass - - watch_paths: set[str] = set() - candidate_homes: list[Path] = [] - - # 1. ~/.conda/environments.txt - conda_envs_txt = eff_home / ".conda" / "environments.txt" - watch_paths.add(str(conda_envs_txt)) - if conda_envs_txt.is_file(): - try: - for line in conda_envs_txt.read_text(encoding="utf-8", errors="ignore").splitlines(): - stripped = line.strip() - if not stripped or stripped.startswith("#"): - continue - p = Path(stripped) - if p.is_absolute() and p.is_dir(): - candidate_homes.append(p) - except OSError: - pass - - # 2. CONDA_ENVS_PATH (supports os.pathsep-separated directories) & CONDA_PREFIX & standard conda dirs - raw_conda_envs = eff_env.get("CONDA_ENVS_PATH", "").strip() - if raw_conda_envs: - for chunk in raw_conda_envs.split(os.pathsep): - chunk = chunk.strip() - if chunk and Path(chunk).is_absolute(): - candidate_homes.extend(_list_subdirs_bounded(Path(chunk))) - raw_conda_prefix = eff_env.get("CONDA_PREFIX", "").strip() - if raw_conda_prefix and Path(raw_conda_prefix).is_absolute(): - cp = Path(raw_conda_prefix) - if cp.is_dir(): - candidate_homes.append(cp) - candidate_homes.extend(_list_subdirs_bounded(cp / "envs")) - for pattern in ("*conda*", "miniforge*"): - for base in _list_subdirs_bounded(eff_home, pattern): - candidate_homes.append(base) - candidate_homes.extend(_list_subdirs_bounded(base / "envs")) - - # 3. UV_PYTHON_INSTALL_DIR / XDG_DATA_HOME / default uv python dirs - uv_dir_env = eff_env.get("UV_PYTHON_INSTALL_DIR", "").strip() - if uv_dir_env and Path(uv_dir_env).is_absolute(): - uv_root = Path(uv_dir_env) - watch_paths.add(str(uv_root)) - candidate_homes.extend(_list_subdirs_bounded(uv_root)) - xdg_data = eff_env.get("XDG_DATA_HOME", "").strip() - if xdg_data and Path(xdg_data).is_absolute(): - candidate_homes.extend(_list_subdirs_bounded(Path(xdg_data) / "uv" / "python")) - candidate_homes.extend(_list_subdirs_bounded(eff_home / ".local" / "share" / "uv" / "python")) - appdata = eff_env.get("APPDATA", "").strip() - if appdata and Path(appdata).is_absolute(): - candidate_homes.extend(_list_subdirs_bounded(Path(appdata) / "uv" / "data" / "python")) - - # 4. PYENV_ROOT / ~/.pyenv - pyenv_root = eff_env.get("PYENV_ROOT", "").strip() - if pyenv_root and Path(pyenv_root).is_absolute(): - pr = Path(pyenv_root) / "versions" - watch_paths.add(str(pr)) - candidate_homes.extend(_list_subdirs_bounded(pr)) - candidate_homes.extend(_list_subdirs_bounded(eff_home / ".pyenv" / "versions")) - candidate_homes.extend(_list_subdirs_bounded(eff_home / ".pyenv" / "pyenv-win" / "versions")) - - # 5. Poetry & Pipenv / WORKON_HOME external virtualenvs - poetry_roots: list[Path] = [] - poetry_cache = eff_env.get("POETRY_CACHE_DIR", "").strip() - if poetry_cache and Path(poetry_cache).is_absolute(): - poetry_roots.append(Path(poetry_cache) / "virtualenvs") - if eff_platform == "macos": - poetry_roots.append(eff_home / "Library" / "Caches" / "pypoetry" / "virtualenvs") - elif eff_platform == "windows": - local_app = eff_env.get("LOCALAPPDATA", "").strip() - if local_app and Path(local_app).is_absolute(): - poetry_roots.append(Path(local_app) / "pypoetry" / "Cache" / "virtualenvs") - else: - xdg_cache = eff_env.get("XDG_CACHE_HOME", "").strip() - if xdg_cache and Path(xdg_cache).is_absolute(): - poetry_roots.append(Path(xdg_cache) / "pypoetry" / "virtualenvs") - poetry_roots.append(eff_home / ".cache" / "pypoetry" / "virtualenvs") - for p_root in poetry_roots: - candidate_homes.extend(_list_subdirs_bounded(p_root)) - - workon = eff_env.get("WORKON_HOME", "").strip() - if workon and Path(workon).is_absolute(): - candidate_homes.extend(_list_subdirs_bounded(Path(workon))) - candidate_homes.extend(_list_subdirs_bounded(eff_home / ".local" / "share" / "virtualenvs")) - candidate_homes.extend(_list_subdirs_bounded(eff_home / ".virtualenvs")) - - layouts = _executable_layouts_for_platform(eff_platform) - installations_by_key: dict[str, dict[str, str]] = {} - probes_used = 0 - - for raw_home in candidate_homes: - ctx.raise_if_cancelled() - if len(installations_by_key) >= _MAX_INSTALLATIONS: - break - try: - canon_home = raw_home.resolve() - except OSError: - continue - if not canon_home.is_dir(): - continue - if any(_within_dir(canon_home, root, case_sensitive) for root in forbidden_roots): - continue - - home_key = str(canon_home) if case_sensitive else str(canon_home).lower() - if home_key in installations_by_key: - continue - - matched_exec: Optional[Path] = None - for rel_layout in layouts: - candidate_exec = canon_home / Path(*rel_layout.split("/")) - if not candidate_exec.exists(): - continue - try: - canon_exec = candidate_exec.resolve() - except OSError: - continue - if not canon_exec.is_file(): - continue - if eff_platform != "windows" and not os.access(canon_exec, os.X_OK): - continue - # Core query.rs requires a provider installation's resolved executable to stay inside - # canonical_home and outside workspace roots. - if not _within_dir(canon_exec, canon_home, case_sensitive): - continue - if any(_within_dir(canon_exec, root, case_sensitive) for root in forbidden_roots): - continue - matched_exec = canon_exec - break - - if matched_exec is None: - continue - - version_str = _read_metadata_version(canon_home) - if version_str is None and probes_used < _MAX_PROBES: - probes_used += 1 - probe_env = dict(eff_env) - probe_env["PYTHONDONTWRITEBYTECODE"] = "1" - try: - code, out, timed_out = run_bounded_process( - [str(matched_exec), "--version"], - cwd=str(canon_home), - env=probe_env, - cancel_token=ctx.cancel_token, - timeout_seconds=3.0, - max_output_bytes=4096, - ) - if not timed_out and code == 0: - m = re.search(r"Python\s+(\d+(?:\.\d+)*)", out) - if m: - version_str = m.group(1) - except OSError: - version_str = None - - if not version_str or _parse_version_tuple(version_str) is None: - continue - - installations_by_key[home_key] = { - "tool": target_tool, - "version": version_str, - "home": str(canon_home), - } - - # Sort installations deterministically: highest version first, then home path. - sorted_installations = sorted( - installations_by_key.values(), - key=lambda item: ( - tuple(-part for part in (_parse_version_tuple(item["version"]) or (0,))), - item["home"], - ), - ) - - def _pick_best_installation(req_spec: str, allow_env_name: bool = False) -> Optional[str]: - cleaned = req_spec.strip() - if not cleaned: - return None - if allow_env_name: - for inst in sorted_installations: - if Path(inst["home"]).name == cleaned: - return inst["home"] - best_home: Optional[str] = None - best_ver: Optional[tuple[int, ...]] = None - for inst in sorted_installations: - if matches_python_requirement(inst["version"], cleaned): - vt = _parse_version_tuple(inst["version"]) - if vt is not None and (best_ver is None or _compare_versions(vt, best_ver) > 0): - best_ver = vt - best_home = inst["home"] - return best_home - - statements: list[dict[str, Any]] = [] - if workspace_root is not None and queried_dir is not None: - ancestors: list[Path] = [] - cur = queried_dir - for _ in range(64): - ancestors.append(cur) - if cur == workspace_root or cur.parent == cur: - break - cur = cur.parent - - tomllib = _load_tomllib() - for anc in ancestors: - if len(statements) >= _MAX_STATEMENTS: - break - - py_ver_file = anc / ".python-version" - watch_paths.add(str(py_ver_file)) - if py_ver_file.is_file(): - try: - lines = [ - ln.strip() - for ln in py_ver_file.read_text(encoding="utf-8", errors="ignore").splitlines() - if ln.strip() and not ln.strip().startswith("#") - ] - if lines: - req_line = lines[0][:512] - statements.append({ - "tool": target_tool, - "scope": "project", - "source": str(py_ver_file.resolve()), - "request": req_line, - "installation": _pick_best_installation(req_line, allow_env_name=True), - "kind": "declaration", - "reader": "compatible", - }) - except OSError: - pass - - pyproject_file = anc / "pyproject.toml" - watch_paths.add(str(pyproject_file)) - project_name_hint: Optional[str] = None - if pyproject_file.is_file(): - try: - data = tomllib.loads(pyproject_file.read_text(encoding="utf-8")) - if isinstance(data, dict): - proj_tbl = data.get("project") - req_py: Optional[str] = None - if isinstance(proj_tbl, dict): - if isinstance(proj_tbl.get("name"), str) and proj_tbl["name"].strip(): - project_name_hint = proj_tbl["name"].strip() - if isinstance(proj_tbl.get("requires-python"), str) and proj_tbl["requires-python"].strip(): - req_py = proj_tbl["requires-python"].strip() - poetry_tbl = (data.get("tool") or {}).get("poetry") if isinstance(data.get("tool"), dict) else None - if isinstance(poetry_tbl, dict): - if not project_name_hint and isinstance(poetry_tbl.get("name"), str): - project_name_hint = poetry_tbl["name"].strip() or None - deps = poetry_tbl.get("dependencies") - if not req_py and isinstance(deps, dict) and isinstance(deps.get("python"), str): - req_py = deps["python"].strip() or None - if req_py: - statements.append({ - "tool": target_tool, - "scope": "project", - "source": str(pyproject_file.resolve()), - "request": req_py[:512], - "installation": _pick_best_installation(req_py, allow_env_name=False), - "kind": "declaration", - "reader": "native", - }) - except Exception: - pass - - poetry_lock = anc / "poetry.lock" - if poetry_lock.is_file(): - watch_paths.add(str(poetry_lock)) - prefix = _poetry_virtualenv_prefix(anc, project_name_hint) - matched_poetry = next( - (inst["home"] for inst in sorted_installations if Path(inst["home"]).name.lower().startswith(prefix)), - None, - ) - if matched_poetry is not None: - statements.append({ - "tool": target_tool, - "scope": "project", - "source": str(poetry_lock.resolve()), - "request": Path(matched_poetry).name[:512], - "installation": matched_poetry, - "kind": "environment", - "reader": "native", - }) - - pipfile = anc / "Pipfile" - if pipfile.is_file(): - watch_paths.add(str(pipfile)) - pipenv_prefix = _pipenv_virtualenv_prefix(anc) - matched_pipenv = next( - (inst["home"] for inst in sorted_installations if Path(inst["home"]).name == pipenv_prefix), - None, - ) - if matched_pipenv is not None: - statements.append({ - "tool": target_tool, - "scope": "project", - "source": str(pipfile.resolve()), - "request": pipenv_prefix[:512], - "installation": matched_pipenv, - "kind": "environment", - "reader": "native", - }) - - bounded_watch = sorted(watch_paths)[:_MAX_WATCH_PATHS] - return { - "operationID": op_id, - "generation": generation, - "providerID": provider_id, - "installations": sorted_installations[:_MAX_INSTALLATIONS], - "statements": statements[:_MAX_STATEMENTS], - "watch": bounded_watch, - } diff --git a/scripts/lib/backend.mjs b/scripts/lib/backend.mjs new file mode 100644 index 0000000..1f4ead7 --- /dev/null +++ b/scripts/lib/backend.mjs @@ -0,0 +1,74 @@ +// Compiles the package-local Rust backend and collects its dependency licenses. +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { dirname, join } from "node:path"; + +const targets = Object.freeze({ + "darwin-arm64": "aarch64-apple-darwin", + "darwin-x64": "x86_64-apple-darwin", + "linux-arm64": "aarch64-unknown-linux-musl", + "linux-x64": "x86_64-unknown-linux-musl", + "windows-arm64": "aarch64-pc-windows-msvc", + "windows-x64": "x86_64-pc-windows-msvc", +}); + +export function backendPath(platform) { + return `bin/lithe-python-backend${platform.startsWith("windows-") ? ".exe" : ""}`; +} + +export function rustTarget(platform) { + const target = targets[platform]; + if (!target) throw new Error(`No backend target configured for ${platform}`); + return target; +} + +function cargo(root, args) { + return execFileSync(process.env.CARGO || "cargo", args, { + cwd: root, + encoding: "utf8", + timeout: 10 * 60 * 1000, + maxBuffer: 16 * 1024 * 1024, + stdio: ["ignore", "pipe", "inherit"], + windowsHide: true, + }); +} + +export function buildBackend(root, platform) { + const target = rustTarget(platform); + const messages = cargo(root, [ + "build", "--locked", "--release", "--target", target, "--message-format=json-render-diagnostics", + "--manifest-path", "backend/Cargo.toml", + ]); + const artifact = messages.trim().split("\n").map((line) => JSON.parse(line)) + .find((event) => event.reason === "compiler-artifact" + && event.target.name === "lithe-python-backend" && event.executable); + if (!artifact) throw new Error(`Cargo did not produce an executable for ${target}`); + return artifact.executable; +} + +export function dependencyNotices(root) { + const metadata = JSON.parse(cargo(root, [ + "metadata", "--format-version", "1", "--locked", "--manifest-path", "backend/Cargo.toml", + ])); + const dependencies = metadata.packages.filter((pkg) => pkg.source) + .sort((left, right) => left.name.localeCompare(right.name, "en") || left.version.localeCompare(right.version, "en")); + const sections = dependencies.map((pkg) => { + const directory = dirname(pkg.manifest_path); + const licenses = readdirSync(directory, { withFileTypes: true }) + .filter((entry) => entry.isFile() && /^(?:licen[cs]e|notice|copying|copyright)(?:\b|_)/i.test(entry.name)) + .map((entry) => join(directory, entry.name)); + if (pkg.license_file) { + licenses.push(join(directory, pkg.license_file)); + } + if (pkg.name === "lithe-plugin-sdk" && licenses.length === 0) { + // The Git SDK shares its license with the sibling SDK packages. + licenses.push(join(directory, "..", "..", "..", "LICENSE")); + } + if (licenses.length === 0 || licenses.some((path) => !existsSync(path))) { + throw new Error(`Missing dependency license for ${pkg.name} ${pkg.version}`); + } + const texts = [...new Set(licenses.sort().map((path) => readFileSync(path, "utf8").trim()))]; + return [`${pkg.name} ${pkg.version} (${pkg.license})`, ...texts].join("\n\n"); + }); + return `Licenses for the packaged Rust backend's locked dependencies.\n\n${sections.join("\n\n------------------------------------------------------------------------\n\n")}\n`; +} diff --git a/scripts/package.mjs b/scripts/package.mjs index 3daf9ec..e133c9a 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -30,6 +30,7 @@ import { extractWheelSubtree, writeDeterministicZip, } from "./lib/archive.mjs"; +import { backendPath, buildBackend, dependencyNotices } from "./lib/backend.mjs"; const ROOT = fileURLToPath(new URL("..", import.meta.url)); export const PACKAGE_ID = "io.github.lithe-idea.python-support"; @@ -54,6 +55,7 @@ export function manifestForPlatform(baseManifest, platform, lock) { } const clone = structuredClone(baseManifest); const isWindows = platform.startsWith("windows-"); + clone.backend.launch.path = backendPath(platform); for (const server of clone.languageServers ?? []) { if (server.languageID === "python" && server.launch?.kind === "packaged") { @@ -174,6 +176,7 @@ export async function packagePlatforms({ platforms, expectTag, cleanDist = false expectedSha256: tomliSpec.sha256, }); + const notices = dependencyNotices(ROOT); const built = []; for (const platform of selectedPlatforms) { const pyreflySpec = lock.pyrefly.platforms[platform]; @@ -211,6 +214,13 @@ export async function packagePlatforms({ platforms, expectTag, cleanDist = false writeFileSync(pyreflyDest, pyreflyBytes); chmodSync(pyreflyDest, 0o755); + const backendDest = join(stagePackageDir, backendPath(platform)); + copyFileSync(buildBackend(ROOT, platform), backendDest); + chmodSync(backendDest, 0o755); + const noticesDest = join(stagePackageDir, "RUST-THIRD-PARTY-NOTICES.txt"); + writeFileSync(noticesDest, notices, "utf8"); + chmodSync(noticesDest, 0o644); + // Extract debugpy and tomli into vendor/. const vendorDir = join(stagePackageDir, "vendor"); extractWheelSubtree(debugpyWheel, "debugpy", vendorDir); diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index 3424265..e3a84b1 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -4,12 +4,29 @@ import assert from "node:assert/strict"; import { existsSync, readdirSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import { readZipEntries } from "../lib/archive.mjs"; +import { backendPath } from "../lib/backend.mjs"; import { ASSET_PREFIX, PACKAGE_ID } from "../package.mjs"; const baseManifest = JSON.parse(readFileSync(`${PACKAGE_ID}/plugin.json`, "utf8")); const lock = JSON.parse(readFileSync("vendor-lock.json", "utf8")); const version = baseManifest.version; +function checkBackendArchitecture(bytes, platform) { + const arm = platform.endsWith("-arm64"); + if (platform.startsWith("windows-")) { + assert.equal(bytes.toString("ascii", 0, 2), "MZ"); + const peHeader = bytes.readUInt32LE(0x3c); + assert.equal(bytes.readUInt32LE(peHeader), 0x4550); + assert.equal(bytes.readUInt16LE(peHeader + 4), arm ? 0xaa64 : 0x8664); + } else if (platform.startsWith("linux-")) { + assert.equal(bytes.readUInt32BE(0), 0x7f454c46); + assert.equal(bytes.readUInt16LE(18), arm ? 183 : 62); + } else { + assert.equal(bytes.readUInt32LE(0), 0xfeedfacf); + assert.equal(bytes.readUInt32LE(4), arm ? 0x0100000c : 0x01000007); + } +} + function builtArchives() { if (!existsSync("dist")) return []; return readdirSync("dist") @@ -25,6 +42,9 @@ function builtArchives() { test("at least one release archive exists in dist/ and matches vendor-lock platforms", () => { const archives = builtArchives(); assert.ok(archives.length >= 1, "Expected at least one built archive in dist/"); + if (process.env.LITHE_EXPECT_ALL_ARCHIVES === "1") { + assert.deepEqual(archives.map((archive) => archive.platform), Object.keys(lock.pyrefly.platforms).sort()); + } for (const archive of archives) { assert.ok(lock.pyrefly.platforms[archive.platform], `Unexpected platform ${archive.platform} for ${archive.name}`); } @@ -39,6 +59,7 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla const folded = new Set(); let manifestEntry = null; let pyreflyEntry = null; + let backendEntry = null; for (const entry of entries) { assert.equal(entry.isSymlink, false, `${archive.name}: symbolic link forbidden (${entry.name})`); @@ -60,22 +81,26 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla if (entry.name === `${PACKAGE_ID}/plugin.json`) manifestEntry = entry; const expectedPyrefly = `${PACKAGE_ID}/${lock.pyrefly.platforms[archive.platform].packagePath}`; if (entry.name === expectedPyrefly) pyreflyEntry = entry; + if (entry.name === `${PACKAGE_ID}/${backendPath(archive.platform)}`) backendEntry = entry; } assert.ok(manifestEntry, `${archive.name}: missing plugin.json`); assert.ok(pyreflyEntry, `${archive.name}: missing pyrefly binary`); assert.equal(pyreflyEntry.unixMode & 0o111, 0o111, `${archive.name}: pyrefly binary must have executable mode`); + assert.ok(backendEntry, `${archive.name}: missing the Rust backend`); + assert.equal(backendEntry.unixMode & 0o111, 0o111, `${archive.name}: backend must have executable mode`); + checkBackendArchitecture(backendEntry.data, archive.platform); + for (const required of [ `${PACKAGE_ID}/LICENSE`, `${PACKAGE_ID}/THIRD-PARTY-NOTICES.txt`, + `${PACKAGE_ID}/RUST-THIRD-PARTY-NOTICES.txt`, `${PACKAGE_ID}/l10n/zh-Hans.json`, `${PACKAGE_ID}/scripts/lithe_rpc.py`, `${PACKAGE_ID}/scripts/windows_job.py`, - `${PACKAGE_ID}/scripts/backend.py`, `${PACKAGE_ID}/scripts/build_model.py`, `${PACKAGE_ID}/scripts/build_provider.py`, - `${PACKAGE_ID}/scripts/toolchain_provider.py`, `${PACKAGE_ID}/scripts/debugpy_adapter.py`, `${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`, `${PACKAGE_ID}/vendor/debugpy/ThirdPartyNotices.txt`, @@ -95,6 +120,9 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla assert.deepEqual(manifest.requires, baseManifest.requires); assert.deepEqual(manifest.vendor, baseManifest.vendor); + assert.deepEqual(manifest.backend, { launch: { kind: "packaged", path: backendPath(archive.platform) } }); + assert.deepEqual(manifest.toolchainProviders, baseManifest.toolchainProviders); + assert.equal(manifest.requires.toolchainProviders, 0); const isWindows = archive.platform.startsWith("windows-"); const pyreflyServer = manifest.languageServers.find((s) => s.languageID === "python"); assert.deepEqual(pyreflyServer.launch, { diff --git a/scripts/test.mjs b/scripts/test.mjs index 781d6fe..192ab2d 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -// Runs static contract checks, unit + protocol tests for scripts/{backend,build_model,build_provider,toolchain_provider}.py, +// Runs static contract checks, unit + protocol tests for the Rust backend and Python build scripts, // and live end-to-end smoke tests against the unpacked plugin package (backend-resolved pyrefly launch with // external tools.python.executable injection and .venv fallback, toolchains/query, pytest --collect-only discovery // and JUnit XML execution, cancellation process-tree cleanup, project templates, and debugpy DAP launch), @@ -12,6 +12,7 @@ import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { chmodSync, existsSync, @@ -25,9 +26,10 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join, normalize, resolve } from "node:path"; +import { basename, dirname, join, normalize, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { readZipEntries } from "./lib/archive.mjs"; +import { backendPath } from "./lib/backend.mjs"; import { ASSET_PREFIX, manifestForPlatform, PACKAGE_ID, packagePlatforms, sha256File } from "./package.mjs"; const ROOT = fileURLToPath(new URL("..", import.meta.url)); @@ -313,11 +315,21 @@ try { assert.equal(variant.schemaVersion, 0); assert.equal(variant.pluginAPIVersion, 0); assert.equal(variant.id, "io.github.lithe-idea.python-support"); - assert.equal(variant.version, "0.2.0"); + assert.equal(variant.version, sourceManifest.version); assert.equal(variant.vendor.id, "io.github.lithe-idea"); assert.equal(variant.vendor.signatureRequirement, "none"); assert.equal("commandInstallers" in variant, false, "must not declare commandInstallers"); - assert.equal("toolchainProviders" in variant, false, "must omit toolchainProviders until desktop host declares it"); + assert.deepEqual(variant.toolchainProviders, [{ + id: "python", + displayName: "Python Environments", + tools: ["python"], + watchFiles: [ + { pattern: ".python-version", reader: "compatible" }, + { pattern: "pyproject.toml", reader: "native" }, + { pattern: "Pipfile", reader: "native" }, + { pattern: "poetry.lock", reader: "native" }, + ], + }]); assert.equal("$schema" in variant, false, "plugin.json must not contain $schema"); assert.deepEqual(Object.keys(variant.requires).sort(), [ "backend", @@ -330,6 +342,7 @@ try { "projectGenerators", "settings", "toolDefinitions", + "toolchainProviders", ]); for (const ver of Object.values(variant.requires)) { assert.equal(ver, 0); @@ -341,17 +354,11 @@ try { "languageServer.launch", "process.build", "project.generate", + "toolchains.provide", ]); assert.deepEqual(variant.backend, { - launch: { - kind: "runtime", - tool: "python", - minimumVersion: "3.9", - runtimeArguments: ["-I", "-B"], - entry: "scripts/backend.py", - }, - arguments: ["--state", "${stateDir}"], + launch: { kind: "packaged", path: backendPath(platform) }, }); const pyLang = variant.languages[0]; @@ -435,7 +442,7 @@ try { const beforeSnapshot = snapshotDirectoryHashes(unpackedPluginDir); const buildModelScript = join(unpackedPluginDir, "scripts", "build_model.py"); - const backendScript = join(unpackedPluginDir, "scripts", "backend.py"); + const backendExecutable = join(unpackedPluginDir, pluginManifest.backend.launch.path); const buildProviderScript = join(unpackedPluginDir, "scripts", "build_provider.py"); await check("build_model.py discovers PEP 621 scripts, src/ packages, tests, and .venv/.conda exclusions", () => { @@ -547,7 +554,7 @@ try { assert.ok(!missing.stderr.includes("secret-path-token-do-not-log"), "stderr must never echo raw paths"); }); - await check("backend.py negotiates litheLogging + litheFunctions, resolves Unix/Windows pyrefly launch, and injects external tools.python.executable into pyrefly LSP", async () => { + await check("The packaged SDK backend negotiates litheLogging + litheFunctions, resolves Unix/Windows pyrefly launch, and injects external tools.python.executable into pyrefly LSP", async () => { const stateDir = join(scratch, "backend-state"); const wsStateDir = join(scratch, "backend-ws-state"); const logDir = join(scratch, "backend-log"); @@ -565,7 +572,7 @@ try { mkdirSync(join(extSite, "external_env_pkg"), { recursive: true }); writeFileSync(join(extSite, "external_env_pkg", "__init__.py"), "def magic_number() -> int:\n return 7\n"); - const child = spawn(pythonCmd, ["-I", "-B", backendScript, "--state", stateDir], { + const child = spawn(backendExecutable, [], { cwd: scratch, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, @@ -805,7 +812,7 @@ try { }); const unknownMethodErr = await peer.waitFor((m) => m.id === 81, "unknown method error"); assert.equal(unknownMethodErr.error?.code, -32601); - assert.equal(unknownMethodErr.error?.message, "The requested method is not supported."); + assert.ok(unknownMethodErr.error?.message, "unknown method must return a diagnostic"); assert.ok(!unknownMethodErr.error.message.includes("secret")); peer.send({ @@ -820,7 +827,7 @@ try { }); const unknownFnErr = await peer.waitFor((m) => m.id === 82, "unknown function error"); assert.equal(unknownFnErr.error?.code, -32602); - assert.equal(unknownFnErr.error?.message, "The requested plugin function is not registered."); + assert.ok(unknownFnErr.error?.message, "unknown function must return a diagnostic"); assert.ok(!unknownFnErr.error.message.includes("secret")); // 7. Clean shutdown + exit without creating any custom log files. @@ -829,7 +836,7 @@ try { peer.send({ jsonrpc: "2.0", method: "exit", params: null }); const exitCode = await peer.waitExit(); assert.equal(exitCode, 0); - assert.deepEqual(readdirSync(logDir), [], "backend.py must create zero custom log files"); + assert.deepEqual(readdirSync(logDir), [], "The SDK backend must create zero custom log files"); } finally { await peer.closeAndKill(); } @@ -919,7 +926,7 @@ try { } }); - await check("toolchain_provider.py answers toolchains/query for conda, uv, pyenv, Poetry, Pipenv, .python-version, and pyproject.toml", async () => { + await check("The packaged provider answers toolchains/query for conda, uv, pyenv, Poetry, Pipenv, .python-version, and pyproject.toml", async () => { const fakeHome = join(scratch, "fake-home"); const condaEnvDir = join(scratch, "conda-envs", "ml-311"); const uvPyDir = join(scratch, "uv-pythons", "cpython-3.12.6-macos-aarch64-none"); @@ -963,23 +970,25 @@ try { ); writeFileSync(join(wsRoot, "Pipfile"), '[[source]]\nname = "pypi"\n'); - // Compute pipenv prefix via python helper to create matching WORKON_HOME env. - const pipenvName = run(pythonCmd, [ - "-I", - "-B", - "-c", - `import sys; sys.path.insert(0, ${JSON.stringify(join(unpackedPluginDir, "scripts"))}); from pathlib import Path; from toolchain_provider import _pipenv_virtualenv_prefix; print(_pipenv_virtualenv_prefix(Path(sys.argv[1]).resolve()))`, - wsRoot, - ]).trim(); + const workspaceDirectory = realpathSync.native(wsRoot); + const workspaceHash = (path) => createHash("sha256").update(path).digest("base64url").slice(0, 8); + const pipenvName = `${basename(workspaceDirectory)}-${workspaceHash(workspaceDirectory)}`; const pipenvDir = join(workonRoot, pipenvName); - makeFakePythonHome(pipenvDir, "3.12.3", false); + makeFakePythonHome(pipenvDir, "3.12.3"); + writeFileSync(join(wsRoot, "poetry.lock"), ""); + const poetryRoot = join(scratch, "poetry"); + const poetryProjectPath = process.platform === "win32" ? workspaceDirectory.toLowerCase() : workspaceDirectory; + const poetryDir = join(poetryRoot, `tc-demo-${workspaceHash(poetryProjectPath)}-py3.12`); + makeFakePythonHome(poetryDir, "3.12.1"); const discoveryEnv = { HOME: fakeHome, USERPROFILE: fakeHome, + PATH: "", UV_PYTHON_INSTALL_DIR: dirname(uvPyDir), PYENV_ROOT: join(scratch, "pyenv-root"), WORKON_HOME: workonRoot, + POETRY_VIRTUALENVS_PATH: poetryRoot, CONDA_ENVS_PATH: "", CONDA_PREFIX: "", }; @@ -988,7 +997,7 @@ try { const inherited = Object.fromEntries( Object.entries(process.env).filter(([key]) => !(key.toUpperCase() in discoveryEnv)), ); - const child = spawn(pythonCmd, ["-I", "-B", backendScript, "--state", join(scratch, "tc-state")], { + const child = spawn(backendExecutable, [], { cwd: scratch, env: { ...inherited, ...discoveryEnv }, stdio: ["pipe", "pipe", "pipe"], @@ -1011,21 +1020,24 @@ try { }); await peer.waitFor((m) => m.id === 1 && "result" in m, "toolchain backend init"); - peer.send({ - jsonrpc: "2.0", - id: 2, - method: "toolchains/query", - params: { - operationID: "tc-op-1", - generation: 3, - providerID: "python", - authority: { kind: "local" }, - tools: ["python"], - workspace: { rootID: "root-1", root: wsRoot, directory: "." }, - context: { contextID: "ctx-tc", generation: 1 }, - }, - }); - const reply = await peer.waitFor((m) => m.id === 2, "toolchains/query reply"); + async function queryProject(id, operationID) { + peer.send({ + jsonrpc: "2.0", + id, + method: "toolchains/query", + params: { + operationID, + generation: id + 1, + providerID: "python", + authority: { kind: "local" }, + tools: ["python"], + workspace: { rootID: "root-1", root: wsRoot, directory: "." }, + context: { contextID: "ctx-tc", generation: 1 }, + }, + }); + return peer.waitFor((m) => m.id === id, "toolchains/query reply"); + } + const reply = await queryProject(2, "tc-op-1"); assert.equal(reply.result.operationID, "tc-op-1"); assert.equal(reply.result.generation, 3); assert.equal(reply.result.providerID, "python"); @@ -1046,20 +1058,67 @@ try { assert.ok(homes.includes(expectedPath(uvPyDir)), "Expected UV_PYTHON_INSTALL_DIR installation"); assert.ok(homes.includes(expectedPath(pyenvVerDir)), "Expected PYENV_ROOT installation"); assert.ok(homes.includes(expectedPath(pipenvDir)), "Expected WORKON_HOME Pipenv installation"); + assert.ok(homes.includes(expectedPath(poetryDir)), "Expected configured Poetry installation"); + assert.ok(reply.result.watch.map(pathKey).includes(expectedPath(join(wsRoot, "poetry.lock")))); assert.equal(homes.includes(expectedPath(wsLocalVenv)), false, "Must NEVER return workspace-local .venv"); const bySource = new Map(reply.result.statements.map((statement) => [pathKey(statement.source), statement])); - const pyVerStmt = bySource.get(expectedPath(join(wsRoot, ".python-version"))); - assert.ok(pyVerStmt); - assert.equal(pathKey(pyVerStmt.installation), expectedPath(condaEnvDir)); - const pyprojStmt = bySource.get(expectedPath(join(wsRoot, "pyproject.toml"))); - assert.ok(pyprojStmt); - assert.equal(pathKey(pyprojStmt.installation), expectedPath(uvPyDir)); + const versionPath = join(wsRoot, ".python-version"); + const projectPath = join(wsRoot, "pyproject.toml"); + const declarations = (response) => response.result.statements.filter((statement) => statement.kind === "declaration"); + assert.equal( + declarations(reply).length, + 1, + "The provider must return one version declaration per directory to avoid a Core providerConflict", + ); + const [unmet] = declarations(reply); + assert.equal(pathKey(unmet.source), expectedPath(versionPath)); + assert.equal(unmet.request, "3.11"); + assert.equal(unmet.installation, null, "3.11 does not satisfy the project requirement"); + for (const watched of [versionPath, projectPath]) { + assert.ok(reply.result.watch.map(pathKey).includes(expectedPath(watched))); + } + + writeFileSync(versionPath, "3.12\n"); + const [compatible] = declarations(await queryProject(6, "tc-op-compatible")); + assert.equal(pathKey(compatible.source), expectedPath(versionPath)); + assert.equal(pathKey(compatible.installation), expectedPath(uvPyDir)); + + rmSync(versionPath); + const [projectOnly] = declarations(await queryProject(7, "tc-op-project-only")); + assert.equal(pathKey(projectOnly.source), expectedPath(projectPath)); + assert.equal(pathKey(projectOnly.installation), expectedPath(uvPyDir)); const pipfileStmt = bySource.get(expectedPath(join(wsRoot, "Pipfile"))); assert.ok(pipfileStmt); assert.equal(pipfileStmt.kind, "environment"); assert.equal(pathKey(pipfileStmt.installation), expectedPath(pipenvDir)); + const poetryStmt = bySource.get(expectedPath(join(wsRoot, "poetry.lock"))); + assert.ok(poetryStmt); + assert.equal(poetryStmt.kind, "environment"); + assert.equal(pathKey(poetryStmt.installation), expectedPath(poetryDir)); + + assert.equal(peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "tc-op-1"), false, + "A successful discovery must not emit an INFO terminal event"); + + peer.send({ + jsonrpc: "2.0", + id: 5, + method: "toolchains/query", + params: { + operationID: "tc-op-global", + generation: 4, + providerID: "python", + authority: { kind: "local" }, + tools: ["python"], + workspace: null, + context: null, + }, + }); + const global = await peer.waitFor((m) => m.id === 5, "global toolchain backend reply"); + assert.deepEqual(global.result.statements, []); + assert.ok(global.result.installations.some((entry) => pathKey(entry.home) === expectedPath(condaEnvDir))); + // Remote authority must return -32071 plugin.toolchain.authorityUnsupported. peer.send({ jsonrpc: "2.0", @@ -1069,7 +1128,7 @@ try { operationID: "tc-op-remote", generation: 4, providerID: "python", - authority: { kind: "remote", hostID: "ssh-box" }, + authority: { kind: "remote", id: "ssh-box" }, tools: ["python"], workspace: null, context: null, From f0d2e1d0bb32394053cb843c82a6fc89575ace86 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:35:52 +0800 Subject: [PATCH 2/6] release(python): prepare version 1.0.0 --- .github/workflows/release.yml | 86 +++++++++++++++++++---------------- docs/releases/v1.0.0.md | 21 +++++++++ 2 files changed, 69 insertions(+), 38 deletions(-) create mode 100644 docs/releases/v1.0.0.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0137be8..c9223c2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,76 +1,86 @@ name: Release # Push a tag v matching plugin.json to publish a GitHub Release. -# Lithe Store's tracker picks up stable releases and opens index pull requests. -# Tags listed in PRERELEASE_TAGS below are published as pre-releases, which the -# tracker skips until a compatible Lithe desktop release is out. +# Lithe Store automatically tracks stable releases of eligible plugins. on: push: tags: ["v*"] permissions: - contents: write + contents: read jobs: - release: + check: runs-on: ubuntu-latest - timeout-minutes: 15 + timeout-minutes: 5 + outputs: + exists: ${{ steps.release.outputs.exists }} steps: - - name: Check whether release already exists - id: check + - name: Check whether the release already exists + id: release env: GH_TOKEN: ${{ github.token }} run: | if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - echo "Release $GITHUB_REF_NAME already exists; skipping workflow build." echo "exists=true" >> "$GITHUB_OUTPUT" else echo "exists=false" >> "$GITHUB_OUTPUT" fi + + package: + needs: check + if: needs.check.outputs.exists == 'false' + uses: ./.github/workflows/package.yml + with: + tag: ${{ github.ref_name }} + + release: + needs: [check, package] + if: needs.check.outputs.exists == 'false' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write + steps: - uses: actions/checkout@v4 - if: steps.check.outputs.exists != 'true' - uses: actions/setup-node@v4 - if: steps.check.outputs.exists != 'true' with: node-version: 22 - - name: Build 6 platform archives - if: steps.check.outputs.exists != 'true' - run: | - set -o pipefail - node scripts/package.mjs --expect-tag "$GITHUB_REF_NAME" | tee "$RUNNER_TEMP/checksums.txt" - - name: Verify release archives - if: steps.check.outputs.exists != 'true' + - uses: actions/download-artifact@v4 + with: + pattern: python-support-archive-* + merge-multiple: true + path: dist + - name: Verify the six release archives + env: + LITHE_EXPECT_ALL_ARCHIVES: "1" run: node --test --test-timeout=60000 scripts/package/*.test.mjs - name: Publish GitHub Release - if: steps.check.outputs.exists != 'true' env: GH_TOKEN: ${{ github.token }} - PRERELEASE_TAGS: v0.1.0 v0.1.1 + # v1.0.0 requires a host that advertises toolchainProviders 0. + PRERELEASE_TAGS: v0.1.0 v0.1.1 v1.0.0 run: | - prerelease=false + release_flags=() + installation='Lithe Store 会在收录后提供此版本。打开 设置 → 插件 → 插件市场,搜索 Python Support。' for tag in $PRERELEASE_TAGS; do - if [[ "$tag" == "$GITHUB_REF_NAME" ]]; then prerelease=true; fi + if [[ "$tag" == "$GITHUB_REF_NAME" ]]; then + release_flags+=(--prerelease) + installation='下载对应平台的 ZIP。打开 设置 → 插件 → 从文件安装…,核对 SHA-256 后确认。' + break + fi done + notes="docs/releases/$GITHUB_REF_NAME.md" + test -s "$notes" { - echo "兼容性:按插件契约 v0(schemaVersion 0、pluginAPIVersion 0)构建,需要支持声明式插件契约 v0 与项目内工具环境(.venv)信任解析的新版 Lithe 桌面端(desktop-v* 预发布)。" + cat "$notes" echo - if [[ -s "docs/releases/$GITHUB_REF_NAME.md" ]]; then - cat "docs/releases/$GITHUB_REF_NAME.md" - echo - fi - if [[ "$prerelease" == true ]]; then - echo "安装:预发布版本,Lithe Store 自动追踪会跳过。下载对应平台的 ZIP,在 设置 → 插件 中点击 从文件安装…,选中 ZIP 后核对 SHA-256 并确认。" - else - echo "安装:Lithe Store(https://github.com/Lithe-IDEA/Lithe-store)收录后,可在 设置 → 插件 → 插件市场 中搜索 Python Support 并安装。" - fi + echo "$installation" + echo + echo 'SHA-256' echo - echo "SHA-256:" echo '```' - sed 's#^dist/##' "$RUNNER_TEMP/checksums.txt" + (cd dist && sha256sum ./*.zip) echo '```' } > "$RUNNER_TEMP/notes.md" - release_flags=() - if [[ "$prerelease" == true ]]; then - release_flags+=(--prerelease) - fi gh release create "$GITHUB_REF_NAME" dist/*.zip --title "Python Support $GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/notes.md" "${release_flags[@]}" diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md new file mode 100644 index 0000000..bacbf65 --- /dev/null +++ b/docs/releases/v1.0.0.md @@ -0,0 +1,21 @@ +## 中文 + +- Toolchains 可从 Conda 环境登记表、uv 自定义安装目录和其他受支持的环境位置发现 Python。项目的 `.python-version` 和 `requires-python` 参与解释器选择。 +- Pyrefly 与宿主选定的解释器保持一致。插件包内的后端可以在尚未安装 Python 时启动 Pyrefly。 +- Build 面板可用 pytest 收集测试,按已发现的套件和用例精确运行。运行 pytest 和 debugpy 仍需要可用的项目解释器。 + +### 升级与兼容性 + +升级需要支持 `toolchainProviders` 0 的 Lithe 桌面版。确认桌面已支持该能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 + +--- + +## English + +- Toolchains can find Python from the Conda environment registry, a custom uv installation directory, and other supported environment locations. The project's `.python-version` and `requires-python` help select an interpreter. +- Pyrefly uses the interpreter selected in Lithe. The bundled backend can start Pyrefly before Python is installed. +- The Build panel can collect tests with pytest and run an exact discovered suite or case. Running pytest and debugpy still requires an available project interpreter. + +### Upgrade and compatibility + +This upgrade requires a Lithe desktop version that supports `toolchainProviders` 0. Once your desktop version supports it, install the plugin ZIP for your operating system and architecture. Python Support v0.1.1 remains available for earlier versions of Lithe. From a2b160c9f6b5c47663bbd9225f55e8932af0f62d Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:38:42 +0800 Subject: [PATCH 3/6] fix(package): encode executable modes from bundle paths --- scripts/lib/archive.mjs | 6 ++++-- scripts/package.mjs | 2 +- scripts/package/archive-mode.test.mjs | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 scripts/package/archive-mode.test.mjs diff --git a/scripts/lib/archive.mjs b/scripts/lib/archive.mjs index 21f8abc..3af3585 100644 --- a/scripts/lib/archive.mjs +++ b/scripts/lib/archive.mjs @@ -185,7 +185,9 @@ export function extractWheelSubtree(wheelBuffer, packagePrefix, destParentDir) { } /** Writes a deterministic POSIX-compatible ZIP archive of `/`. */ -export function writeDeterministicZip(stageRoot, rootDirName, outputZipPath) { +export function writeDeterministicZip(stageRoot, rootDirName, outputZipPath, executablePaths) { + // Staging filesystem permissions cannot represent Unix execute bits on Windows. + const executables = new Set(executablePaths.map((path) => `${rootDirName}/${path}`)); const collected = []; function walk(absDir, relPosix) { @@ -201,7 +203,7 @@ export function writeDeterministicZip(stageRoot, rootDirName, outputZipPath) { if (stat.isDirectory()) { walk(absPath, rel); } else if (stat.isFile()) { - const executable = (stat.mode & 0o111) !== 0; + const executable = executables.has(rel); collected.push({ name: rel, data: readFileSync(absPath), diff --git a/scripts/package.mjs b/scripts/package.mjs index e133c9a..66cacf0 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -229,7 +229,7 @@ export async function packagePlatforms({ platforms, expectTag, cleanDist = false const relZipPath = `dist/${ASSET_PREFIX}-${baseManifest.version}-${platform}.zip`; const absZipPath = resolve(ROOT, relZipPath); rmSync(absZipPath, { force: true }); - writeDeterministicZip(stagePlatformRoot, PACKAGE_ID, absZipPath); + writeDeterministicZip(stagePlatformRoot, PACKAGE_ID, absZipPath, [pyreflySpec.packagePath, backendPath(platform)]); const sha256 = sha256File(absZipPath); built.push({ platform, relZipPath, absZipPath, sha256 }); diff --git a/scripts/package/archive-mode.test.mjs b/scripts/package/archive-mode.test.mjs new file mode 100644 index 0000000..5f63a4f --- /dev/null +++ b/scripts/package/archive-mode.test.mjs @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { readZipEntries, writeDeterministicZip } from "../lib/archive.mjs"; + +test("the archive declares executable files independently of staging permissions", (t) => { + const directory = mkdtempSync(join(tmpdir(), "python-archive-mode-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + mkdirSync(join(directory, "package", "bin"), { recursive: true }); + writeFileSync(join(directory, "package", "bin", "backend.exe"), "backend", { mode: 0o644 }); + writeFileSync(join(directory, "package", "metadata.json"), "{}", { mode: 0o755 }); + + const output = join(directory, "release.zip"); + writeDeterministicZip(directory, "package", output, ["bin/backend.exe"]); + const modes = readZipEntries(readFileSync(output)).map(({ name, unixMode }) => [name, unixMode]); + assert.deepEqual(modes, [ + ["package/bin/backend.exe", 0o100755], + ["package/metadata.json", 0o100644], + ]); +}); From 401bef49b8124d96510ad27542d38751787d54b7 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:48:47 +0800 Subject: [PATCH 4/6] test(python): use native paths in discovery fixture --- scripts/test.mjs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/scripts/test.mjs b/scripts/test.mjs index 192ab2d..851b761 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -286,7 +286,7 @@ async function check(name, body) { } } -const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-python-test-"))); +const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), "lithe-python-test-"))); let unpackedPluginDir = null; try { @@ -1042,16 +1042,19 @@ try { assert.equal(reply.result.generation, 3); assert.equal(reply.result.providerID, "python"); - // Python and Node may preserve different drive letter and directory - // casing for a real path on Windows. Compare native path identities. + // Rust and Node may preserve different drive letter and directory casing + // on Windows. Resolve candidate homes and statement sources separately. const pathKey = (path) => { const nativePath = normalize(path); return process.platform === "win32" ? nativePath.toLowerCase() : nativePath; }; const expectedPath = (path) => pathKey(realpathSync.native(path)); - assert.ok( - reply.result.watch.map(pathKey).includes(expectedPath(condaRegistry)), - "Expected toolchain discovery to read the fixture home", + const watch = reply.result.watch.map(pathKey); + // The registry watch uses the configured home path so it still works + // when conda has yet to create the registry file. + assert.deepEqual( + watch.filter((path) => basename(path) === "environments.txt"), + [pathKey(condaRegistry)], ); const homes = reply.result.installations.map((installation) => pathKey(installation.home)); assert.ok(homes.includes(expectedPath(condaEnvDir)), "Expected ~/.conda/environments.txt installation"); @@ -1059,7 +1062,7 @@ try { assert.ok(homes.includes(expectedPath(pyenvVerDir)), "Expected PYENV_ROOT installation"); assert.ok(homes.includes(expectedPath(pipenvDir)), "Expected WORKON_HOME Pipenv installation"); assert.ok(homes.includes(expectedPath(poetryDir)), "Expected configured Poetry installation"); - assert.ok(reply.result.watch.map(pathKey).includes(expectedPath(join(wsRoot, "poetry.lock")))); + assert.ok(watch.includes(expectedPath(join(wsRoot, "poetry.lock")))); assert.equal(homes.includes(expectedPath(wsLocalVenv)), false, "Must NEVER return workspace-local .venv"); const bySource = new Map(reply.result.statements.map((statement) => [pathKey(statement.source), statement])); @@ -1076,7 +1079,7 @@ try { assert.equal(unmet.request, "3.11"); assert.equal(unmet.installation, null, "3.11 does not satisfy the project requirement"); for (const watched of [versionPath, projectPath]) { - assert.ok(reply.result.watch.map(pathKey).includes(expectedPath(watched))); + assert.ok(watch.includes(expectedPath(watched))); } writeFileSync(versionPath, "3.12\n"); From 250383fc218acdc25ea70b19db0b3848e00697fe Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 15:30:15 +0800 Subject: [PATCH 5/6] feat(python): discover pytest cases with a build command --- .github/workflows/release.yml | 2 +- README.md | 14 +- docs/feature-matrix.md | 4 +- docs/releases/v1.0.0.md | 4 +- .../python_support_plugin_e2e_test.go | 73 ++++-- e2e/host/lithe-host.json | 2 +- .../plugin.json | 16 +- .../scripts/build_model.py | 12 + .../scripts/build_provider.py | 245 +----------------- .../scripts/discover_tests.py | 129 +++++++++ scripts/package/archives.test.mjs | 5 + scripts/test.mjs | 164 +++++++----- 12 files changed, 318 insertions(+), 352 deletions(-) create mode 100644 io.github.lithe-idea.python-support/scripts/discover_tests.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c9223c2..cb190bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -58,7 +58,7 @@ jobs: - name: Publish GitHub Release env: GH_TOKEN: ${{ github.token }} - # v1.0.0 requires a host that advertises toolchainProviders 0. + # v1.0.0 requires a host that advertises toolchainProviders 0 and buildSystems 1. PRERELEASE_TAGS: v0.1.0 v0.1.1 v1.0.0 run: | release_flags=() diff --git a/README.md b/README.md index ab15821..432c31d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Python Support for Lithe (`io.github.lithe-idea.python-support`) -Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, a packaged Rust backend for interpreter discovery and language-server startup, and a Python build provider for model, run, and pytest integration. +Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for static type checking and LSP navigation and [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging. A Rust backend discovers interpreters and starts the language server. The build integration uses a pytest discovery command and a Python provider for build models, run entries, and test execution. 遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。 @@ -19,10 +19,10 @@ Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。 - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。宿主观察这些输入并在变化后重新查询。 - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。 -4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)** - - `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载: +4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders`)** + - `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。 + - Python 构建提供者 `scripts/build_provider.py` 使用 `python -I -B` 启动,处理以下请求。 - `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置; - - `lithe/build/discoverTests`:运行可随 `$/cancelRequest` 整组终止的 `pytest --collect-only`,收集函数、类方法与参数化用例,按 Core 的条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0。缓存写入 `${workspaceStateDir}`。 - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。 - `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志; - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 @@ -53,7 +53,6 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` | | `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` | | `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` | -| `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出条数、大小或无法表示为有效选择器而省略的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` | | `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` | | `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` | | `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` | @@ -62,12 +61,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/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. 上游子进程通道、隐私红线与原生日志文件 @@ -76,7 +76,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | Rust 后端 / `build_provider.py` | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 | | `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 | | `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 | -| `pytest`、构建任务与项目生成 | 构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `lithe/build/discoverTests` 将 `pytest` 缓存重定向至 `${workspaceStateDir}`;进程 `stdout`、用户测试代码与环境变量值仅进入协议进度流或报告文件,绝不进入 v2 结构化诊断日志。 | +| `pytest`、构建任务与项目生成 | 测试发现报告(`${outputFile}`)、构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `pytest --collect-only` 的缓存与报告同目录,随宿主发现操作结束清理。宿主可向用户展示失败命令的部分输出。v2 结构化诊断只保存阶段类别和耗时。 | --- diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 663561b..e753d20 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -16,7 +16,7 @@ | 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 工具链与环境自动发现 (`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` | -| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `lithe/build/discoverTests` 通过有界可取消 `pytest --collect-only` 收集函数、测试类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,按条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0);`lithe/build/test` 支持精确 node ID 与 JUnit 类名重跑,单个用例须带套件、`lithe/build/progress` 流式输出及 `.pytest_cache/lithe-junit.xml` 解码;保留 `pip install -r requirements.txt` 与 `mypy` 任务 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `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` | +| 动态 `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-19(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-18`(`darwin-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` | | 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ 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` | @@ -26,6 +26,6 @@ ## 宿主版本与验证 -- 插件要求 `toolchainProviders: 0`。已发布的 Lithe 桌面 v0.8.6 无此能力,仅用于此前版本的回归。当前归档须在宣布该能力的兼容候选宿主上验收。 +- 插件要求宿主声明 `toolchainProviders: 0` 和 `buildSystems: 1`。旧版桌面用于此前插件版本的回归。当前归档须在同时声明这两项能力的候选宿主上验收。 - 候选宿主测试使用实际安装的插件、Conda 登记表和外部解释器副本,覆盖项目要求变更后切换解释器、全局候选、原生项目解释器信任及包文件哈希。 - 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md index bacbf65..86e76aa 100644 --- a/docs/releases/v1.0.0.md +++ b/docs/releases/v1.0.0.md @@ -6,7 +6,7 @@ ### 升级与兼容性 -升级需要支持 `toolchainProviders` 0 的 Lithe 桌面版。确认桌面已支持该能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 +升级需要支持 `toolchainProviders` 0 和 `buildSystems` 1 的 Lithe 桌面版。确认桌面已支持这两项能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 --- @@ -18,4 +18,4 @@ ### Upgrade and compatibility -This upgrade requires a Lithe desktop version that supports `toolchainProviders` 0. Once your desktop version supports it, install the plugin ZIP for your operating system and architecture. Python Support v0.1.1 remains available for earlier versions of Lithe. +This upgrade requires a Lithe desktop version that supports `toolchainProviders` 0 and `buildSystems` 1. Once your desktop version supports both capabilities, install the plugin ZIP for your operating system and architecture. Python Support v0.1.1 remains available for earlier versions of Lithe. diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go index cfcd37d..038d20a 100644 --- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go @@ -22,10 +22,12 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" @@ -491,15 +493,18 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { _ = dapCmd.Process.Kill() _ = dapCmd.Wait() - // 6. Detect all 4 build systems (conda, python, ruff, uv), start real build_provider.py, - // and verify lithe/build/model, lithe/build/discoverTests, and lithe/build/test + junitXml! + // 6. Detect all four build systems and exercise the Python model, discovery and test run. detection, err := kernel.DetectBuildSystems(ctx, workspace, []json.RawMessage{normalizedManifest}) if err != nil { t.Fatalf("DetectBuildSystems: %v", err) } var detectedIDs []string + var pythonInstance core.BuildInstance for _, inst := range detection.Instances { detectedIDs = append(detectedIDs, inst.BuildSystemID) + if inst.BuildSystemID == "python" { + pythonInstance = inst + } } slices.Sort(detectedIDs) if !slices.Equal(detectedIDs, []string{"conda", "python", "ruff", "uv"}) { @@ -569,32 +574,49 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("expected derived Run entries for ws-cli and main.py, got %+v", decodedModel.Run) } - // 6b. Provider lithe/build/discoverTests -> DecodeBuildTestDiscovery. - discPlan, err := kernel.PlanBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildPlanRequest{ - Root: ".", - WorkspaceRoot: workspace, - Tool: &pytestTool, - }) + // 6b. Run the installed plugin's discovery through the workbench command path. + entries, err := service.Manager.Installed() if err != nil { - t.Fatalf("PlanBuildTestDiscovery: %v", err) + t.Fatal(err) + } + buildPlugins, err := service.BuildPlugins(ctx, entries) + if err != nil || len(buildPlugins) != 1 || buildPlugins[0].PluginID != pythonSupportPluginID { + t.Fatalf("expected the installed Python build plugin: %+v (%v)", buildPlugins, err) + } + buildPlugin := buildPlugins[0] + instance := buildInstance{ + BuildInstance: pythonInstance, + PluginID: buildPlugin.PluginID, + Version: buildPlugin.Version, + Manifest: buildPlugin.Manifest, + PackageDirectory: buildPlugin.Directory, + System: buildPlugin.Systems["python"], } - if discPlan.Provider == nil || discPlan.Provider.Method != "lithe/build/discoverTests" { - t.Fatalf("expected provider testDiscoveryPlan, got %+v", discPlan) + if instance.System.Test == nil || !instance.System.Test.DiscoveryCommand { + t.Fatal("installed Python build system did not expose command discovery") } - discOp, err := providerClient.Execute(ctx, discPlan.Provider.Method, discPlan.Provider.Params, 45_000) + preferences := pluginsettings.New(kernel, appStore.Dir()) + settings, err := preferences.Load(ctx, instance.Manifest, workspace) if err != nil { - t.Fatalf("providerClient.Execute(lithe/build/discoverTests): %v", err) + t.Fatal(err) } - discRawResult, err := discOp.Wait(ctx) + pythonSetting, err := json.Marshal(pytestTool.Executable) if err != nil { - t.Fatalf("discOp.Wait: %v", err) + t.Fatal(err) } - decodedDiscovery, err := kernel.DecodeBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildDecodeTestDiscoveryRequest{ - Root: ".", - Result: discRawResult, - }) + if _, err := preferences.Save(ctx, settings, "global", []core.PluginSettingEdit{{ID: "pythonExecutable", Value: pythonSetting}}, nil); err != nil { + t.Fatalf("set the test interpreter: %v", err) + } + workbench := &App{kernel: kernel, plugins: service, store: appStore, text: i18n.For(i18n.English)} + discoveryOperation := core.NewOperation() + discoveryCtx := core.WithOrigin(ctx, core.Origin{Operation: discoveryOperation}) + decodedDiscovery, err := workbench.buildTestDiscovery(discoveryCtx, &project{root: workspace}, instance, kernel, false) if err != nil { - t.Fatalf("DecodeBuildTestDiscovery: %v", err) + t.Fatalf("workbench command discovery: %v", err) + } + discoveryFiles, err := os.ReadDir(buildStateDirectory(service.Root, workspace, instance)) + if err != nil || len(discoveryFiles) != 0 { + t.Fatalf("discovery left workspace state entries %v (%v)", discoveryFiles, err) } if len(decodedDiscovery.Tests) != 3 { t.Fatalf("discovered tests = %+v, want 3 items (test_alpha, test_scale[2-6], test_scale[4-12])", decodedDiscovery.Tests) @@ -668,8 +690,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("unexpected decoded JUnit XML results: %+v", decodedResults) } - // Verify Core validated and forwarded structured lithe/log events for both backend and build provider - // with zero plugins.diagnostics.rejected events! + // Verify plugin RPC diagnostics and the workbench's command terminal event. drained, err := kernel.DrainCoreEvents(ctx) if err != nil { t.Fatalf("DrainCoreEvents: %v", err) @@ -677,9 +698,13 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { logMu.Lock() captured := slices.Clone(recordedEvents) logMu.Unlock() + var discoveryTerminals []string for _, ev := range drained.Events { op, _ := ev.Fields["operation"].(string) captured = append(captured, fmt.Sprintf("%s:%s", ev.Event, op)) + if op == "lithe/build/discoverTests" && ev.Op == discoveryOperation { + discoveryTerminals = append(discoveryTerminals, ev.Event) + } if ev.Event == "plugins.diagnostics.rejected" { t.Fatalf("unexpected rejected plugin diagnostic from Core: %+v", ev) } @@ -692,8 +717,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if !slices.Contains(captured, "plugins.operation.finished:pyrefly.resolveLaunch") { t.Fatalf("expected plugins.operation.finished:pyrefly.resolveLaunch in Core log facts, got %v", captured) } - if !slices.Contains(captured, "plugins.operation.finished:lithe/build/discoverTests") { - t.Fatalf("expected plugins.operation.finished:lithe/build/discoverTests in Core log facts, got %v", captured) + if !slices.Equal(discoveryTerminals, []string{"plugins.operation.finished"}) { + t.Fatalf("expected one successful command discovery terminal, got %v (Core events %v)", discoveryTerminals, captured) } // 7. Verify Python Traceback outputLinkMatchers. diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index fbfce81..f44fd00 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/Mucheen/Lithe-IDEA.git", - "revision": "8b80afb5031f55daad5a769bca7126f9e632cf59", + "revision": "9fe390d08ccb16586294fbfb64a83964221093dd", "packages": { "./internal/projectgen": "^TestPythonPlugin", "./internal/workbench": "^TestPythonSupportPlugin" diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 334f564..535f78e 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -13,7 +13,7 @@ "requires": { "backend": 0, "buildProviders": 0, - "buildSystems": 0, + "buildSystems": 1, "debugAdapters": 0, "languageServers": 0, "languages": 0, @@ -503,7 +503,6 @@ "runtimeArguments": ["-I", "-B"], "entry": "scripts/build_provider.py" }, - "arguments": ["--cache", "${workspaceStateDir}"], "executesProjectCode": true, "mayUseNetwork": false }, @@ -639,7 +638,18 @@ "scopes": ["workspace", "project", "target"], "targetTags": ["test"], "filters": ["suite", "case"], - "discovery": true, + "discoveryCommand": { + "arguments": [ + "-I", + "-B", + "${pluginDir}/scripts/discover_tests.py", + "${outputFile}", + "${root}", + "${optionArguments}" + ], + "executesProjectCode": true, + "mayUseNetwork": false + }, "arguments": [], "results": { "decoder": "junitXml", diff --git a/io.github.lithe-idea.python-support/scripts/build_model.py b/io.github.lithe-idea.python-support/scripts/build_model.py index 418fa9e..98737c0 100644 --- a/io.github.lithe-idea.python-support/scripts/build_model.py +++ b/io.github.lithe-idea.python-support/scripts/build_model.py @@ -406,6 +406,18 @@ def _module_name_for_file(rel_posix: str, has_src_dir: bool): return ".".join(parts), app_dir +def project_name_for_dir(instance_dir: Path) -> str: + for filename, parse in ( + ("pyproject.toml", _parse_pyproject), + ("setup.cfg", _parse_setup_cfg), + ("setup.py", _parse_setup_py), + ): + name = parse(instance_dir / filename)["name"] + if name: + return name + return instance_dir.name or "python-project" + + def build_model_with_diagnostics(root_dir: Path) -> tuple[dict, list[str]]: root_real = root_dir.resolve() py_meta = _parse_pyproject(root_dir / "pyproject.toml") diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py index 8c78d4c..c8574d1 100644 --- a/io.github.lithe-idea.python-support/scripts/build_provider.py +++ b/io.github.lithe-idea.python-support/scripts/build_provider.py @@ -5,11 +5,7 @@ sys.dont_write_bytecode = True os.environ["PYTHONDONTWRITEBYTECODE"] = "1" -import argparse -import json from pathlib import Path -import shutil -import tempfile import threading from typing import Any, Optional from urllib.parse import unquote, urlparse @@ -20,120 +16,20 @@ sys.path.insert(0, _SCRIPTS_DIR) from build_model import ( # noqa: E402 - _parse_pyproject, - _parse_setup_cfg, - _parse_setup_py, _safe_within, build_model_with_diagnostics, inspect_file_entrypoints, + project_name_for_dir, ) from lithe_rpc import ( # noqa: E402 CallContext, JsonRpcServer, - MAX_BUILD_RESULT_BYTES, PluginError, run_bounded_process, ) -_MAX_DISCOVERED_TESTS = 10_000 -_MAX_TEST_SELECTOR_BYTES = 1024 _JUNIT_REPORT_REL = ".pytest_cache/lithe-junit.xml" -_PYTEST_COLLECTOR_SNIPPET = """ -import json, os, pathlib, sys -sys.dont_write_bytecode = True -os.environ["PYTHONDONTWRITEBYTECODE"] = "1" - -out_path = pathlib.Path(sys.argv[1]) -cache_dir = sys.argv[2] -project = json.loads(sys.argv[3]) -max_items, max_bytes, max_selector_bytes = map(int, sys.argv[4:7]) -extra_args = sys.argv[7:] - -try: - import pytest -except ModuleNotFoundError: - sys.exit(197) - -cwd_real = pathlib.Path.cwd().resolve() - -def valid_selector(text): - try: - return (text.strip() and not text.lstrip().startswith("-") - and len(text.encode("utf-8")) <= max_selector_bytes - and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text)) - except UnicodeEncodeError: - return False - -class _LitheTestCollector: - def __init__(self): - self.items = [] - self.omitted = 0 - - def pytest_collection_finish(self, session): - root_real = pathlib.Path(str(session.config.rootpath)).resolve() - # Reserve room for JSON keys, counters and the provider response envelope. - remaining_bytes = max_bytes - 128 - for item in session.items: - nodeid = getattr(item, "nodeid", "") - if not isinstance(nodeid, str) or not nodeid: - continue - if "::" in nodeid: - fpart, cpart = nodeid.split("::", 1) - else: - fpart, cpart = nodeid, getattr(item, "name", "") or nodeid - item_path = getattr(item, "path", None) - resolved_suite = None - if item_path is not None: - try: - resolved_suite = pathlib.Path(item_path).resolve().relative_to(cwd_real).as_posix() - except Exception: - resolved_suite = None - if resolved_suite is None: - try: - resolved_suite = (root_real / fpart).resolve().relative_to(cwd_real).as_posix() - except Exception: - resolved_suite = None - if ( - resolved_suite - and valid_selector(resolved_suite) - and valid_selector(cpart) - and ":" not in resolved_suite and "\\\\" not in resolved_suite - and all(seg not in ("", ".", "..") and not seg.startswith("-") for seg in resolved_suite.split("/")) - ): - if len(self.items) < max_items: - selector = {"suite": resolved_suite, "case": cpart, "project": project} - size = len(json.dumps(selector, ensure_ascii=False).encode("utf-8")) + 2 - if size <= remaining_bytes: - self.items.append(selector) - remaining_bytes -= size - continue - self.omitted += 1 - -args = [ - "--collect-only", - "-q", - "--color=no", - "-o", - "addopts=", - "-o", - f"cache_dir={cache_dir}", - *extra_args, -] -collector = _LitheTestCollector() -raw_code = pytest.main(args, plugins=[collector]) -try: - exit_code = int(raw_code) -except Exception: - exit_code = 1 -out_path.write_text( - json.dumps({"items": collector.items, "omitted": collector.omitted}, ensure_ascii=False), - encoding="utf-8", -) -sys.exit(exit_code) -""".strip() - - def file_uri_to_path(uri: str) -> Optional[Path]: parsed = urlparse(uri) if parsed.scheme != "file": @@ -208,19 +104,6 @@ def _verify_contained_path(instance_dir: Path, instance_real: Path, rel_posix: s return cur -def _project_name_for_dir(instance_dir: Path) -> str: - py_meta = _parse_pyproject(instance_dir / "pyproject.toml") - if py_meta.get("name"): - return py_meta["name"] - cfg_meta = _parse_setup_cfg(instance_dir / "setup.cfg") - if cfg_meta.get("name"): - return cfg_meta["name"] - setup_meta = _parse_setup_py(instance_dir / "setup.py") - if setup_meta.get("name"): - return setup_meta["name"] - return instance_dir.name or "python-project" - - def _resolve_pytest_selector_args( instance_dir: Path, suite: Any, @@ -294,16 +177,9 @@ def _resolve_pytest_selector_args( return [target_dir] if target_dir else [] -def create_build_provider_server(*, cache_dir: Optional[str] = None) -> JsonRpcServer: +def create_build_provider_server() -> JsonRpcServer: server = JsonRpcServer(name="python-build-provider", version="0.2.0") workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()} - owned_temp_dir: Optional[str] = None - if cache_dir: - cache_root = Path(cache_dir) - else: - owned_temp_dir = tempfile.mkdtemp(prefix="lithe-python-build-") - cache_root = Path(owned_temp_dir) - degraded_model_roots: set[str] = set() state_lock = threading.Lock() @@ -328,10 +204,6 @@ def _on_init(params: dict[str, Any]) -> None: if cand.is_dir(): workspace_root_holder["root"] = cand.resolve() - def _on_shutdown() -> None: - if owned_temp_dir and os.path.isdir(owned_temp_dir): - shutil.rmtree(owned_temp_dir, ignore_errors=True) - def _resolve_instance(params: dict[str, Any]) -> tuple[str, Path]: ws_root = workspace_root_holder["root"] norm_root = _normalize_rel_root(params.get("root")) @@ -387,105 +259,6 @@ def handle_model(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: ctx.diagnostics.recovered("lithe/build/model", "pyproject_restored", 1) return model - def handle_discover_tests(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: - ctx.raise_if_cancelled() - norm_root, instance_dir = _resolve_instance(params) - python_exec, child_env = _resolve_runtime_and_env(params) - project_selection = { - "name": _project_name_for_dir(instance_dir), - "path": norm_root, - } - - try: - cache_root.mkdir(parents=True, exist_ok=True) - pytest_cache_dir = cache_root / "pytest-collect-cache" - pytest_cache_dir.mkdir(parents=True, exist_ok=True) - except OSError as exc: - raise PluginError("python.cacheUnavailable", "Workspace state directory is not writable.") from exc - - timeout_ms = 45_000.0 - raw_env_timeout = os.environ.get("LITHE_PYTHON_DISCOVER_TIMEOUT_MS") - if raw_env_timeout: - try: - timeout_ms = max(200.0, float(raw_env_timeout)) - except ValueError: - pass - - option_args = _string_args(params.get("optionArguments")) - with tempfile.TemporaryDirectory(dir=str(cache_root), prefix="discover-") as run_tmp: - out_json_path = Path(run_tmp) / "collected.json" - argv = [ - python_exec, - "-B", - "-c", - _PYTEST_COLLECTOR_SNIPPET, - str(out_json_path), - str(pytest_cache_dir), - json.dumps(project_selection), - str(_MAX_DISCOVERED_TESTS), - str(MAX_BUILD_RESULT_BYTES), - str(_MAX_TEST_SELECTOR_BYTES), - *option_args, - ] - try: - exit_code, _output, timed_out = run_bounded_process( - argv, - cwd=str(instance_dir), - env=child_env, - cancel_token=ctx.cancel_token, - timeout_seconds=timeout_ms / 1000.0, - ) - except FileNotFoundError as exc: - raise PluginError( - "python.interpreterUnavailable", - "The selected Python interpreter could not be started.", - ) from exc - - if timed_out: - raise PluginError("python.pytestTimedOut", "pytest test discovery timed out.") - if exit_code == 197: - raise PluginError( - "python.pytestUnavailable", - "pytest is not installed in the selected Python environment.", - ) - if exit_code == 5: - return { - "format": "litheTestDiscovery", - "version": 0, - "tests": [], - } - if exit_code != 0 or not out_json_path.is_file(): - raise PluginError( - "python.pytestCollectionFailed", - "pytest failed to collect tests. Fix syntax or import errors and retry.", - ) - - try: - with out_json_path.open("rb") as collection: - data = collection.read(MAX_BUILD_RESULT_BYTES + 1) - if len(data) > MAX_BUILD_RESULT_BYTES: - raise ValueError("pytest collection report exceeds its byte budget") - payload = json.loads(data) - items = payload["items"] - omitted = payload["omitted"] - if (not isinstance(items, list) or len(items) > _MAX_DISCOVERED_TESTS - or type(omitted) is not int or omitted < 0): - raise ValueError("invalid pytest collection report") - except (OSError, ValueError, TypeError, KeyError) as exc: - raise PluginError( - "python.pytestCollectionFailed", - "pytest returned an unreadable test collection payload.", - ) from exc - - if omitted: - ctx.diagnostics.degraded("lithe/build/discoverTests", "test_discovery_truncated", omitted) - - return { - "format": "litheTestDiscovery", - "version": 0, - "tests": items, - } - def handle_test(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: ctx.raise_if_cancelled() _norm_root, instance_dir = _resolve_instance(params) @@ -587,7 +360,7 @@ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str if not rel_file or any(p in ("", ".", "..") for p in rel_file.split("/")): return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []} project_selection = { - "name": _project_name_for_dir(instance_dir), + "name": project_name_for_dir(instance_dir), "path": norm_root, } entrypoints = inspect_file_entrypoints(instance_dir, rel_file, project_selection) @@ -598,22 +371,12 @@ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str } server.on_initialize(_on_init) - server.on_shutdown(_on_shutdown) server.build_handler("lithe/build/model", handle_model) - server.build_handler("lithe/build/discoverTests", handle_discover_tests) server.build_handler("lithe/build/test", handle_test) server.build_handler("lithe/build/runEntrypoints", handle_run_entrypoints) server.suppress_success_diagnostics("lithe/build/runEntrypoints") return server -def main(argv: list[str]) -> int: - parser = argparse.ArgumentParser(add_help=False) - parser.add_argument("--cache", dest="cache_dir", default=None) - known, _ = parser.parse_known_args(argv[1:]) - server = create_build_provider_server(cache_dir=known.cache_dir) - return server.listen() - - if __name__ == "__main__": - raise SystemExit(main(sys.argv)) + raise SystemExit(create_build_provider_server().listen()) diff --git a/io.github.lithe-idea.python-support/scripts/discover_tests.py b/io.github.lithe-idea.python-support/scripts/discover_tests.py new file mode 100644 index 0000000..854b4d2 --- /dev/null +++ b/io.github.lithe-idea.python-support/scripts/discover_tests.py @@ -0,0 +1,129 @@ +"""Collect exact pytest selectors for the host-owned discovery report.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from build_model import project_name_for_dir # noqa: E402 + + +_DISCOVERY_TIMEOUT_SECONDS = 45 +_PYTEST_COLLECTOR = r""" +import json +from pathlib import Path +import sys + +try: + import pytest +except ModuleNotFoundError: + print("pytest --collect-only: pytest unavailable (ModuleNotFoundError)", file=sys.stderr) + sys.exit(197) + +MAX_TESTS = 10_000 +MAX_REPORT_BYTES = 32 * 1024 * 1024 +MAX_SELECTOR_BYTES = 1024 +HEADER = b'{"format":"litheTestDiscovery","version":0,"tests":[' +FOOTER = b"]}\n" + +output_file = Path(sys.argv[1]) +project = json.loads(sys.argv[2]) +cwd = Path.cwd().resolve() + + +def valid_selector(text): + if not isinstance(text, str): + return False + try: + return (text.strip() and not text.lstrip().startswith("-") + and len(text.encode("utf-8")) <= MAX_SELECTOR_BYTES + and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text)) + except UnicodeEncodeError: + return False + + +class Collector: + def __init__(self): + self.tests = None + + def pytest_collection_finish(self, session): + if len(session.items) > MAX_TESTS: + return + root = Path(session.config.rootpath).resolve() + tests = [] + remaining_bytes = MAX_REPORT_BYTES - len(HEADER) - len(FOOTER) + for item in session.items: + nodeid = getattr(item, "nodeid", "") + if not isinstance(nodeid, str) or not nodeid: + return + filename, separator, case = nodeid.partition("::") + if not separator: + case = getattr(item, "name", "") or nodeid + suite = None + for path in (getattr(item, "path", None), root / filename): + if path is not None: + try: + suite = Path(path).resolve().relative_to(cwd).as_posix() + break + except (OSError, RuntimeError, ValueError): + continue + if (not suite or not valid_selector(suite) or not valid_selector(case) + or ":" in suite or "\\" in suite + or any(seg in ("", ".", "..") or seg.startswith("-") for seg in suite.split("/"))): + return + selector = {"suite": suite, "case": case, "project": project} + encoded = json.dumps(selector, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + remaining_bytes -= len(encoded) + bool(tests) + if remaining_bytes < 0: + return + tests.append(encoded) + self.tests = tests + + +collector = Collector() +exit_code = pytest.main([ + "--collect-only", "-q", "--color=no", + "-o", "addopts=", "-o", f"cache_dir={output_file.with_name('pytest-cache')}", + *sys.argv[3:], +], plugins=[collector]) +if exit_code not in (pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED): + sys.exit(exit_code) +if collector.tests is None: + print("litheTestDiscovery: invalid or oversized test selectors", file=sys.stderr) + sys.exit(1) + +with output_file.open("xb") as report: + report.write(HEADER) + for index, item in enumerate(collector.tests): + if index: + report.write(b",") + report.write(item) + report.write(FOOTER) +""" + + +def main() -> int: + output_file, root, *options = sys.argv[1:] + project = {"name": project_name_for_dir(Path.cwd().resolve()), "path": root} + # The isolated entry point only imports bundled helpers. The pytest child + # inherits the selected Python's user site and project imports, like pytest + # execution, and stays in the host-owned process group or Windows job. + try: + child = subprocess.run( + [sys.executable, "-B", "-c", _PYTEST_COLLECTOR, output_file, json.dumps(project), *options], + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8"}, + check=False, + timeout=_DISCOVERY_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + print(f"pytest --collect-only: ETIMEDOUT ({_DISCOVERY_TIMEOUT_SECONDS}s)", file=sys.stderr) + return 124 + return child.returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index e3a84b1..27a3380 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -101,6 +101,7 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla `${PACKAGE_ID}/scripts/windows_job.py`, `${PACKAGE_ID}/scripts/build_model.py`, `${PACKAGE_ID}/scripts/build_provider.py`, + `${PACKAGE_ID}/scripts/discover_tests.py`, `${PACKAGE_ID}/scripts/debugpy_adapter.py`, `${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`, `${PACKAGE_ID}/vendor/debugpy/ThirdPartyNotices.txt`, @@ -123,6 +124,10 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla assert.deepEqual(manifest.backend, { launch: { kind: "packaged", path: backendPath(archive.platform) } }); assert.deepEqual(manifest.toolchainProviders, baseManifest.toolchainProviders); assert.equal(manifest.requires.toolchainProviders, 0); + assert.deepEqual( + manifest.buildSystems.find(({ id }) => id === "python").test, + baseManifest.buildSystems.find(({ id }) => id === "python").test, + ); const isWindows = archive.platform.startsWith("windows-"); const pyreflyServer = manifest.languageServers.find((s) => s.languageID === "python"); assert.deepEqual(pyreflyServer.launch, { diff --git a/scripts/test.mjs b/scripts/test.mjs index 851b761..37bd738 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -344,8 +344,8 @@ try { "toolDefinitions", "toolchainProviders", ]); - for (const ver of Object.values(variant.requires)) { - assert.equal(ver, 0); + for (const [capability, version] of Object.entries(variant.requires)) { + assert.equal(version, capability === "buildSystems" ? 1 : 0); } assert.deepEqual([...variant.permissions].sort(), [ "backend.launch", @@ -396,7 +396,12 @@ try { assert.equal(pyBuild.provider.mayUseNetwork, false); assert.deepEqual(pyBuild.model, { source: "provider" }); assert.equal(pyBuild.test.source, "provider"); - assert.equal(pyBuild.test.discovery, true); + assert.equal("discovery" in pyBuild.test, false); + assert.deepEqual(pyBuild.test.discoveryCommand, { + arguments: ["-I", "-B", "${pluginDir}/scripts/discover_tests.py", "${outputFile}", "${root}", "${optionArguments}"], + executesProjectCode: true, + mayUseNetwork: false, + }); assert.deepEqual(pyBuild.test.filters, ["suite", "case"]); assert.deepEqual(pyBuild.test.arguments, []); assert.deepEqual(pyBuild.test.results, { @@ -1150,7 +1155,7 @@ try { } }); - await check("build_provider.py executes model (with degraded/recovered), pytest --collect-only discovery, pytest JUnit XML test runs, runEntrypoints, and cancellation cleanup", async () => { + await check("The packaged discovery command collects pytest selectors and the provider runs them exactly, reports JUnit, and handles cancellation", async () => { const pytestExecutable = resolvePytestRuntime(); const noPytestExec = ensureNoPytestPython(scratch); @@ -1162,10 +1167,17 @@ try { // Start with an intentionally malformed pyproject.toml to verify degraded -> recovered! writeFileSync(join(wsDir, "pyproject.toml"), "[project\nname = 'broken'\n"); writeFileSync(join(wsDir, "worker.py"), 'if __name__ == "__main__":\n print("run worker")\n'); + writeFileSync(join(wsDir, "conftest.py"), [ + "def pytest_sessionstart(session):", + " if session.config.option.collectonly:", + " session.config.cache.set('lithe/discovery-test', True)", + "", + ].join("\n")); writeFileSync( join(wsDir, "tests", "test_calc.py"), [ "import pytest", + "import worker", "", "@pytest.mark.parametrize('x,expected', [(2, 6), (3, 9)])", "def test_scale(x, expected):", @@ -1177,7 +1189,26 @@ try { ].join("\n") + "\n", ); - const child = spawn(pythonCmd, ["-I", "-B", buildProviderScript, "--cache", cacheDir], { + const discoveryCommand = pluginManifest.buildSystems.find(({ id }) => id === "python").test.discoveryCommand; + assert.ok(discoveryCommand, "The installed plugin must declare a test discovery command"); + function discover(label, { cwd = wsDir, root = ".", executable = pytestExecutable, options = [] } = {}) { + const attemptDir = join(cacheDir, label); + mkdirSync(attemptDir); + const report = join(attemptDir, "tests.json"); + const args = discoveryCommand.arguments.flatMap((value) => value === "${optionArguments}" + ? options + : value.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", report).replace("${root}", root)); + const result = spawnSync(executable, args, { + cwd, + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + windowsHide: true, + }); + if (result.error) throw result.error; + return { ...result, report }; + } + + const child = spawn(pythonCmd, ["-I", "-B", buildProviderScript], { cwd: wsDir, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, @@ -1267,63 +1298,52 @@ try { "Expected recovered pyproject_restored log", ); - // 2. lithe/build/discoverTests via pytest --collect-only. - peer.send({ - jsonrpc: "2.0", - id: 4, - method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-1", - buildSystemID: "python", - root: ".", - tool: { executable: pytestExecutable }, - options: {}, - optionArguments: [], - environment: {}, - }, - }); - const discResp = await peer.waitFor((m) => m.id === 4, "discoverTests response"); - assert.equal(discResp.result.format, "litheTestDiscovery"); - assert.equal(discResp.result.version, 0); - assert.equal(existsSync(join(wsDir, ".pytest_cache")), false, "discoverTests must write cache to workspaceStateDir, not workspace"); + // 2. Run the packaged command with the host's output path and project cwd. + const discovered = discover("collected"); + assert.equal(discovered.status, 0, discovered.stdout + discovered.stderr); + const discovery = JSON.parse(readFileSync(discovered.report, "utf8")); + assert.equal(discovery.format, "litheTestDiscovery"); + assert.equal(discovery.version, 0); + assert.equal(existsSync(join(wsDir, ".pytest_cache")), false); + assert.equal(existsSync(join(dirname(discovered.report), "pytest-cache")), true); - const discoveredCases = discResp.result.tests.map((t) => `${t.suite}::${t.case}`).sort(); + const discoveredCases = discovery.tests.map((t) => `${t.suite}::${t.case}`).sort(); assert.deepEqual(discoveredCases, [ "tests/test_calc.py::TestCalc::test_add", "tests/test_calc.py::test_scale[2-6]", "tests/test_calc.py::test_scale[3-9]", ]); - for (const item of discResp.result.tests) { + for (const item of discovery.tests) { assert.deepEqual(item.project, { name: "calc-suite", path: "." }); } - // 3. Missing pytest returns controlled PluginError python.pytestUnavailable + operationFailed ERROR. - peer.send({ - jsonrpc: "2.0", - id: 5, - method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-missing", - buildSystemID: "python", - root: ".", - tool: { executable: noPytestExec }, - options: {}, - optionArguments: [], - environment: {}, - }, + // 3. Empty projects complete, while missing pytest and failed collection publish no report. + const missingPytest = discover("missing-pytest", { executable: noPytestExec }); + assert.equal(missingPytest.status, 197); + assert.match(missingPytest.stderr, /pytest unavailable/); + assert.equal(existsSync(missingPytest.report), false); + + const nested = join(wsDir, "nested project"); + mkdirSync(nested); + const empty = discover("empty", { cwd: nested, root: "nested project" }); + assert.equal(empty.status, 0, empty.stdout + empty.stderr); + assert.deepEqual(JSON.parse(readFileSync(empty.report, "utf8")), { + format: "litheTestDiscovery", version: 0, tests: [], }); - const missingPytest = await peer.waitFor((m) => m.id === 5, "missing pytest error"); - assert.equal(missingPytest.error?.code, -32000); - assert.equal(missingPytest.error?.data?.code, "python.pytestUnavailable"); - assert.ok( - peer.allReceived.some( - (m) => - m.method === "lithe/log" && - m.params?.operationId === "op-discover-missing" && - m.params?.kind === "operationFailed" && - m.params?.code === "python.pytestUnavailable", - ), - ); + writeFileSync(join(nested, "test_nested.py"), "def test_nested():\n assert True\n"); + const nestedDiscovery = discover("nested", { cwd: nested, root: "nested project" }); + assert.equal(nestedDiscovery.status, 0, nestedDiscovery.stdout + nestedDiscovery.stderr); + assert.deepEqual(JSON.parse(readFileSync(nestedDiscovery.report, "utf8")).tests, [{ + suite: "test_nested.py", case: "test_nested", project: { name: "nested project", path: "nested project" }, + }]); + rmSync(nested, { recursive: true }); + + const brokenTest = join(wsDir, "tests", "test_collection_error.py"); + writeFileSync(brokenTest, "def test_broken():\n assert (\n"); + const collectionError = discover("collection-error"); + assert.equal(collectionError.status, 2); + assert.equal(existsSync(collectionError.report), false); + rmSync(brokenTest); // 4. Execute a single discovered parameterized test via lithe/build/test and verify progress + JUnit XML. peer.send({ @@ -1359,11 +1379,15 @@ try { assert.match(junitXml, /test_scale\[2-6\]/); writeFileSync(join(wsDir, "tests", "test_names.py"), [ - "import pytest", "def test_add():", " assert True", "def test_additional():", " assert True", + "", + ].join("\n")); + const oversizedTest = join(wsDir, "tests", "test_long_id.py"); + writeFileSync(oversizedTest, [ + "import pytest", "@pytest.mark.parametrize('value', [pytest.param(1, id='é' * 600)])", "def test_long_id(value):", " assert value == 1", @@ -1382,22 +1406,19 @@ try { assert.equal(caseOnly.error?.data?.code, "python.invalidTestSelector"); assert.equal(readFileSync(junitXmlPath, "utf8"), junitXml); - peer.send({ - jsonrpc: "2.0", id: 69, method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-long-id", - buildSystemID: "python", root: ".", tool: { executable: pytestExecutable }, - options: {}, optionArguments: [], environment: {}, - }, - }); - const withLongId = await peer.waitFor((m) => m.id === 69, "discover with oversized UTF-8 test ID"); + const withLongId = discover("oversized-id"); + assert.notEqual(withLongId.status, 0); + assert.match(withLongId.stderr, /invalid or oversized test selectors/); + assert.equal(existsSync(withLongId.report), false, "An oversized UTF-8 ID must fail the whole discovery"); + rmSync(oversizedTest); + const withDoctest = discover("doctest", { options: ["--doctest-glob=test_notes.txt"] }); + assert.equal(withDoctest.status, 0, withDoctest.stdout + withDoctest.stderr); + const tests = JSON.parse(readFileSync(withDoctest.report, "utf8")).tests; assert.deepEqual( - withLongId.result.tests.filter(({ suite }) => suite === "tests/test_names.py").map(({ case: name }) => name).sort(), + tests.filter(({ suite }) => suite === "tests/test_names.py").map(({ case: name }) => name).sort(), ["test_add", "test_additional"], ); - assert.ok(peer.allReceived.some((m) => m.method === "lithe/log" - && m.params?.operationId === "op-discover-long-id" && m.params?.code === "test_discovery_truncated")); - const doctest = withLongId.result.tests.find(({ suite }) => suite === "test_notes.txt"); + const doctest = tests.find(({ suite }) => suite === "test_notes.txt"); assert.ok(doctest, "pytest must discover a root-level doctest"); peer.send({ jsonrpc: "2.0", id: 70, method: "lithe/build/test", @@ -1538,7 +1559,7 @@ try { ); // 6. $/cancelRequest terminates active pytest subprocess tree cleanly with zero orphan processes! - const pidFile = join(scratch, "slow-collect.pid"); + const pidFile = join(scratch, "slow-test.pid"); writeFileSync( join(wsDir, "tests", "test_blocking.py"), [ @@ -1553,12 +1574,13 @@ try { peer.send({ jsonrpc: "2.0", id: 8, - method: "lithe/build/discoverTests", + method: "lithe/build/test", params: { - operationID: "op-discover-cancel", + operationID: "op-test-cancel", buildSystemID: "python", root: ".", tool: { executable: pytestExecutable }, + suite: "tests/test_blocking.py", options: {}, optionArguments: [], environment: {}, @@ -1574,10 +1596,10 @@ try { assert.ok(Number.isInteger(childPid) && childPid > 0); peer.send({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: 8 } }); - const cancelResp = await peer.waitFor((m) => m.id === 8, "cancelled discoverTests response", 10_000); + const cancelResp = await peer.waitFor((m) => m.id === 8, "cancelled test response", 10_000); assert.equal(cancelResp.error?.code, -32800); assert.equal( - peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-discover-cancel"), + peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-test-cancel"), false, "Cancelled requests must NOT emit operationFinished or operationFailed logs", ); From 16231e14a814998373edaac6b191719eef89d667 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 22:49:56 +0800 Subject: [PATCH 6/6] Fix Pipenv project matching and refresh Python integration pins --- README.md | 2 +- backend/Cargo.lock | 2 +- backend/Cargo.toml | 2 +- backend/src/discovery/project.rs | 19 +++++++++++++---- docs/feature-matrix.md | 3 ++- .../python_support_plugin_e2e_test.go | 21 ++++++++++++------- scripts/test.mjs | 14 +++++++++++-- 7 files changed, 45 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 432c31d..6aee653 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: - 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。 3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchainProviders: 0`)** - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。 - - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。宿主观察这些输入并在变化后重新查询。 + - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。Pipenv 默认环境按完整的 `Pipfile` 路径匹配,并遵守同目录的 Python 版本约束。宿主观察这些输入并在变化后重新查询。 - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。 4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders`)** - `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。 diff --git a/backend/Cargo.lock b/backend/Cargo.lock index fee9c6e..d2b2e27 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -105,7 +105,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "lithe-plugin-sdk" version = "0.4.0" -source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust.git?rev=e56af624d3f615982f90c6249f7aa43c9b3b218e#e56af624d3f615982f90c6249f7aa43c9b3b218e" +source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust.git?rev=509c2beed1b23b4d3fd1d6649a4e252982e34db2#509c2beed1b23b4d3fd1d6649a4e252982e34db2" dependencies = [ "base64", "serde", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d8154f0..d8d00dc 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -9,7 +9,7 @@ publish = false [dependencies] base64 = "0.22" dunce = "1" -lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust.git", rev = "e56af624d3f615982f90c6249f7aa43c9b3b218e" } +lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust.git", rev = "509c2beed1b23b4d3fd1d6649a4e252982e34db2" } pep440_rs = "0.7" serde_json = "1" sha2 = "0.10" diff --git a/backend/src/discovery/project.rs b/backend/src/discovery/project.rs index c9aba9c..3faf324 100644 --- a/backend/src/discovery/project.rs +++ b/backend/src/discovery/project.rs @@ -147,9 +147,10 @@ fn project_file( } } if let Some(source) = source(&pipfile, root)? { - let name = pipenv_name(directory); + let name = pipenv_name(directory, &source); if let Some(home) = choose(snapshot, |candidate| { candidate.names.contains(std::ffi::OsStr::new(&name)) + && allows_version(&candidate.version) }) { statement( snapshot, @@ -226,10 +227,20 @@ fn statement( Ok(()) } -fn pipenv_name(directory: &Path) -> String { +fn pipenv_name(directory: &Path, pipfile: &Path) -> String { let name = directory.file_name().unwrap_or_default().to_string_lossy(); - let name: String = sanitize(&name).chars().take(42).collect(); - let hash = Sha256::digest(directory.to_string_lossy().as_bytes()); + let name: String = name + .replace( + [ + ' ', '&', '$', '`', '!', '*', '@', '"', '(', ')', '[', ']', '\\', '\r', '\n', '\t', + ], + "_", + ) + .chars() + .take(42) + .collect(); + // Pipenv hashes the full Pipfile path. Poetry hashes the project directory. + let hash = Sha256::digest(pipfile.to_string_lossy().as_bytes()); format!("{name}-{}", URL_SAFE_NO_PAD.encode(&hash[..6])) } diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index e753d20..c3faa81 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -22,10 +22,11 @@ | 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ 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` | | 新建项目向导 (`projectGenerators`) | `python-project`:选择并固定项目级 `python` 工具链(`pinAs: "project"`),可选 `none` / `venv (.venv)` / `uv (.venv)` 与示例代码生成(Windows 自动将 `python3` 命令切换为 `python`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(Windows 清单 `python` 命令切换已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/templates/python/`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/projectgen/python_integration_test.go` | | 国际化 (`l10n`) | 英文默认文案 + `l10n/zh-Hans.json` 简体中文完整设置与分组翻译 | ✅ 已验证 | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/l10n/zh-Hans.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 工具链提供者 (`litheToolchains` / `toolchains/query`) | 包内 Rust 后端在全局与项目上下文读取 Conda 登记、uv、pyenv、Poetry/Pipenv 环境以及项目版本声明。安装、要求与观察路径作为事实交回宿主验证。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/discovery.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 工具链提供者 (`litheToolchains` / `toolchains/query`) | 包内 Rust 后端在全局与项目上下文读取 Conda 登记、uv、pyenv、Poetry/Pipenv 环境以及项目版本声明。Pipenv 默认环境按完整的 `Pipfile` 路径识别,所选解释器须满足同目录的项目版本约束。安装、要求与观察路径作为事实交回宿主验证。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待宿主验收 | ⏳ 待宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/discovery.rs`
`backend/src/discovery/project.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | ## 宿主版本与验证 - 插件要求宿主声明 `toolchainProviders: 0` 和 `buildSystems: 1`。旧版桌面用于此前插件版本的回归。当前归档须在同时声明这两项能力的候选宿主上验收。 +- `e2e/host/lithe-host.json` 固定来自 Lithe 桌面 #2193 的兼容候选,包含已合入 #2192 的命令式测试发现。 - 候选宿主测试使用实际安装的插件、Conda 登记表和外部解释器副本,覆盖项目要求变更后切换解释器、全局候选、原生项目解释器信任及包文件哈希。 - 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go index 038d20a..cdc8783 100644 --- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go @@ -511,6 +511,9 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("detected build systems = %v, want [conda python ruff uv]", detectedIDs) } + // Run Build and pytest as a user who explicitly trusted this fixture. + buildProject := &project{root: workspace} + buildProject.trust.codeAllowed.Store(true) buildWsState := t.TempDir() providerClient, err := buildprovider.Start(ctx, service.Backend, pluginbackend.StartRequest{ Manifest: normalizedManifest, @@ -544,6 +547,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { WorkspaceStateDirectory: buildWsState, WorkspaceRoot: workspace, Tool: &pytestTool, + ProjectCodeAllowed: buildProject.trust.allowed(), }) if err != nil { t.Fatalf("PlanBuildModel: %v", err) @@ -610,7 +614,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { workbench := &App{kernel: kernel, plugins: service, store: appStore, text: i18n.For(i18n.English)} discoveryOperation := core.NewOperation() discoveryCtx := core.WithOrigin(ctx, core.Origin{Operation: discoveryOperation}) - decodedDiscovery, err := workbench.buildTestDiscovery(discoveryCtx, &project{root: workspace}, instance, kernel, false) + decodedDiscovery, err := workbench.buildTestDiscovery(discoveryCtx, buildProject, instance, kernel, false) if err != nil { t.Fatalf("workbench command discovery: %v", err) } @@ -634,13 +638,14 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { // 6c. Run that exact single discovered test via PlanBuildTest -> lithe/build/test -> DecodeBuildTestResults! testPlan, err := kernel.PlanBuildTest(ctx, normalizedManifest, "python", core.BuildTestRequest{ - Root: ".", - WorkspaceRoot: workspace, - Project: chosenTest.Project, - Target: chosenTest.Target, - Suite: chosenTest.Suite, - Case: chosenTest.Case, - Projects: []string{"."}, + Root: ".", + WorkspaceRoot: workspace, + Project: chosenTest.Project, + Target: chosenTest.Target, + Suite: chosenTest.Suite, + Case: chosenTest.Case, + Projects: []string{"."}, + ProjectCodeAllowed: buildProject.trust.allowed(), }) if err != nil { t.Fatalf("PlanBuildTest: %v", err) diff --git a/scripts/test.mjs b/scripts/test.mjs index 37bd738..eeec627 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -937,7 +937,7 @@ try { const uvPyDir = join(scratch, "uv-pythons", "cpython-3.12.6-macos-aarch64-none"); const pyenvVerDir = join(scratch, "pyenv-root", "versions", "3.10.14"); const workonRoot = join(scratch, "workon-envs"); - const wsRoot = join(scratch, "tc-workspace"); + const wsRoot = join(scratch, "tc-workspace (venv)"); mkdirSync(wsRoot, { recursive: true }); // Workspace-local .venv MUST be excluded from provider installations per toolchains contract! const wsLocalVenv = join(wsRoot, ".venv"); @@ -977,7 +977,8 @@ try { const workspaceDirectory = realpathSync.native(wsRoot); const workspaceHash = (path) => createHash("sha256").update(path).digest("base64url").slice(0, 8); - const pipenvName = `${basename(workspaceDirectory)}-${workspaceHash(workspaceDirectory)}`; + // Pipenv derives the default environment name from the full Pipfile path. + const pipenvName = `tc-workspace__venv_-${workspaceHash(join(workspaceDirectory, "Pipfile"))}`; const pipenvDir = join(workonRoot, pipenvName); makeFakePythonHome(pipenvDir, "3.12.3"); writeFileSync(join(wsRoot, "poetry.lock"), ""); @@ -1101,6 +1102,15 @@ try { assert.equal(pipfileStmt.kind, "environment"); assert.equal(pathKey(pipfileStmt.installation), expectedPath(pipenvDir)); + writeFileSync(projectPath, '[project]\nname = "tc-demo"\nrequires-python = ">=3.12.5"\n'); + const stricter = await queryProject(8, "tc-op-incompatible-pipenv"); + assert.equal( + stricter.result.statements.some((statement) => pathKey(statement.source) === expectedPath(join(wsRoot, "Pipfile"))), + false, + "A Pipenv environment outside requires-python must not override the compatible declaration", + ); + assert.equal(pathKey(declarations(stricter)[0].installation), expectedPath(uvPyDir)); + const poetryStmt = bySource.get(expectedPath(join(wsRoot, "poetry.lock"))); assert.ok(poetryStmt); assert.equal(poetryStmt.kind, "environment");