diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae36c7c..343d91f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,3 +89,31 @@ jobs: run: | python --version || python3 --version node scripts/test.mjs + + host-e2e: + needs: package + runs-on: macos-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/setup-go@v7 + with: + go-version: "1.27.3" + cache: false + - uses: dtolnay/rust-toolchain@1.100.0 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: actions/download-artifact@v4 + with: + name: python-support-archive-darwin-arm64 + path: dist + - name: Install pytest for the host suite + run: python -m pip install --disable-pip-version-check pytest + - name: Verify Python highlighting on Lithe 0.8.9 + run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPluginGrammarHighlighting$' + - name: Run the full Python host suite on the pinned desktop + run: PYTEST_PYTHON="$(command -v python)" node scripts/e2e-host.mjs diff --git a/README.md b/README.md index 6aee653..889ae20 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 1. **语言与编辑器基础(`languages: python`)** - 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。 + - Lithe 0.8.9 可以安装此插件。支持 TextMate 首行匹配的桌面版本还会按 shebang 识别无后缀脚本,提供 Python 高亮和 Pyrefly 诊断。 2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)** - 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。 - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。 @@ -90,6 +91,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | `backend/target/` | Rust 后端编译输出,包含按平台目标区分的产物 | 随工作树保留,可重新由 Cargo 生成 | 不共享,构建时由固定的 Cargo.lock 和 Rust 目标重建。Cargo 使用全局 registry 与 Git 依赖下载缓存。 | | `.artifacts/stage/` | 打包过程中的单平台解包暂存目录 | 每次 `scripts/package.mjs` 按平台重建(`.gitignore` 忽略) | **不可复用**(构建中间产物,毫秒级重建) | | `.artifacts/lithe-host/` | `scripts/e2e-host.mjs` 检出的宿主稀疏工作树及其编译产物 | 本地按需保留(`.gitignore` 忽略) | 其内部 `.artifacts/desktop` 在同一操作系统、CPU 架构与相同 `PINNED_CORE_REVISION` 前提下可按宿主规则复制加速,不得跨工作树软链共用;任何运行时会话日志目录(`sessions//plugins/.../files/`)与状态目录严禁跨工作树复制 | +| `grammars/python.first-line.json`(插件包内) | 插件的 TextMate 首行元数据。普通文件和按首行识别的脚本都沿用宿主的 `source.python` 高亮 | 构建时随 ZIP 打包,运行时只读,随插件版本更新或卸载 | 由插件源码随包生成,无运行时缓存 | | `dist/` | 最终产出的 `python-support--.zip` 发布包 | 打包输出(`.gitignore` 忽略) | 按需重新运行 `node scripts/package.mjs` 生成 | ### 常用命令 @@ -112,9 +114,12 @@ node --test --test-timeout=60000 scripts/package/*.test.mjs cargo test --locked --manifest-path backend/Cargo.toml node scripts/test.mjs -# 使用 e2e/host/lithe-host.json 固定的兼容桌面候选 +# 使用 e2e/host/lithe-host.json 固定的桌面主线提交运行完整宿主套件 node scripts/e2e-host.mjs +# 用同一个 ZIP 检查 0.8.9 能安装插件并正常高亮 .py +node scripts/e2e-host.mjs --source https://github.com/1lck/Lithe-IDEA.git --ref desktop-v0.8.9 --run '^TestPythonSupportPluginGrammarHighlighting$' + # 也可使用另一个兼容的本地检出和提交 node scripts/e2e-host.mjs --source /path/to/Lithe-IDEA --ref COMPATIBLE_HOST_COMMIT ``` diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index c3faa81..ab29eed 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -12,21 +12,24 @@ | 能力域 | 功能项 | `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`) | 包内 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` | +| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-20`(`darwin-arm64`,0.8.9 复验 `.py` 高亮) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` | +| 无后缀 Python 脚本 | 支持 TextMate 首行匹配的桌面按解释器路径或 `env` shebang 打开,提供 Python 高亮、注释与 Pyrefly 诊断 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | `2026-11-20`(`darwin-arm64`,桌面 `645a3aee8`) | `io.github.lithe-idea.python-support/grammars/python.first-line.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` | +| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | | 工具链与环境自动发现 (`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`) | `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` | +| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-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` | +| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | | 终端输出跳转 (`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 环境以及项目版本声明。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` | +| 工具链提供者 (`litheToolchains` / `toolchains/query`) | 包内 Rust 后端在全局与项目上下文读取 Conda 登记、uv、pyenv、Poetry/Pipenv 环境以及项目版本声明。Pipenv 默认环境按完整的 `Pipfile` 路径识别,所选解释器须满足同目录的项目版本约束。安装、要求与观察路径作为事实交回宿主验证。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待宿主验收 | ⏳ 待宿主验收 | 2026-11-20(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 登记表和外部解释器副本,覆盖项目要求变更后切换解释器、全局候选、原生项目解释器信任及包文件哈希。 +- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1` 和 `languages: 0`。桌面 0.8.9 支持安装与原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。 +- `e2e/host/lithe-host.json` 固定支持 TextMate 首行匹配的桌面主线提交 `645a3aee8`。 +- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮,并在固定的桌面主线上运行完整宿主套件,覆盖项目生成、解释器切换、pytest、debugpy、普通文件高亮和无后缀脚本的编辑诊断。 +- macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。 +- 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。 - 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md index 86e76aa..70672be 100644 --- a/docs/releases/v1.0.0.md +++ b/docs/releases/v1.0.0.md @@ -1,21 +1,23 @@ ## 中文 +- 支持 TextMate 首行匹配的 Lithe 可按 shebang 识别无后缀 Python 脚本,提供高亮、注释和 Pyrefly 诊断。 - Toolchains 可从 Conda 环境登记表、uv 自定义安装目录和其他受支持的环境位置发现 Python。项目的 `.python-version` 和 `requires-python` 参与解释器选择。 - Pyrefly 与宿主选定的解释器保持一致。插件包内的后端可以在尚未安装 Python 时启动 Pyrefly。 - Build 面板可用 pytest 收集测试,按已发现的套件和用例精确运行。运行 pytest 和 debugpy 仍需要可用的项目解释器。 ### 升级与兼容性 -升级需要支持 `toolchainProviders` 0 和 `buildSystems` 1 的 Lithe 桌面版。确认桌面已支持这两项能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 +Lithe 0.8.9 支持安装此插件并使用普通 Python 文件功能。无后缀脚本的自动识别需要支持 TextMate 首行匹配的桌面版本。请选择对应操作系统和架构的 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 --- ## English +- On Lithe versions that support TextMate first-line matching, open extensionless Python scripts with a shebang to get highlighting, comment commands, and Pyrefly diagnostics. - 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 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. +Lithe 0.8.9 can install this plugin and use its standard Python support. Automatic recognition of extensionless scripts requires a desktop version with TextMate first-line matching. Choose the 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_editor_debug_e2e_test.go b/e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go new file mode 100644 index 0000000..8bcb20e --- /dev/null +++ b/e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go @@ -0,0 +1,120 @@ +package workbench + +import ( + "context" + "maps" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// Drive the installed plugin through the window's normal Python editor and Debug paths. +// The debuggee records which interpreter actually ran it. The host has to discover +// the external environment selected by this project's .python-version. +func TestPythonSupportPluginEditorAndDebugger(t *testing.T) { + archive := pythonArchiveForE2E(t) + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + _, _, homes := registeredPythonEnvironments(t, ctx) + interpreterHome := homes[1] + preferences := store.At(t.TempDir()) + workspace, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, ".python-version"), []byte(filepath.Base(interpreterHome)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + // Only the selected interpreter contains this module. Its class name in a type + // error proves the language server actually consulted that environment. + interpreter := filepath.Join(interpreterHome, "bin", "python") + if runtime.GOOS == "windows" { + interpreter = filepath.Join(interpreterHome, "Scripts", "python.exe") + } + + createModule := `import pathlib, sysconfig +path = pathlib.Path(sysconfig.get_path("purelib")) / "lithe_test_environment.py" +path.write_text("class ProjectInterpreterType: pass\n", encoding="utf-8")` + if out, err := exec.CommandContext(ctx, interpreter, "-I", "-B", "-c", createModule).CombinedOutput(); err != nil { + t.Fatalf("create module in the selected environment: %v\n%s", err, out) + } + source := filepath.Join(workspace, "main.py") + code := `import sys +from pathlib import Path +from lithe_test_environment import ProjectInterpreterType + +value: int = ProjectInterpreterType() +Path('interpreter.txt').write_text(sys.prefix, encoding='utf-8') +` + if err := os.WriteFile(source, []byte(code), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(preferences.Dir(), settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + logDir := t.TempDir() + kernel := core.NewClient() + h := newHarnessWithOptions(t, Options{ + Kernel: kernel, PluginKernel: kernel, PluginRoot: filepath.Join(t.TempDir(), "Lithe Plugins"), Store: preferences, + Logs: &pluginFilesLog{directory: logDir}, LogKernel: kernel, Languages: []string{"en"}, + }) + installedDir := installPythonArchive(t, ctx, h.app.plugins, archive) + before := pythonPackageDigest(t, installedDir) + h.app.reloadPluginLanguages() + h.settle() + p := openDebugPanel(t, h, workspace) + h.app.openFileAt(p, source, 1) + awaitStateWithin(t, h, 30*time.Second, "Pyrefly to diagnose the open document", func() bool { + if failure := h.app.pluginServerFailed["python"]; failure != nil { + t.Fatalf("Pyrefly start: %s", failure.message) + } + return pythonDiagnosticMessage(h.app, source, "`ProjectInterpreterType` is not assignable to `int`") != "" + }) + t.Logf("Pyrefly reported %q for the open editor document", problemMessages(h.app)) + h.app.startDebug(p) + marker := filepath.Join(workspace, "interpreter.txt") + awaitStateWithin(t, h, 30*time.Second, "debugpy to run the program and finish the session", func() bool { + if p.debug.failure != "" { + t.Fatalf("debugpy: %s", p.debug.failure) + } + _, err := os.Stat(marker) + return err == nil && p.debug.activeSession() == nil + }) + actualPrefix, err := os.ReadFile(marker) + if err != nil { + t.Fatal(err) + } + actual, err := os.Stat(string(actualPrefix)) + if err != nil { + t.Fatal(err) + } + want, err := os.Stat(interpreterHome) + if err != nil || !os.SameFile(actual, want) { + t.Fatalf("debuggee used interpreter home %q, want %q (%v)", actualPrefix, interpreterHome, err) + } + entries, err := os.ReadDir(logDir) + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(entries, func(entry os.DirEntry) bool { + return strings.HasPrefix(entry.Name(), "debugpy.adapter-") && strings.HasSuffix(entry.Name(), ".log") + }) { + t.Fatal("debugpy did not write its adapter log to the host log directory") + } + t.Log("debugpy ran the program with the project-selected interpreter and wrote its adapter log to the host log directory") + h.app.closeProject() + awaitStateWithin(t, h, 20*time.Second, "the workspace to close", func() bool { return h.app.project == nil }) + h.settle() + h.app.plugins.Host.Stop(pythonSupportPluginID) + if !maps.Equal(before, pythonPackageDigest(t, installedDir)) { + t.Fatal("the editor and debugger changed the installed plugin files") + } +} diff --git a/e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go b/e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go new file mode 100644 index 0000000..3d1f788 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go @@ -0,0 +1,126 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" +) + +func openPythonGrammarWorkbench(t *testing.T) *harness { + t.Helper() + archive := pythonArchiveForE2E(t) + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + kernel := core.NewClient() + preferences := store.At(t.TempDir()) + service, err := pluginservice.Open(kernel, preferences, t.TempDir()) + if err != nil { + t.Fatal(err) + } + installPythonArchive(t, ctx, service, archive) + if err := os.WriteFile(filepath.Join(preferences.Dir(), settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + workspace, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + h := newHarnessWithOptions(t, Options{ + Kernel: kernel, PluginKernel: kernel, PluginRoot: service.Root, Store: preferences, Languages: []string{"en"}, + Logs: &pluginFilesLog{directory: t.TempDir()}, LogKernel: kernel, + }) + h.app.reloadPluginLanguages() + h.settle() + h.open(workspace) + return h +} + +func TestPythonSupportPluginGrammarHighlighting(t *testing.T) { + h := openPythonGrammarWorkbench(t) + p := h.app.project + path := filepath.Join(p.root, "sample.py") + const body = `class Counter: + def greet(self, name: str): + count = 42 + 1 + if count >= 1 and name: + return f"Hi {name.upper()}, {count + 1}" # hello + return None +` + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + grammar := h.app.syntaxRegistry().SyntaxForPath(path) + if grammar == nil || grammar.Language().Scope != "source.python" { + t.Fatal("installed plugin did not preserve the built-in Python grammar") + } + h.app.openFile(p, path) + h.settle() + doc := p.docs.byPath(path) + if doc == nil || doc.languageID != "python" { + t.Fatal("sample.py did not open as Python") + } + + bundled := syntax.NewRegistry().SyntaxForPath(path) + highlighter := syntax.NewHighlighter(bundled, rope.New([]byte(body)), syntax.HighlighterOptions{}) + t.Cleanup(highlighter.Close) + for lineIndex, line := range strings.Split(body, "\n") { + want := highlighter.Line(nil, lineIndex) + got := doc.view.SyntaxLine(nil, lineIndex) + if len(got) != len(want) { + t.Fatalf("line %d %q highlights = %v, bundled Python = %v", lineIndex+1, line, got, want) + } + for i, token := range got { + if token != want[i] { + t.Errorf("line %d %q token = %v, bundled Python = %v", lineIndex+1, line, token, want[i]) + } + } + } +} + +func TestPythonSupportPluginShebang(t *testing.T) { + h := openPythonGrammarWorkbench(t) + p := h.app.project + path := filepath.Join(p.root, "script") + const body = "#!/usr/bin/env -S /usr/bin/python3 -I\ncount: int = 42\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + h.app.openFile(p, path) + h.settle() + doc := p.docs.byPath(path) + if doc == nil || doc.languageID != "python" { + t.Fatal("extensionless script did not open as Python") + } + if len(doc.view.SyntaxLine(nil, 1)) == 0 { + t.Fatal("extensionless script has no Python syntax tokens") + } + awaitStateWithin(t, h, 15*time.Second, "Pyrefly to open the extensionless document", func() bool { + if failure := h.app.pluginServerFailed["python"]; failure != nil { + t.Fatalf("Pyrefly start: %s", failure.message) + } + return doc.sync.opened + }) + if !doc.view.GoToNavigation(1, 13, false) { + t.Fatal("could not place the caret before the integer literal") + } + input := doc.view.TextInput(app.TextInputContext{ID: doc.hit}) + if _, err := input.OnEvent(app.TextEvent{Kind: app.TextInsert, Text: `"bad" # `}); err != nil { + t.Fatal(err) + } + if !strings.Contains(doc.view.TextSnapshot().String(), `count: int = "bad" # 42`) { + t.Fatal("extensionless script edit was not applied") + } + awaitStateWithin(t, h, 15*time.Second, "Pyrefly to diagnose the edited extensionless script", func() bool { + return pythonDiagnosticMessage(h.app, path, "bad", "`int`") != "" + }) +} 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 cdc8783..5a21ec2 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 @@ -35,8 +35,20 @@ import ( const pythonSupportPluginID = "io.github.lithe-idea.python-support" -type workspaceTrustSaver interface { - SaveWorkspaceTrust(ctx context.Context, kernel toolchain.Kernel, trusted bool) (bool, error) +// Require all parts of the message on one diagnostic from this plugin and file. +func pythonDiagnosticMessage(a *App, path string, parts ...string) string { + set := a.pluginDiagnostics[pythonSupportPluginID] + if set == nil { + return "" + } + for _, record := range set.All() { + if record.FileKey == path && !slices.ContainsFunc(parts, func(part string) bool { + return !strings.Contains(record.Message, part) + }) { + return record.Message + } + } + return "" } func pythonPackageDigest(t *testing.T, root string) map[string]string { @@ -124,12 +136,10 @@ func resolvePytestToolForE2E(t *testing.T, ctx context.Context, systemPython str return core.BuildTool{Executable: executable} } -func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { - archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE") - if archive == "" { - t.Skip("set LITHE_TEST_PYTHON_PLUGIN_ARCHIVE to a python-support--.zip") - } - +// registeredPythonEnvironments creates isolated external interpreters listed in a +// temporary Conda registry. Both the provider and the workbench see that same home. +func registeredPythonEnvironments(t *testing.T, ctx context.Context) (systemPython, providerHome string, registeredHomes []string) { + t.Helper() pythonCmd := "python3" if runtime.GOOS == "windows" { pythonCmd = "python" @@ -142,10 +152,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { systemPython = resolvedSysPy } - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) - defer cancel() - - providerHome := t.TempDir() + providerHome = t.TempDir() if canonical, err := filepath.EvalSymlinks(providerHome); err == nil { providerHome = canonical } @@ -155,7 +162,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { 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{ + registeredHomes = []string{ filepath.Join(providerHome, "registered-python-one"), filepath.Join(providerHome, "registered-python-replacement"), } @@ -172,17 +179,21 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatal(err) } - kernel := core.NewClient() - appStore := store.At(t.TempDir()) - service, err := pluginservice.Open(kernel, appStore, filepath.Join(t.TempDir(), "Lithe Plugins")) - if err != nil { - t.Fatal(err) + return systemPython, providerHome, registeredHomes +} + +func pythonArchiveForE2E(t *testing.T) string { + t.Helper() + archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE") + if archive == "" { + t.Skip("set LITHE_TEST_PYTHON_PLUGIN_ARCHIVE to a python-support--.zip") } - t.Cleanup(func() { - service.Host.Stop(pythonSupportPluginID) - }) - // 1. Real installer Prepare + Commit + Enable. + return archive +} + +func installPythonArchive(t *testing.T, ctx context.Context, service *pluginservice.Service, archive string) string { + t.Helper() plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ ArchivePath: archive, Root: service.Root, @@ -204,8 +215,31 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("SetEnabled: %v", err) } - installedDir := installed.Path + return installed.Path +} + +func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { + archive := pythonArchiveForE2E(t) + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + + systemPython, providerHome, registeredHomes := registeredPythonEnvironments(t, ctx) + kernel := core.NewClient() + appStore := store.At(t.TempDir()) + service, err := pluginservice.Open(kernel, appStore, filepath.Join(t.TempDir(), "Lithe Plugins")) + if err != nil { + t.Fatal(err) + } + installedDir := installPythonArchive(t, ctx, service, archive) beforeDigest := pythonPackageDigest(t, installedDir) + // Runs after the build client and workspace have closed, including on failure. + t.Cleanup(func() { + service.Host.Stop(pythonSupportPluginID) + after := pythonPackageDigest(t, installedDir) + if !maps.Equal(beforeDigest, after) { + t.Errorf("installed package files or hashes changed (before %d, after %d)", len(beforeDigest), len(after)) + } + }) // 2. Validate BOTH Unix and Windows manifests against real Core + pluginhost.Declared(). rawManifest, err := os.ReadFile(filepath.Join(installedDir, "plugin.json")) @@ -373,7 +407,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("windows launch path = %q, want bin/pyrefly.exe", decodedWin.Launch.Path) } - // 5. Plan debug adapter (debugpy), verify launch/attach startArguments, and run DAP initialize smoke. + // 5. Verify debugpy launch and attach arguments against the host contract. dapPlan, err := kernel.PlanPluginDebugAdapter(ctx, normalizedManifest, "debugpy", core.PluginBackendDirectories{ PluginDirectory: installedDir, StateDirectory: stateDir, @@ -389,13 +423,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if _, err := pluginhost.ResolvePackagePaths(installedDir, dapPlan.RequiredPackagePaths); err != nil { t.Fatalf("ResolvePackagePaths(%v): %v", dapPlan.RequiredPackagePaths, err) } - entryScript := dapPlan.Launch.Entry - if !filepath.IsAbs(entryScript) { - entryScript, err = pluginhost.ResolvePackagePath(installedDir, entryScript) - if err != nil { - t.Fatalf("ResolvePackagePath(%s): %v", dapPlan.Launch.Entry, err) - } - } workspace := t.TempDir() if resolvedWs, evalErr := filepath.EvalSymlinks(workspace); evalErr == nil { @@ -465,34 +492,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("unexpected attach connection: %+v", attachStart.Connection) } - dapArgs := append([]string{}, dapPlan.Launch.RuntimeArguments...) - dapArgs = append(dapArgs, entryScript) - dapArgs = append(dapArgs, dapPlan.Arguments...) - dapCmd := exec.CommandContext(ctx, systemPython, dapArgs...) - dapCmd.Dir = workspace - dapIn, err := dapCmd.StdinPipe() - if err != nil { - t.Fatal(err) - } - dapOut, err := dapCmd.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err := dapCmd.Start(); err != nil { - t.Fatalf("starting debugpy adapter failed: %v", err) - } - initFrame := `{"seq":1,"type":"request","command":"initialize","arguments":{"adapterID":"debugpy"}}` - _, _ = io.WriteString(dapIn, "Content-Length: 85\r\n\r\n"+initFrame) - headerBuf := make([]byte, 18) - if _, err := io.ReadFull(dapOut, headerBuf); err != nil { - _ = dapCmd.Process.Kill() - _ = dapCmd.Wait() - t.Fatalf("debugpy adapter failed to emit DAP response header: %v", err) - } - _ = dapIn.Close() - _ = dapCmd.Process.Kill() - _ = dapCmd.Wait() - // 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 { @@ -750,12 +749,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { } // 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} @@ -766,7 +759,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatal(err) } snapshot, err := toolchain.Load(ctx, kernel, workspace, ".", manifestSet, - providerHost.ToolchainOptions(workspace, toolchain.Options{Home: providerHome, Environment: map[string]string{}})) + service.ToolchainOptions(workspace, toolchain.Options{Home: providerHome, Environment: map[string]string{}})) if err != nil { t.Fatalf("load provider toolchain: %v", err) } @@ -784,7 +777,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { } } global, err := toolchain.Load(ctx, kernel, "", ".", manifestSet, - providerHost.ToolchainOptions("", toolchain.Options{Global: true, Home: providerHome, Environment: map[string]string{}})) + service.ToolchainOptions("", toolchain.Options{Global: true, Home: providerHome, Environment: map[string]string{}})) if err != nil { t.Fatalf("load global provider toolchains: %v", err) } @@ -822,41 +815,30 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if err != nil { t.Fatalf("toolchain.Load(untrusted): %v", err) } - if saver, ok := any(untrustedSnap).(workspaceTrustSaver); ok { - for _, tool := range untrustedSnap.Tools { - if tool.ID == "python" && tool.Effective != nil && tool.Effective.Executable == expectedVenvPython { - t.Fatalf("untrusted workspace must NOT auto-select .venv interpreter %s", expectedVenvPython) - } - } - if _, err := saver.SaveWorkspaceTrust(ctx, kernel, true); err != nil { - t.Fatalf("SaveWorkspaceTrust(true): %v", err) - } - if _, statErr := os.Stat(filepath.Join(workspace, ".lithe")); !os.IsNotExist(statErr) { - t.Fatalf("workspace trust must NOT write .lithe inside workspace, statErr=%v", statErr) - } - trustedSnap, err := toolchain.Load(ctx, kernel, workspace, ".", []json.RawMessage{normalizedManifest}, toolchain.Options{ - GlobalRoot: globalRoot, - }) - if err != nil { - t.Fatalf("toolchain.Load(trusted): %v", err) - } - var resolvedExec string - for _, tool := range trustedSnap.Tools { - if tool.ID == "python" && tool.Effective != nil { - resolvedExec = tool.Effective.Executable - } + for _, tool := range untrustedSnap.Tools { + if tool.ID == "python" && tool.Effective != nil && tool.Effective.Executable == expectedVenvPython { + t.Fatalf("untrusted workspace must NOT auto-select .venv interpreter %s", expectedVenvPython) } - if resolvedExec != expectedVenvPython { - t.Fatalf("trusted .venv resolution = %q, want literal path %q", resolvedExec, expectedVenvPython) + } + if _, err := untrustedSnap.SaveWorkspaceTrust(ctx, kernel, true); err != nil { + t.Fatalf("SaveWorkspaceTrust(true): %v", err) + } + if _, statErr := os.Stat(filepath.Join(workspace, ".lithe")); !os.IsNotExist(statErr) { + t.Fatalf("workspace trust must NOT write .lithe inside workspace, statErr=%v", statErr) + } + trustedSnap, err := toolchain.Load(ctx, kernel, workspace, ".", []json.RawMessage{normalizedManifest}, toolchain.Options{ + GlobalRoot: globalRoot, + }) + if err != nil { + t.Fatalf("toolchain.Load(trusted): %v", err) + } + var resolvedExec string + for _, tool := range trustedSnap.Tools { + if tool.ID == "python" && tool.Effective != nil { + resolvedExec = tool.Effective.Executable } } - - // Shut down backend cleanly BEFORE checking package immutability so any shutdown write would be caught too! - service.Host.Stop(pythonSupportPluginID) - - // 9. Assert installed plugin package file list and SHA-256 hashes are 100% unchanged! - afterDigest := pythonPackageDigest(t, installedDir) - if !maps.Equal(beforeDigest, afterDigest) { - t.Fatalf("installed plugin package was mutated at runtime!\nbefore=%d files\nafter=%d files", len(beforeDigest), len(afterDigest)) + if resolvedExec != expectedVenvPython { + t.Fatalf("trusted .venv resolution = %q, want literal path %q", resolvedExec, expectedVenvPython) } } diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 0f63309..516e61c 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "46035f092ca31bb94b9463bf54385dca47d9ea98", + "revision": "645a3aee86e3ee5d6a308defa350678f8048baa8", "packages": { "./internal/projectgen": "^TestPythonPlugin", "./internal/workbench": "^TestPythonSupportPlugin" diff --git a/io.github.lithe-idea.python-support/grammars/python.first-line.json b/io.github.lithe-idea.python-support/grammars/python.first-line.json new file mode 100644 index 0000000..02f2a36 --- /dev/null +++ b/io.github.lithe-idea.python-support/grammars/python.first-line.json @@ -0,0 +1,3 @@ +{ + "firstLineMatch": "^#![ \\t]*/(?:[^ \\t]*/)?(?:env[ \\t]+(?:-S[ \\t]+)?(?:/(?:[^ \\t]*/)?)?)?(?:python(?:[0-9]+(?:\\.[0-9]+)*t?)?|pypy[0-9]*)(?:[ \\t]|$)" +} diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index 27a3380..7c8c70d 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -121,6 +121,20 @@ 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.equal(manifest.requires.languages, 0); + const pythonLanguage = manifest.languages.find(({ id }) => id === "python"); + assert.equal(pythonLanguage.grammar, undefined); + assert.equal("firstLineMatch" in pythonLanguage, false); + const metadataPath = `${PACKAGE_ID}/grammars/python.first-line.json`; + const metadataEntry = entries.find(({ name }) => name === metadataPath); + assert.ok(metadataEntry, `${archive.name}: missing ${metadataPath}`); + // Packaged JSON can have CRLF when a Windows runner assembles the ZIP. + assert.deepEqual( + JSON.parse(metadataEntry.data.toString("utf8")), + JSON.parse(readFileSync(metadataPath, "utf8")), + `${archive.name}: packaged metadata differs from ${metadataPath}`, + ); + assert.deepEqual(manifest.backend, { launch: { kind: "packaged", path: backendPath(archive.platform) } }); assert.deepEqual(manifest.toolchainProviders, baseManifest.toolchainProviders); assert.equal(manifest.requires.toolchainProviders, 0); diff --git a/scripts/test.mjs b/scripts/test.mjs index eeec627..ab5ee9e 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -310,6 +310,28 @@ try { const pluginManifest = JSON.parse(readFileSync(join(unpackedPluginDir, "plugin.json"), "utf8")); await check("Unix and Windows plugin.json + zh-Hans.json satisfy M3 contract invariants", () => { + const metadata = JSON.parse(readFileSync(join(unpackedPluginDir, "grammars", "python.first-line.json"), "utf8")); + assert.deepEqual(Object.keys(metadata), ["firstLineMatch"]); + const firstLine = new RegExp(metadata.firstLineMatch); + for (const line of [ + "#!/usr/bin/python", + "#!/usr/bin/env python3", + "#!/usr/bin/env -S python3.13 -I", + "#!/usr/bin/env -S /usr/bin/python3 -I", + "#!/opt/venv/bin/python3.13t", + "#!/usr/bin/env pypy3", + ]) { + assert.match(line, firstLine); + } + for (const line of [ + "#!/usr/bin/env bash", + "#!/usr/bin/env python-wrapper", + "#!/usr/bin/python3.13.exe", + "#!/usr/bin/env node python3", + "# Mention #!/usr/bin/env python3", + ]) { + assert.doesNotMatch(line, firstLine); + } for (const platform of Object.keys(lock.pyrefly.platforms)) { const variant = manifestForPlatform(sourceManifest, platform, lock); assert.equal(variant.schemaVersion, 0); @@ -362,7 +384,8 @@ try { }); const pyLang = variant.languages[0]; - assert.equal("shebang" in pyLang, false); + assert.equal(pyLang.grammar, undefined); + assert.equal("firstLineMatch" in pyLang, false); assert.deepEqual(pyLang.fileExtensions, ["py", "pyi", "pyw"]); assert.deepEqual(pyLang.dependencies.projectDependencyPaths, [".venv", "venv", ".conda"]);