Skip to content

Commit a8fbf9c

Browse files
committed
fix(python): 接通当前文件运行
1 parent 50daeb2 commit a8fbf9c

8 files changed

Lines changed: 227 additions & 9 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ jobs:
115115
path: dist
116116
- name: Install pytest for the host suite
117117
run: python -m pip install --disable-pip-version-check pytest
118-
- name: Verify Python highlighting on Lithe 0.8.9
119-
run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPluginGrammarHighlighting$'
118+
- name: Verify Python highlighting and current-file run on Lithe 0.8.9
119+
run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile)$'
120120
- name: Run the full Python host suite on the pinned desktop
121121
run: PYTEST_PYTHON="$(command -v python)" node scripts/e2e-host.mjs

‎README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the
2626
- 严格按 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/*`)。
2727
- Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。Pipenv 默认环境按完整的 `Pipfile` 路径匹配,并遵守同目录的 Python 版本约束。宿主观察这些输入并在变化后重新查询。
2828
- 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。
29-
4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders`)**
29+
4. **构建、运行与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders: 1`)**
3030
- `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。
3131
- Python 构建提供者 `scripts/build_provider.py` 使用 `python -I -B` 启动,处理以下请求。
3232
- `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` 配置;
3333
- `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
34-
- `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志;
34+
- 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划,由宿主用项目选定的 Python 运行。
3535
- 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
3636
- `uv`(`uv.lock`):`uv sync`、`uv lock`。
3737
- `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。
@@ -62,6 +62,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0
6262
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)<br>恢复:`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` |
6363
| `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` |
6464
| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
65+
| `lithe/build/prepareRun` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRunEntrypoint`、`python.staleRunEntrypoint`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
6566
| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
6667

6768
`toolchains/query` 是高频只读操作,成功由 SDK 返回事实。取消、读取失败、扫描超限与不安全输入通过 `plugin.toolchain.*` 结构化返回。宿主工具链层观察并处理查询及解码失败。协议 v0 的 SDK 无该操作的诊断回调。

‎docs/feature-matrix.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/pyrefly.rs`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`<br>`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` |
1818
| 工具链与环境自动发现 (`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`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
1919
| 构建模型与运行 (`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`<br>`io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
20+
| 当前文件运行 (`buildProviders: 1`) | 顶部工具栏运行带 `__main__` 入口的脚本或包内 `__main__.py`。提供者静态发现并复验入口,宿主用项目所选 Python 启动。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` |
2021
| 动态 `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`<br>`io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
2122
| 独立工具构建系统 (`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`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
2223
| 调试器 (`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`<br>`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`<br>`vendor-lock.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`<br>`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` |
@@ -27,9 +28,9 @@
2728

2829
## 宿主版本与验证
2930

30-
- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1` 和 `languages: 0`。桌面 0.8.9 支持安装与原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。
31+
- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。
3132
- `e2e/host/lithe-host.json` 固定支持 TextMate 首行匹配的桌面主线提交 `645a3aee8`。
32-
- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮,并在固定的桌面主线上运行完整宿主套件,覆盖项目生成、解释器切换、pytest、debugpy、普通文件高亮和无后缀脚本的编辑诊断。
33+
- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮和当前文件运行,并在固定的桌面主线上运行完整宿主套件,额外覆盖项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。
3334
- macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。
3435
- 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。
3536
- 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package workbench
2+
3+
import (
4+
"context"
5+
"os"
6+
"os/exec"
7+
"path/filepath"
8+
"runtime"
9+
"strings"
10+
"testing"
11+
"time"
12+
13+
"github.com/1lck/Lithe-IDEA/desktop/internal/core"
14+
"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
15+
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
16+
"github.com/1lck/Lithe-IDEA/desktop/internal/toolchain"
17+
)
18+
19+
func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
20+
archive := pythonArchiveForE2E(t)
21+
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
22+
defer cancel()
23+
root, err := filepath.EvalSymlinks(t.TempDir())
24+
if err != nil {
25+
t.Fatal(err)
26+
}
27+
venv := filepath.Join(root, ".venv")
28+
python := "python3"
29+
if runtime.GOOS == "windows" {
30+
python = "python"
31+
}
32+
if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", venv).CombinedOutput(); err != nil {
33+
t.Fatalf("create project environment: %v\n%s", err, output)
34+
}
35+
source := filepath.Join(root, "main.py")
36+
for name, contents := range map[string]string{
37+
"pyproject.toml": "[project]\nname = 'current-file-run'\nversion = '0.1.0'\n",
38+
"main.py": "import sys\n\nif __name__ == '__main__':\n print('current file ran')\n print(sys.prefix)\n",
39+
} {
40+
if err := os.WriteFile(filepath.Join(root, name), []byte(contents), 0o600); err != nil {
41+
t.Fatal(err)
42+
}
43+
}
44+
kernel := core.NewClient()
45+
preferences := store.At(t.TempDir())
46+
// The toolchain resolver reads persisted trust before probing a project .venv.
47+
trust, err := toolchain.ReadWorkspaceTrust(ctx, kernel, preferences.Dir(), root)
48+
if err != nil {
49+
t.Fatal(err)
50+
}
51+
if _, err := trust.Save(ctx, kernel, true, false); err != nil {
52+
t.Fatal(err)
53+
}
54+
h := newHarnessWithOptions(t, Options{
55+
Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences,
56+
Languages: []string{"en"},
57+
})
58+
installPythonArchive(t, ctx, h.app.plugins, archive)
59+
h.app.reloadPluginLanguages()
60+
h.open(root)
61+
p := h.app.project
62+
if p == nil {
63+
t.Fatal("the workspace did not open")
64+
}
65+
openSource(t, h, p, source)
66+
h.app.post(func(a *App) {
67+
a.chooseTitleConfiguration(p, "")
68+
a.titleRun(p)
69+
})
70+
notRunnable := i18n.Shared(h.app.language(), "desktop.title.currentFileNotRunnable")
71+
awaitStateWithin(t, h, 20*time.Second, "the current file to start running", func() bool {
72+
for _, notice := range noticeTexts(h.app) {
73+
if notice == notRunnable {
74+
t.Fatalf("the toolbar rejected the Python entrypoint: %s", notice)
75+
}
76+
}
77+
return p.runConfigs.selected != ""
78+
})
79+
run := awaitProcessRun(t, h, p, "main.py", nil)
80+
checkOutput := func(output string) {
81+
t.Helper()
82+
if !strings.Contains(output, "current file ran") || !strings.Contains(output, venv) {
83+
t.Fatalf("expected the program to run using the project's environment %q:\n%s", venv, output)
84+
}
85+
}
86+
checkOutput(run.output.all())
87+
saved := p.runConfigs.configuration(p.runConfigs.selected)
88+
if saved == nil {
89+
t.Fatal("the toolbar did not select the saved run configuration")
90+
}
91+
if ref, ok := saved.BuildReference(); !ok || ref.Run != "main" || ref.TargetID != "" {
92+
t.Fatalf("current file saved the wrong build reference: %+v", ref)
93+
}
94+
95+
for i := range p.build.instances {
96+
instance := &p.build.instances[i]
97+
if instance.BuildSystemID != "python" {
98+
continue
99+
}
100+
for _, target := range instance.Model.Targets {
101+
if target.Name == "main.py" {
102+
action, ok := buildPrimaryAction(instance, &target)
103+
if !ok || action.entryID == "" {
104+
t.Fatal("main.py no longer has a command run in the Build panel")
105+
}
106+
h.app.post(func(a *App) {
107+
a.selectBuildInstance(p, i)
108+
a.runBuildTargetAction(p, target.ID, action)
109+
})
110+
checkOutput(awaitProcessRun(t, h, p, "main.py", run).output.all())
111+
return
112+
}
113+
}
114+
}
115+
t.Fatal("the build model no longer exposes the main.py target")
116+
}

‎io.github.lithe-idea.python-support/plugin.json‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"pluginAPIVersion": 0,
1313
"requires": {
1414
"backend": 0,
15-
"buildProviders": 0,
15+
"buildProviders": 1,
1616
"buildSystems": 1,
1717
"debugAdapters": 0,
1818
"languageServers": 0,
@@ -543,6 +543,11 @@
543543
}
544544
],
545545
"run": [
546+
{
547+
"id": "main",
548+
"source": "provider",
549+
"entrypoints": true
550+
},
546551
{
547552
"id": "script",
548553
"fromTargets": { "tags": ["script"] },

‎io.github.lithe-idea.python-support/scripts/build_model.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -673,7 +673,8 @@ def inspect_file_entrypoints(root_dir: Path, rel_file_posix: str, project_select
673673
results.append({
674674
"run": "main",
675675
"name": mod_name,
676-
"entrypoint": f"module:{mod_name}",
676+
# Keep the source path so preparation can distinguish root and src layouts.
677+
"entrypoint": f"module:{clean_rel}",
677678
"project": project_selection,
678679
})
679680
return results

0 commit comments

Comments
 (0)