Skip to content

Commit 6936b36

Browse files
committed
fix(python): 修复当前文件运行的解释器与包入口
1 parent a8fbf9c commit 6936b36

9 files changed

Lines changed: 193 additions & 26 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,6 @@ jobs:
116116
- name: Install pytest for the host suite
117117
run: python -m pip install --disable-pip-version-check pytest
118118
- 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)$'
119+
run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride)?)$'
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
@@ -31,7 +31,8 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the
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-
- 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划,由宿主用项目选定的 Python 运行。
34+
- 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划。默认使用项目选定的 Python;指定「Python 解释器覆盖」时,使用宿主解析的显式解释器。
35+
- `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。
3536
- 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
3637
- `uv`(`uv.lock`):`uv sync`、`uv lock`。
3738
- `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。
@@ -62,7 +63,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0
6263
| `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` |
6364
| `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` |
6465
| `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` |
66+
| `lithe/build/prepareRun` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRunEntrypoint`、`python.staleRunEntrypoint`、`python.interpreterUnavailable`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
6667
| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
6768

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

‎docs/feature-matrix.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +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` |
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>`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` |
2121
| 动态 `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` |
2222
| 独立工具构建系统 (`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` |
2323
| 调试器 (`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` |

‎e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package workbench
22

33
import (
44
"context"
5+
"encoding/json"
56
"os"
67
"os/exec"
78
"path/filepath"
@@ -17,6 +18,15 @@ import (
1718
)
1819

1920
func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
21+
checkPythonCurrentFileRun(t, false)
22+
}
23+
24+
func TestPythonSupportPluginRunCurrentFileInterpreterOverride(t *testing.T) {
25+
checkPythonCurrentFileRun(t, true)
26+
}
27+
28+
func checkPythonCurrentFileRun(t *testing.T, override bool) {
29+
t.Helper()
2030
archive := pythonArchiveForE2E(t)
2131
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
2232
defer cancel()
@@ -51,6 +61,30 @@ func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
5161
if _, err := trust.Save(ctx, kernel, true, false); err != nil {
5262
t.Fatal(err)
5363
}
64+
wantVenv := venv
65+
if override {
66+
overrideDir, err := filepath.EvalSymlinks(t.TempDir())
67+
if err != nil {
68+
t.Fatal(err)
69+
}
70+
wantVenv = filepath.Join(overrideDir, "configured interpreter")
71+
if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", wantVenv).CombinedOutput(); err != nil {
72+
t.Fatalf("create configured environment: %v\n%s", err, output)
73+
}
74+
configured := filepath.Join(wantVenv, "bin", "python")
75+
if runtime.GOOS == "windows" {
76+
configured = filepath.Join(wantVenv, "Scripts", "python.exe")
77+
}
78+
settings, err := json.Marshal(map[string]map[string]string{
79+
pythonSupportPluginID: {"pythonExecutable": configured},
80+
})
81+
if err != nil {
82+
t.Fatal(err)
83+
}
84+
if err := os.WriteFile(filepath.Join(preferences.Dir(), "plugin-settings.json"), settings, 0o600); err != nil {
85+
t.Fatal(err)
86+
}
87+
}
5488
h := newHarnessWithOptions(t, Options{
5589
Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences,
5690
Languages: []string{"en"},
@@ -79,8 +113,8 @@ func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
79113
run := awaitProcessRun(t, h, p, "main.py", nil)
80114
checkOutput := func(output string) {
81115
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)
116+
if !strings.Contains(output, "current file ran") || !strings.Contains(output, wantVenv) {
117+
t.Fatalf("expected the program to use Python environment %q:\n%s", wantVenv, output)
84118
}
85119
}
86120
checkOutput(run.output.all())

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,7 @@
503503
"runtimeArguments": ["-I", "-B"],
504504
"entry": "scripts/build_provider.py"
505505
},
506+
"initializationOptions": { "pythonExecutable": "${setting:pythonExecutable}" },
506507
"executesProjectCode": true,
507508
"mayUseNetwork": false
508509
},

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

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,10 @@
2727
PluginError,
2828
run_bounded_process,
2929
)
30+
from run_entrypoint import run_message # noqa: E402
3031

3132
_JUNIT_REPORT_REL = ".pytest_cache/lithe-junit.xml"
32-
_RUN_MODULE = (
33-
"import runpy, sys; sys.path.insert(0, sys.argv.pop(1)); "
34-
"runpy.run_module(sys.argv.pop(1), run_name='__main__', alter_sys=True)"
35-
)
33+
_ENTRYPOINT_LAUNCHER = str(Path(_SCRIPTS_DIR) / "run_entrypoint.py")
3634

3735
def file_uri_to_path(uri: str) -> Optional[Path]:
3836
parsed = urlparse(uri)
@@ -186,8 +184,16 @@ def create_build_provider_server() -> JsonRpcServer:
186184
workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()}
187185
degraded_model_roots: set[str] = set()
188186
state_lock = threading.Lock()
187+
configured_interpreter = False
188+
locale = ""
189189

190190
def _on_init(params: dict[str, Any]) -> None:
191+
nonlocal configured_interpreter, locale
192+
initialization = params.get("initializationOptions")
193+
if isinstance(initialization, dict):
194+
configured_interpreter = bool(initialization.get("pythonExecutable"))
195+
if isinstance(params.get("locale"), str):
196+
locale = params["locale"]
191197
folders = params.get("workspaceFolders")
192198
if isinstance(folders, list) and folders:
193199
first = folders[0]
@@ -382,41 +388,49 @@ def handle_prepare_run(params: dict[str, Any], ctx: CallContext) -> dict[str, An
382388
if (params.get("run") != "main" or params.get("target") is not None
383389
or not isinstance(project, dict) or project.get("path") != norm_root
384390
or not isinstance(launch, dict)):
385-
raise PluginError("python.invalidRunEntrypoint", "Run this file from its Python project.")
391+
raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
386392

387393
entrypoint = launch.get("entrypoint")
388394
if not isinstance(entrypoint, str):
389-
raise PluginError("python.invalidRunEntrypoint", "Select a Python file to run.")
395+
raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
390396
kind, _, relative_file = entrypoint.partition(":")
391397
if (kind not in ("script", "module") or relative_file.startswith("/")
392398
or any(char in relative_file for char in ("\\", ":", "\x00"))):
393-
raise PluginError("python.invalidRunEntrypoint", "Select a Python file inside the project.")
399+
raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
394400

395401
# Saved configurations can outlive their source or its main guard.
396402
entries = inspect_file_entrypoints(instance_dir, relative_file, project)
397403
if not entries or entries[0]["entrypoint"] != entrypoint:
398-
raise PluginError("python.staleRunEntrypoint", "The saved Python entry point is unavailable. Open a runnable Python file and run it again.")
404+
raise PluginError("python.staleRunEntrypoint", run_message("stale", locale))
399405

400406
working_directory = launch.get("workingDirectory") or norm_root
407+
source = str(instance_dir / relative_file)
401408
if kind == "script":
402-
program = [str(instance_dir / relative_file)]
403-
elif relative_file.startswith("src/") or working_directory != norm_root:
404-
# Keep module imports rooted in the build instance even when using a custom cwd.
405-
module_root = instance_dir / "src" if relative_file.startswith("src/") else instance_dir
406-
program = ["-c", _RUN_MODULE, str(module_root), entries[0]["name"]]
409+
program = [source]
407410
else:
408-
program = ["-m", entries[0]["name"]]
411+
module_root = instance_dir / "src" if relative_file.startswith("src/") else instance_dir
412+
program = [_ENTRYPOINT_LAUNCHER, "package", str(module_root), entries[0]["name"], source, locale]
409413

410414
environment = dict(params.get("environment") or {})
411415
environment.update(launch.get("environment") or {})
416+
if kind == "module":
417+
environment.setdefault("PYTHONIOENCODING", "utf-8")
418+
arguments = [
419+
*_string_args(launch.get("runtimeArguments")),
420+
*program,
421+
*_string_args(params.get("optionArguments")),
422+
*_string_args(launch.get("arguments", params.get("userArguments"))),
423+
]
424+
if configured_interpreter:
425+
tool = params.get("tool")
426+
executable = tool.get("executable") if isinstance(tool, dict) else None
427+
if not isinstance(executable, str) or not Path(executable).is_absolute():
428+
raise PluginError("python.interpreterUnavailable", run_message("interpreter", locale))
429+
environment.setdefault("PYTHON_EXECUTABLE", executable)
430+
arguments = ["-I", "-B", _ENTRYPOINT_LAUNCHER, "interpreter", executable, *arguments]
412431
return {
413432
"executable": {"kind": "toolchain", "value": "python"},
414-
"arguments": [
415-
*_string_args(launch.get("runtimeArguments")),
416-
*program,
417-
*_string_args(params.get("optionArguments")),
418-
*_string_args(launch.get("arguments", params.get("userArguments"))),
419-
],
433+
"arguments": arguments,
420434
"workingDirectory": working_directory,
421435
"environment": environment,
422436
}

0 commit comments

Comments
 (0)