diff --git a/README.md b/README.md
index c2685ae..7062d58 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda
| 运行 | 工具栏「当前文件」运行带 `if __name__ == "__main__"` 的脚本和包里的 `__main__.py`;构建窗口列出 `[project.scripts]`、Django `manage.py`、FastAPI、Flask 等入口;「运行/调试配置 → + → Python」可以手动配置脚本或模块 |
| 测试 | `pytest --collect-only` 收集函数、类方法、参数化用例和 doctest,组成测试树;可以运行整个套件或单个用例 |
| 依赖 | 构建窗口的「依赖」列出所选解释器里已安装的包、版本和依赖关系,不需要 pip |
-| 任务 | `pip install -r requirements.txt`、`mypy`;有 `uv.lock` 时 `uv sync`、`uv lock`;有 `environment.yml` 时 `conda env update`;有 Ruff 配置时 `ruff check`、`ruff format` |
+| 任务 | `pip install -r requirements.txt`、`mypy`;有 `uv.lock` 时 `uv sync`、`uv lock`;有 `environment.yml` 或 `environment.yaml` 时 `conda env update`(两者都有时使用 `environment.yml`);有 `ruff.toml` 或 `.ruff.toml` 时 `ruff check`、`ruff format`,优先使用项目虚拟环境里的 Ruff |
| 调试 | 随包的 debugpy 1.8.22,支持启动和按地址附加(`host`、`port`、`pathMappings`) |
| 输出链接 | 终端和运行输出里 Traceback 的 `File "…", line N` 可以点击跳到源码 |
| 新建项目 | 选解释器、选是否用 venv 或 uv 建 `.venv`、是否加示例代码;创建后项目固定使用所选解释器 |
@@ -90,7 +90,8 @@ pytest 用覆盖路径,Pyrefly 和调试仍用下面找到的解释器。Lithe
| Python 3.9 或更新,调试要 3.10 或更新 | 运行、测试、调试、依赖、读取项目 | 你电脑上的,见上文“Python 解释器” |
| pytest | 测试树和运行测试 | 装在项目用的解释器里 |
| mypy | `mypy` 任务 | 装在项目用的解释器里 |
-| uv、conda、ruff | 对应的任务 | `PATH` |
+| uv、conda | 对应的任务 | `PATH`。Conda 任务使用 `PATH` 或 Python 工具链中可运行的 Python 3.9+ 选择环境文件。 |
+| Ruff | Ruff 检查与格式化任务 | 项目的 `.venv`、`venv`、`.conda`,然后是 `PATH` |
| Pyrefly 1.4.1 | 代码智能 | 随插件包 |
| debugpy 1.8.22 | 调试 | 随插件包,由项目用的解释器运行,需要 Python 3.10 或更新 |
@@ -144,6 +145,7 @@ PYTEST_PYTHON=/path/to/python node scripts/test.mjs # 用真实的 Pyre
(默认 `python3`)。`PYTHON` 要是 3.10 或更新,调试流程要用它建的虚拟环境运行 debugpy。`plugin.json` 的格式见 Rust Core 仓库的
[插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md)和
[构建工具接入指南](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/build-tool-integration.md)。
+打包时把 `scripts/package/conda_env_update.py` 嵌入 Conda 任务的命令参数。脚本只在用户执行任务时读取工作目录里的环境文件。
## 宿主端到端测试
diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md
index 667ddc0..60c7883 100644
--- a/docs/feature-matrix.md
+++ b/docs/feature-matrix.md
@@ -23,7 +23,7 @@
| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用工具链为项目解析出的解释器,设置了覆盖路径时用覆盖路径。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(宿主 `58b527ed`(含 [#2321](https://github.com/1lck/Lithe-IDEA/pull/2321)),脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` |
| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时用 `python -I -B` 读取所选 Python 环境中已安装的包、版本和依赖关系,跳过用户级 site-packages 及其启动钩子,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` |
| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --prune`,优先 `environment.yml`,其次 `environment.yaml`)、`ruff`(`check` / `format`)直接显示工作区任务,需要支持省略构建模型的桌面宿主。Ruff 由 `ruff.toml` 或 `.ruff.toml` 识别,依次查找 `.venv`、`venv`、`.conda` 和 `PATH`。 | ✅ 已验证(修复版宿主) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-25,macOS ARM64 真实包工作台 [#19](https://github.com/Lithe-IDEA/lithe-plugin-python/issues/19) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`,需要 Python 3.10 或更新(`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` |
diff --git a/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go
index fbda9b6..aa9d95c 100644
--- a/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go
+++ b/e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go
@@ -18,6 +18,147 @@ import (
"github.com/vivaui/viva/headless"
)
+func TestPythonSupportPluginStandaloneBuildPanel(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ files map[string]string
+ tasks map[string][]string
+ }{
+ {
+ name: "uv-without-ruff",
+ files: map[string]string{"pyproject.toml": "[project]\nname = 'plain'\nversion = '0.1.0'\n", "uv.lock": "version = 1\n"},
+ tasks: map[string][]string{"uv": {"lock", "sync"}},
+ },
+ {
+ name: "uv-conda-and-ruff",
+ files: map[string]string{
+ "pyproject.toml": "[project]\nname = 'tools'\nversion = '0.1.0'\n",
+ "uv.lock": "version = 1\n",
+ "environment.yaml": "name: fixture\ndependencies:\n - python\n",
+ ".ruff.toml": "line-length = 100\n",
+ },
+ tasks: map[string][]string{"uv": {"lock", "sync"}, "conda": {"env-update"}, "ruff": {"check", "format"}},
+ },
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
+ defer cancel()
+ root := filepath.Join(t.TempDir(), scenario.name)
+ if err := os.Mkdir(root, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ for name, contents := range scenario.files {
+ if err := os.WriteFile(filepath.Join(root, name), []byte(contents), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ runConda := runtime.GOOS != "windows" && len(scenario.tasks["conda"]) != 0
+ if runConda {
+ tools := t.TempDir()
+ python, err := exec.LookPath("python3")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(python, filepath.Join(tools, "python")); err != nil {
+ t.Fatal(err)
+ }
+ // Some systems expose a launcher on PATH even without a Python runtime behind it.
+ if err := os.WriteFile(filepath.Join(tools, "python3"), []byte("#!/bin/sh\nexit 29\n"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ const conda = "#!/bin/sh\n[ \"$#\" = 5 ] && [ \"$*\" = 'env update --file environment.yaml --prune' ] && [ -f \"$4\" ]\n"
+ if err := os.WriteFile(filepath.Join(tools, "conda"), []byte(conda), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", tools+string(os.PathListSeparator)+os.Getenv("PATH"))
+ }
+ kernel := core.NewClient()
+ preferences := store.At(t.TempDir())
+ if err := preferences.Save(settingsFile, settings{Theme: themeDark}); err != nil {
+ t.Fatal(err)
+ }
+ options := Options{
+ Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences,
+ Languages: []string{"zh-Hans"},
+ }
+ openHarness := newHarnessWithOptions
+ out := os.Getenv("LITHE_PYTHON_VISUAL_DIR")
+ var session *headless.Session
+ if out != "" {
+ if err := os.MkdirAll(out, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ openHarness = func(t testing.TB, options Options) *harness {
+ return newHarnessWithDriver(t, options, func(config app.Config) (*app.Driver, func(), error) {
+ config.Width, config.Height = 1280, 840
+ var err error
+ session, err = headless.Open(config, nil, headless.Options{})
+ if err != nil {
+ return nil, nil, err
+ }
+ return session.Driver(), session.Close, nil
+ })
+ }
+ }
+ h := openHarness(t, options)
+ installPythonArchive(t, ctx, h.app.plugins, pythonArchiveForE2E(t))
+ h.open(root)
+ p := h.app.project
+ h.app.reduceChrome(core.SetChromeOpen(itemBuild, true))
+ h.awaitBuildDetection(p)
+ p.setAllBuildGroups(true)
+
+ condaIndex := -1
+ for index, instance := range p.build.instances {
+ id := instance.BuildSystemID
+ if id == "conda" {
+ condaIndex = index
+ }
+ if id == "python" {
+ continue
+ }
+ if _, expected := scenario.tasks[id]; !expected {
+ t.Errorf("unexpected build system %q", id)
+ }
+ if !instance.modelLoaded || instance.modelError != "" || p.buildSyncSession(instance.ID) != nil {
+ t.Errorf("%s loaded=%v, model error=%q, sync session=%v", id, instance.modelLoaded, instance.modelError, p.buildSyncSession(instance.ID))
+ }
+ }
+ visible := make(map[[2]string]bool)
+ for _, row := range laidOutBuildRows(t, h, p) {
+ if row.kind == buildRowTask && row.node != nil && row.node.ProjectID == "" && row.node.TargetID == "" {
+ id := p.build.instances[row.instance].BuildSystemID
+ visible[[2]string{id, row.node.TaskID}] = true
+ }
+ }
+ for id, tasks := range scenario.tasks {
+ for _, task := range tasks {
+ if !visible[[2]string{id, task}] {
+ t.Errorf("missing visible workspace task %s/%s", id, task)
+ }
+ }
+ }
+ if session != nil {
+ h.settle()
+ if err := session.Screenshot(filepath.Join(out, "python-build-"+scenario.name+".png")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if runConda && condaIndex >= 0 {
+ h.app.selectBuildInstance(p, condaIndex)
+ operation, err := h.app.runBuildTask(p, "", "", "env-update", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ awaitStateWithin(t, h, 10*time.Second, "Conda environment update to finish", func() bool { return !operation.session.running })
+ if operation.session.outcome != runSucceeded {
+ t.Fatalf("Conda environment update: %s\n%s", operation.session.summary, operation.session.output.all())
+ }
+ }
+ })
+ }
+}
+
func TestPythonSupportPluginManualRunAndDependencies(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel()
@@ -200,18 +341,14 @@ func TestPythonSupportPluginManualRunAndDependencies(t *testing.T) {
h.app.post(func(a *App) {
p.setBuildOpen(buildOpenKey(instance.ID, section.node.Key), buildOpenState{open: true, dependencies: true})
})
- var dependencies *buildDependencies
+ const rootPackage = "root-demo:1.0"
awaitStateWithin(t, h, 10*time.Second, "the installed Python package in the Build panel", func() bool {
- rows, _ := h.app.buildTreeRows(p)
- for _, row := range rows {
- if row.kind == buildRowDependency && row.label == "root-demo:1.0" {
- dependencies = p.build.dependencies[buildDependencyKey(instance.ID, section.node.ProjectID)]
- return true
- }
- }
- return false
+ return h.labelBounds(rootPackage).Width > 0
})
- h.app.post(func(a *App) { dependencies.open["0"] = true })
+ point := center(h.labelBounds(rootPackage))
+ if err := h.driver.Click(point.X, point.Y); err != nil {
+ t.Fatal(err)
+ }
awaitStateWithin(t, h, 10*time.Second, "the transitive package in the Build panel", func() bool {
return h.shows("child-demo:2.0")
})
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 19a6184..d4ef181 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
@@ -333,6 +333,101 @@ func installPythonArchive(t *testing.T, ctx context.Context, service *pluginserv
return installed.Path
}
+func TestPythonSupportPluginStandaloneBuildPlans(t *testing.T) {
+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
+ defer cancel()
+ kernel := core.NewClient()
+ service, err := pluginservice.Open(kernel, store.At(t.TempDir()), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ installed := installPythonArchive(t, ctx, service, pythonArchiveForE2E(t))
+ rawManifest, err := os.ReadFile(filepath.Join(installed, "plugin.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifest, err := pluginhost.Validate(ctx, kernel, rawManifest, pluginhost.Declared())
+ if err != nil {
+ t.Fatal(err)
+ }
+ workspace := t.TempDir()
+ write := func(name, contents string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(workspace, name), []byte(contents), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ detect := func(want ...string) {
+ t.Helper()
+ detection, err := kernel.DetectBuildSystems(ctx, workspace, []json.RawMessage{manifest})
+ if err != nil || len(detection.Rejected) != 0 {
+ t.Fatalf("detect build systems: %+v, %v", detection.Rejected, err)
+ }
+ ids := make([]string, 0, len(detection.Instances))
+ for _, instance := range detection.Instances {
+ ids = append(ids, instance.BuildSystemID)
+ }
+ slices.Sort(ids)
+ if !slices.Equal(ids, want) {
+ t.Fatalf("detected systems = %v, want %v", ids, want)
+ }
+ }
+ write("pyproject.toml", "[project]\nname = 'plain'\nversion = '0.1.0'\n")
+ write("uv.lock", "version = 1\n")
+ detect("python", "uv")
+ write("environment.yml", "name: fixture\n")
+ detect("conda", "python", "uv")
+
+ for _, marker := range []string{"ruff.toml", ".ruff.toml"} {
+ write(marker, "line-length = 100\n")
+ detect("conda", "python", "ruff", "uv")
+ if err := os.Remove(filepath.Join(workspace, marker)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for _, system := range []struct {
+ id string
+ tasks []string
+ }{
+ {"uv", []string{"lock", "sync"}},
+ {"conda", []string{"env-update"}},
+ {"ruff", []string{"check", "format"}},
+ } {
+ tree, err := kernel.BuildModelTree(ctx, manifest, system.id, core.BuildModelTreeRequest{})
+ if err != nil {
+ t.Fatalf("%s task tree: %v", system.id, err)
+ }
+ var ids []string
+ for _, group := range tree.Nodes {
+ for _, node := range group.Children {
+ if node.Kind == core.BuildTreeTask && node.ProjectID == "" && node.TargetID == "" {
+ ids = append(ids, node.TaskID)
+ }
+ }
+ }
+ slices.Sort(ids)
+ if !slices.Equal(ids, system.tasks) {
+ t.Errorf("%s workspace tasks = %v, want %v", system.id, ids, system.tasks)
+ }
+ }
+
+ invocation, err := kernel.PlanBuildInvocation(ctx, manifest, "ruff", core.BuildInvocationRequest{
+ Root: "nested", Platform: "macos",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(invocation.Executables) == 0 {
+ t.Fatal("Ruff invocation has no executable candidates")
+ }
+ first := invocation.Executables[0]
+ if first.Kind != "projectFile" || first.Path != "nested/.venv/bin/ruff" ||
+ !slices.Equal(first.Requires, []string{"nested/.venv/pyvenv.cfg"}) {
+ t.Fatalf("first Ruff candidate = %+v, want project-local Ruff with its environment marker", first)
+ }
+}
+
func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
archive := pythonArchiveForE2E(t)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json
index d9ee8d4..5ad93b3 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": "58b527edc46345d7c623c3bddd9db80d609ebf06",
+ "revision": "26b691995b6f2898baa2243b1692512f456b7304",
"packages": {
"./internal/projectgen": "^TestPythonPlugin",
"./internal/settingswindow": "^TestPythonPluginSettingsPreview$",
diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json
index 8404d71..51dd6ad 100644
--- a/io.github.lithe-idea.python-support/plugin.json
+++ b/io.github.lithe-idea.python-support/plugin.json
@@ -822,26 +822,40 @@
},
"invocation": {
"executables": [
- { "kind": "command", "command": "conda" }
+ { "kind": "command", "command": "python3", "platforms": ["macos", "linux"] },
+ { "kind": "command", "command": "python" },
+ { "kind": "toolchain", "toolchainID": "python" }
],
+ "minimumVersion": "3.9",
"version": {
"arguments": ["--version"],
- "pattern": "conda (\\d+(?:\\.\\d+)*)"
- }
+ "pattern": "Python (\\d+(?:\\.\\d+)*)"
+ },
+ "runtimeDependencies": [
+ {
+ "id": "conda",
+ "displayName": "Conda",
+ "executables": [{ "kind": "command", "command": "conda" }],
+ "version": {
+ "arguments": ["--version"],
+ "pattern": "conda (\\d+(?:\\.\\d+)*)"
+ }
+ }
+ ]
},
"tasks": [
{
"id": "env-update",
"displayName": "conda env update",
- "description": "Update the Conda environment from environment.yml and prune removed packages.",
+ "description": "Update the Conda environment from environment.yml or environment.yaml and prune removed packages.",
"group": "build",
"scopes": ["workspace", "project"],
"arguments": [
- "env",
- "update",
- "--file",
- "environment.yml",
- "--prune",
+ "-I",
+ "-B",
+ "-S",
+ "-c",
+ "@conda-env-update@",
"${optionArguments}",
"${userArguments}"
]
@@ -855,10 +869,17 @@
"id": "ruff",
"displayName": "Ruff",
"detection": {
- "markers": ["ruff.toml", ".ruff.toml", "pyproject.toml"]
+ "markers": ["ruff.toml", ".ruff.toml"]
},
"invocation": {
"executables": [
+ { "kind": "projectFile", "path": ".venv/bin/ruff", "requires": [".venv/pyvenv.cfg"], "platforms": ["macos", "linux"] },
+ { "kind": "projectFile", "path": ".venv/Scripts/ruff.exe", "requires": [".venv/pyvenv.cfg"], "platforms": ["windows"] },
+ { "kind": "projectFile", "path": "venv/bin/ruff", "requires": ["venv/pyvenv.cfg"], "platforms": ["macos", "linux"] },
+ { "kind": "projectFile", "path": "venv/Scripts/ruff.exe", "requires": ["venv/pyvenv.cfg"], "platforms": ["windows"] },
+ { "kind": "projectFile", "path": ".conda/bin/ruff", "requires": [".conda/conda-meta/history"], "platforms": ["macos", "linux"] },
+ { "kind": "projectFile", "path": ".conda/Library/bin/ruff.exe", "requires": [".conda/conda-meta/history"], "platforms": ["windows"] },
+ { "kind": "projectFile", "path": ".conda/Scripts/ruff.exe", "requires": [".conda/conda-meta/history"], "platforms": ["windows"] },
{ "kind": "command", "command": "ruff" }
],
"version": {
@@ -909,7 +930,7 @@
]
},
"sync": {
- "watch": ["ruff.toml", ".ruff.toml", "pyproject.toml"]
+ "watch": ["ruff.toml", ".ruff.toml"]
}
}
],
diff --git a/scripts/package.mjs b/scripts/package.mjs
index 1d47bf0..45b185a 100644
--- a/scripts/package.mjs
+++ b/scripts/package.mjs
@@ -57,6 +57,13 @@ export function manifestForPlatform(baseManifest, platform, lock) {
const isWindows = platform.startsWith("windows-");
clone.backend.launch.path = backendPath(platform);
+ // Task arguments have no plugin-directory variable. Keep the task body in
+ // a Python source file and embed it as an argv element during packaging.
+ const conda = clone.buildSystems.find(({ id }) => id === "conda");
+ const envUpdate = conda.tasks.find(({ id }) => id === "env-update");
+ const condaProgram = readFileSync(join(ROOT, "scripts", "package", "conda_env_update.py"), "utf8");
+ envUpdate.arguments = envUpdate.arguments.map((arg) => arg === "@conda-env-update@" ? condaProgram : arg);
+
for (const server of clone.languageServers ?? []) {
if (server.languageID === "python" && server.launch?.kind === "packaged") {
server.launch.path = platformSpec.packagePath;
diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs
index ca81780..ded0c89 100644
--- a/scripts/package/archives.test.mjs
+++ b/scripts/package/archives.test.mjs
@@ -27,6 +27,26 @@ test("every platform shows the settings views and the interpreter override on th
}
});
+test("Ruff requires its own configuration and prefers project executables to PATH", () => {
+ for (const platform of Object.keys(lock.pyrefly.platforms)) {
+ const manifest = manifestForPlatform(baseManifest, platform, lock);
+ const ruff = manifest.buildSystems.find(({ id }) => id === "ruff");
+ assert.deepEqual(ruff.detection.markers, ["ruff.toml", ".ruff.toml"]);
+ const host = platform.startsWith("windows-") ? "windows" : platform.startsWith("darwin-") ? "macos" : "linux";
+ const windows = host === "windows";
+ const venvBinary = windows ? "Scripts/ruff.exe" : "bin/ruff";
+ const condaBinaries = windows ? ["Library/bin/ruff.exe", "Scripts/ruff.exe"] : ["bin/ruff"];
+ const projectFile = (path, marker) => ({ kind: "projectFile", path, requires: [marker] });
+ const candidates = ruff.invocation.executables.filter(({ platforms }) => !platforms || platforms.includes(host));
+ assert.deepEqual(candidates.map(({ platforms, ...candidate }) => candidate), [
+ projectFile(`.venv/${venvBinary}`, ".venv/pyvenv.cfg"),
+ projectFile(`venv/${venvBinary}`, "venv/pyvenv.cfg"),
+ ...condaBinaries.map((binary) => projectFile(`.conda/${binary}`, ".conda/conda-meta/history")),
+ { kind: "command", command: "ruff" },
+ ], platform);
+ }
+});
+
function checkBackendArchitecture(bytes, platform) {
const arm = platform.endsWith("-arm64");
if (platform.startsWith("windows-")) {
diff --git a/scripts/package/conda_env_update.py b/scripts/package/conda_env_update.py
new file mode 100644
index 0000000..44d2491
--- /dev/null
+++ b/scripts/package/conda_env_update.py
@@ -0,0 +1,28 @@
+"""Run Conda against the environment file in the task's working directory."""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+
+def main() -> int:
+ conda = Path(os.environ["LITHE_CONDA_PATH"])
+ if os.name == "nt" and conda.suffix.lower() in (".bat", ".cmd"):
+ # Standard Conda installations expose condabin on PATH. Use its native
+ # executable so arguments are passed directly without batch expansion.
+ if conda.parent.name.lower() == "condabin":
+ conda = conda.parent.parent / "Scripts" / "conda.exe"
+ else:
+ conda = conda.with_suffix(".exe")
+ environment_file = "environment.yml"
+ if not Path(environment_file).is_file() and Path("environment.yaml").is_file():
+ environment_file = "environment.yaml"
+ args = [str(conda), "env", "update", "--file", environment_file, "--prune", *sys.argv[1:]]
+ if os.name == "nt":
+ return subprocess.run(args, check=False, creationflags=subprocess.CREATE_NO_WINDOW).returncode
+ os.execv(conda, args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test.mjs b/scripts/test.mjs
index a3f0658..9cfea72 100644
--- a/scripts/test.mjs
+++ b/scripts/test.mjs
@@ -313,6 +313,47 @@ try {
const dependencyArguments = (outputFile) => dependencyCommand.arguments.map((arg) =>
arg.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", outputFile));
+ await check("Conda task selects the existing environment file and passes through arguments", () => {
+ const task = pluginManifest.buildSystems.find(({ id }) => id === "conda").tasks[0];
+ const [isolated, noBytecode, noSite, execute, script] = task.arguments;
+ const workspace = join(scratch, "conda workspace");
+ mkdirSync(workspace);
+ run(pythonCmd, [isolated, noBytecode, noSite, execute, `
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import ModuleType
+from unittest.mock import Mock, patch
+
+task = ModuleType("conda_env_update")
+exec(compile(sys.argv[1], "conda_env_update.py", "exec"), task.__dict__)
+conda = Path.cwd() / "conda install" / "bin" / "conda"
+if os.name == "nt":
+ conda = Path.cwd() / "conda install" / "condabin" / "conda.bat"
+ executable = conda.parent.parent / "Scripts" / "conda.exe"
+else:
+ executable = conda
+os.environ["LITHE_CONDA_PATH"] = str(conda)
+sys.argv = ["conda_env_update.py", "--name", "test environment"]
+for files, selected in [((), "environment.yml"), (("environment.yaml",), "environment.yaml"),
+ (("environment.yml", "environment.yaml"), "environment.yml")]:
+ for name in ("environment.yml", "environment.yaml"):
+ Path(name).unlink(missing_ok=True)
+ for name in files:
+ Path(name).write_text("name: test\\n", encoding="utf-8")
+ expected = [str(executable), "env", "update", "--file", selected, "--prune", "--name", "test environment"]
+ if os.name == "nt":
+ with patch.object(task.subprocess, "run", return_value=Mock(returncode=17)) as invoke:
+ assert task.main() == 17
+ invoke.assert_called_once_with(expected, check=False, creationflags=subprocess.CREATE_NO_WINDOW)
+ else:
+ with patch.object(task.os, "execv") as invoke:
+ task.main()
+ invoke.assert_called_once_with(executable, expected)
+`, script], { cwd: workspace });
+ });
+
await check("dependency command skips user-site startup hooks", () => {
const environment = join(scratch, "dependency environment with shared site");
run(pythonCmd, ["-I", "-B", "-m", "venv", "--without-pip", "--system-site-packages", environment]);