diff --git a/README.md b/README.md index 155b499..186b123 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ > **预发布**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 > (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。0.1.0 的调试需要宿主支持 `tcpAnnounced` 调试适配器 -> ([1lck/Lithe-IDEA#1954](https://github.com/1lck/Lithe-IDEA/pull/1954)),在包含它的桌面端版本发布前, -> 这个版本只作为预发布提供。 +> ([1lck/Lithe-IDEA#1954](https://github.com/1lck/Lithe-IDEA/pull/1954)),`go` 工具定义需要固定了 Rust Core +> 6477e9a 或更新版本的桌面端([1lck/Lithe-IDEA#1964](https://github.com/1lck/Lithe-IDEA/pull/1964))。在包含它们的桌面端版本发布前,这个版本只作为预发布提供。 ## 功能 @@ -29,7 +29,8 @@ | 依赖 | `go list -m -json all` 列出模块依赖(含版本和是否间接依赖) | | 同步 | `go.mod`、`go.sum`、`go.work` 变化后重新读取模块 | | 调试 | 「调试」窗口里选 Go (Delve),调试当前打开的 `.go` 文件所在的包:断点、单步、调用栈、变量和表达式求值,程序输出显示在调试控制台 | -| 新建项目 | 「新建项目」里的 Go:生成 `go.mod`、`.gitignore`,可选生成示例 `main.go`;模块路径默认是小写的项目名 | +| 新建项目 | 「新建项目」里的 Go:选择 GOROOT,生成 `go.mod`、`.gitignore`,可选生成示例 `main.go`;模块路径默认是小写的项目名,Go 版本默认是所选 Go 的版本 | +| 工具链 | 在常见位置找到电脑上的 Go 安装;项目可以固定用其中一个构建和运行 | ## 设置和构建选项 @@ -37,7 +38,7 @@ | 设置 | 生效方式 | 说明 | | --- | --- | --- | -| Go executable | 重新读取模块 | 读取模块、构建、检查、测试和运行用的 `go`。留空时使用 `PATH` 里的 `go`。也显示在「构建、执行、部署 › Go Modules」页 | +| Go executable | 重新读取模块 | 读取模块、构建、检查、测试和运行用的 `go`。留空时使用「工具链」选出的 Go(见下)。也显示在「构建、执行、部署 › Go Modules」页 | | Staticcheck analyses | 立即 | 让 gopls 额外报告 staticcheck 的检查结果;大模块上更耗 CPU 和内存 | | Format with gofumpt | 立即 | 格式化时使用 gofumpt 的更严格规则 | | Parameter placeholders in completion | 立即 | 补全函数调用时插入参数占位符 | @@ -55,6 +56,20 @@ 选项会加到构建、检查、测试和运行的命令里。 +**工具链**(设置 →「构建、执行、部署」→「工具链」):插件声明了 `go` 工具,Lithe 在下面这些位置查找 Go, +用 `go version` 读出版本,列在这里: + +| 平台 | 位置 | +| --- | --- | +| macOS | `/usr/local/go`(官方安装包),Homebrew 的 `go` 和 `go@1.N`(`/opt/homebrew/Cellar`、`/usr/local/Cellar`) | +| Linux | `/usr/local/go`,`/usr/lib/go`、`/usr/lib/go-1.N`,Linuxbrew | +| Windows | `C:\Program Files\Go`,Scoop | +| 所有平台 | `~/sdk/go*`(`golang.org/dl` 下载的版本),`~/go/go*` | + +没有设置 Go executable 时,构建、检查、测试和运行按顺序使用第一个可用的 Go:项目固定的 Go、全局默认的 Go、 +`GOROOT` 环境变量指向的 Go、`PATH` 里的 `go`、找到的最新安装;都没有时使用 `PATH` 里的 `go`。 +选中的 Go 的 `bin` 目录加到命令的 `PATH` 前面,`GOROOT` 设为它的安装目录。 + ## 调试 打开「调试」窗口,适配器选 **Go (Delve)**,打开要调试的 `.go` 文件,在行号旁设好断点后点「开始」。 @@ -73,18 +88,20 @@ | 字段 | 说明 | | --- | --- | +| GOROOT | 项目构建和运行用的 Go,从「工具链」找到的安装里选,默认是版本最新的一个。创建后项目固定使用它(记在项目的 `.lithe/toolchains/local.json`),以后可以在「工具链」里修改。没有找到 Go 时留空,不影响创建 | | 添加示例代码 | 默认开启,生成打印 `Hello, Gopher!` 的 `main.go`,创建后打开它;关闭时只生成模块文件,创建后打开 `go.mod` | | 模块路径 | 写进 `go.mod` 的 `module` 行,别的代码用它导入本模块,例如 `example.com/hello` 或 `github.com/you/hello`。默认是小写的项目名;项目名里有空格时需要改掉 | -| Go 版本(高级) | 写进 `go.mod` 的 `go` 行,表示模块至少需要的 Go 版本,默认 `1.21`;更新的 Go 也能构建 | +| Go 版本(高级) | 写进 `go.mod` 的 `go` 行,表示模块至少需要的 Go 版本,默认是所选 GOROOT 的版本,换 GOROOT 时跟着变,手动改过后不再变;更新的 Go 也能构建。没有选 GOROOT 时需要手动填写,高级选项会自动展开 | -`go.mod` 由模板直接写出,不运行 `go mod init`,所以创建项目不需要联网,也不依赖 `go` 的安装位置。 +`go.mod` 由模板直接写出,不运行 `go mod init`,所以创建项目不需要联网,也不需要先装好 `go`。 +GOROOT 只能选 Go 1.21 或更新的版本;选了更旧的版本时表单会提示,不能创建。 这些字段目前只有英文名称:插件语言文件还不能翻译新建项目的字段。 ## 依赖的程序 | 程序 | 用途 | 查找方式 | | --- | --- | --- | -| `go` 1.21 或更新版本 | 读取模块、构建、检查、测试、运行、依赖 | 插件设置 Go executable;留空时找 `PATH` 里的 `go` | +| `go` 1.21 或更新版本 | 读取模块、构建、检查、测试、运行、依赖 | 插件设置 Go executable;留空时用「工具链」选出的 Go,最后找 `PATH` 里的 `go` | | `gopls` | 代码智能 | `PATH` 里的 `gopls` | | `dlv`(Delve,需要有 `dlv dap` 命令,已用 1.27.2 验证) | 调试 | `PATH` 里的 `dlv`;Delve 构建程序时用 `PATH` 里的 `go` | @@ -117,8 +134,11 @@ go install github.com/go-delve/delve/cmd/dlv@latest - Delve 由 Lithe 按 `debugAdapters` 的声明启动为 `dlv dap`。Delve 在标准输出打印 `DAP server listening at: <地址>`,Lithe 读到这一行后连接这个本机地址(`tcpAnnounced` 传输)。 调试的包由当前文件所在目录决定(`target.directory` 绑定到 Delve 的 `program`)。 +- Go 的查找方式由 `toolDefinitions` 里的 `go` 声明:查找位置、`bin/go` 的位置、用 `go version` 读版本、 + `GOROOT` 环境变量。构建系统的 `go` 先看 Go executable 设置,再交给这个工具定义解析。 - 新建项目由 `projectGenerators` 声明,Lithe 把 `templates/go/` 里的模板展开到新目录; - 模板名以 `dot-` 开头的文件生成为点文件。 + 模板名以 `dot-` 开头的文件生成为点文件。GOROOT 是 `tool` 类型的字段,Go 版本的默认值是 + `${field.goroot.version}`;创建后 Lithe 把所选 GOROOT 记为项目固定(`pinAs: "project"`)。 - 插件目录在运行时保持只读。 ## 诊断日志 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 4069c46..6bb5a3b 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -22,12 +22,14 @@ | --- | --- | --- | --- | --- | | `go-support-plugin` | gopls 代码智能、Go Modules 构建、运行与 `go test` | implemented / pending | missing / not-applicable | 2026-11-15 macOS 宿主端到端测试通过 | | `go-debug-delve` | 用用户的 Delve 调试 Go 包 | implemented / pending | missing / not-applicable | 2026-11-15 macOS 宿主端到端测试通过 | -| `go-project-generator` | 「新建项目」里的 Go 模块 | implemented / pending | missing / not-applicable | 2026-11-15 macOS 宿主集成测试通过 | +| `go-project-generator` | 「新建项目」里的 Go 模块,GOROOT 选择和 Go 版本默认值 | implemented / pending | missing / not-applicable | 2026-11-15 macOS 宿主集成测试通过 | ## go-support-plugin **能力**:用用户自己的 `gopls` 提供代码智能;用声明式 `buildSystems` 识别 Go 模块,在构建窗口里列出包, 运行 `go build`、`go vet`、`go test` 和 `go run`,列出模块依赖;插件设置调整 `go` 路径和 gopls 选项。 +没有设置 `go` 路径时,构建用 `toolDefinitions` 里的 `go` 工具定义解析 Go:项目固定的 Go、全局默认、`GOROOT`、 +`PATH` 里的 `go`、在常见位置找到的最新安装。 | 平台 | 实现 | 验证 | 说明 | | --- | --- | --- | --- | @@ -36,7 +38,9 @@ **证据**: -- `io.github.lithe-idea.go-support/plugin.json`:`languageServers`、`buildSystems`、`settings` 的声明。 +- `io.github.lithe-idea.go-support/plugin.json`:`languageServers`、`buildSystems`、`settings`、`toolDefinitions` 的声明。 +- `e2e/host/desktop/internal/projectgen/go_integration_test.go`:`TestGoPluginToolDefinitionFindsTheLocalGo` + 确认工具定义找到 `PATH` 里那个 go 的 GOROOT 和版本。 - `e2e/host/desktop/internal/workbench/official_go_plugin_e2e_test.go`:宿主端到端测试。 **依赖的宿主能力**:`languageServers`(宿主启动 gopls 并转发 `workspace/configuration`)、`buildSystems` @@ -50,6 +54,7 @@ `application` 目标、Build、Vet、运行入口、Go executable 设置重新读取模型并用于后续构建、gopls 诊断、 gofumpt 设置立即生效,以及工作流结束后安装目录逐字节不变。没有覆盖 `go test`、依赖列表、`go.mod` 变化后重新读取、 构建选项(Build Tags、Race Detector)、缺少 gopls 时的提示,也没有做下面的手工验收。 +这次验证早于构建加入 `go` 工具定义解析(插件 PR “GOROOT 选择”),之后没有重跑这个测试。 **验证方法**(macOS): @@ -60,6 +65,7 @@ gofumpt 设置立即生效,以及工作流结束后安装目录逐字节不变 4. 打开 `.go` 文件:gopls 来自用户的 `PATH`,补全、跳转定义、悬停、诊断和格式化可用;修改 gofumpt、 Staticcheck、补全占位符、悬停文档设置后立即生效,不需要重启语言服务器。 5. 修改 Go executable 设置后模块重新读取,之后的构建使用新路径;Build Tags 和 Race Detector 构建选项出现在命令里。 + 清空 Go executable 后,「构建、执行、部署 › 工具链」列出电脑上的 Go;为项目选另一个 Go 后,构建输出里的 `go version` 随之改变。 6. 查看依赖列表(含版本和间接依赖);修改 `go.mod` 后模块重新读取。 7. `PATH` 里没有 gopls 时给出缺失提示,不崩溃。 8. 禁用插件后 gopls 和运行中的进程退出;插件安装目录在整个过程中不被写入。 @@ -110,9 +116,10 @@ Go 1.27.4、Delve 1.27.2。`node scripts/e2e-host.mjs` 通过 `TestOfficialGoPlu ## go-project-generator -**能力**:「新建项目」对话框里的 Go。生成 `go.mod`(`module` 行是模块路径,默认是小写的项目名;`go` 行默认 1.21) -和 `.gitignore`,可选生成打印 `Hello, Gopher!` 的示例 `main.go`。`go.mod` 由模板写出,不运行 `go mod init`, -创建项目不需要联网,也不需要 `go`。 +**能力**:「新建项目」对话框里的 Go。GOROOT 下拉列出 `go` 工具定义在电脑上找到的 Go,默认是版本最新的一个, +创建后记为项目固定,构建和运行使用它;没有找到 Go 时留空,不影响创建。生成 `go.mod`(`module` 行是模块路径, +默认是小写的项目名;`go` 行默认是所选 GOROOT 的版本,手动改过后不再跟随)和 `.gitignore`,可选生成打印 +`Hello, Gopher!` 的示例 `main.go`。`go.mod` 由模板写出,不运行 `go mod init`,创建项目不需要联网,也不需要先装好 `go`。 | 平台 | 实现 | 验证 | 说明 | | --- | --- | --- | --- | @@ -121,26 +128,42 @@ Go 1.27.4、Delve 1.27.2。`node scripts/e2e-host.mjs` 通过 `TestOfficialGoPlu **证据**: -- `io.github.lithe-idea.go-support/plugin.json`:`projectGenerators` 里的 `go-module`,以及 `project.generate` 权限。 +- `io.github.lithe-idea.go-support/plugin.json`:`projectGenerators` 里的 `go-module`(`goroot` 是 `tool` 字段, + `goVersion` 默认 `${field.goroot.version}`)、`toolDefinitions` 里的 `go`,以及 `project.generate` 权限。 - `io.github.lithe-idea.go-support/templates/go/`:模块和示例代码模板。 - `e2e/host/desktop/internal/projectgen/go_integration_test.go`:经 Core 的表单、生成计划和宿主执行器的集成测试。 +**依赖的宿主能力**:`projectGenerators` 的 `tool` 字段和创建后的项目固定,`toolDefinitions` 的发现和解析; +以子命令开头的版本探针 `go version` 需要 Rust Core 6477e9a(Lithe-core-rust#52,宿主 [1lck/Lithe-IDEA#1964](https://github.com/1lck/Lithe-IDEA/pull/1964))。 + **限制**:字段名称和说明目前只有英文,插件语言文件还不覆盖新建项目。 -**最近验证**:2026-11-15,macOS(Apple Silicon),插件源目录里的清单和模板,宿主 `cebbe0def`(1lck/Lithe-IDEA#1958 的分支提交), -Go 1.27.4。`node scripts/e2e-host.mjs` 在 `internal/projectgen` 通过三个集成测试,经 Core 的表单、生成计划和宿主执行器: -`TestGoPluginGeneratesAModuleWithSampleCode`(`Hello-Go` 生成 `module hello-go`、`go 1.21`、`main.go`,`.gitignore` -忽略 `__debug_bin*`,打开 `main.go`,生成的模块能通过 `go vet` 并且 `go run` 输出 `Hello, Gopher!`)、 -`TestGoPluginGeneratesAnEmptyModule`(关闭示例代码,改模块路径和 Go 版本,只生成 `go.mod` 并打开它)和 -`TestGoPluginFormRejectsAModulePathWithSpaces`(`My App` 默认得到的模块路径被表单拒绝,改成合法路径后通过)。覆盖验证方法第 2 步里的 -文件、打开的文件和 `go run`,以及第 3、4、5 步;没有覆盖新建项目对话框的界面和图标(第 1 步)、创建后在构建窗口里的识别, -也没有做手工验收。 +**最近验证**:2026-11-15,macOS(Apple Silicon),插件源目录里的清单和模板,宿主 `b03dbf0c0`(1lck/Lithe-IDEA#1964 的分支提交:preview 1fc1e8b05 加上 +Core 6477e9a),Homebrew 的 Go 1.27.4。在宿主检出里运行 `internal/projectgen` 的 `^TestGoPlugin`,通过五个集成测试,经 Core 的表单、 +生成计划、宿主执行器和工具链解析: + +- `TestGoPluginToolDefinitionFindsTheLocalGo`:插件的 `go` 工具定义找到 `PATH` 里那个 go 的 GOROOT + (`/opt/homebrew/Cellar/go/1.27.4/libexec`),版本与 `go env GOVERSION` 一致。 +- `TestGoPluginGeneratesAModuleWithSampleCode`:用找到的 Go 填 GOROOT,`Hello-Go` 生成 `module hello-go` 和 + `go 1.27.4`、`main.go`,`.gitignore` 忽略 `__debug_bin*`,打开 `main.go`;生成计划带 `goroot` 的项目固定, + 保存后工具链把项目里的 `go` 解析到这个 GOROOT,用它 `go vet` 通过、`go run` 输出 `Hello, Gopher!`。 +- `TestGoPluginGeneratesAnEmptyModuleWithoutAGoroot`:没有 Go 时手填 Go 版本,关闭示例代码、改模块路径, + 只生成 `go.mod` 并打开它,没有项目固定。 +- `TestGoPluginGoVersionFollowsTheGoroot`:没有 Go 或只有低于 1.21 的 Go 时 GOROOT 留空、Go 版本必填; + Go 版本默认取最新的 GOROOT,换 GOROOT 后跟着变,手动改过后保留;手动选低于 1.21 的 GOROOT 时表单报错。 +- `TestGoPluginFormRejectsAModulePathWithSpaces`:`My App` 默认得到的模块路径被表单拒绝,改成合法路径后通过。 + +覆盖验证方法第 2 步里的文件、打开的文件、项目固定和 `go run`,以及第 3、4、5、6 步的表单和生成结果; +没有覆盖新建项目对话框的界面和图标(第 1 步)、GOROOT 下拉的显示、创建后在构建窗口里的识别,也没有做手工验收。 **验证方法**(macOS): 1. 安装插件包,打开「新建项目」:左侧出现 Go,图标在浅色和深色外观下都清楚。 -2. 名称填 `Hello-Go`,保持默认创建:项目里有 `go.mod`(`module hello-go`、`go 1.21`)、`.gitignore` 和 `main.go`, - 创建后打开 `main.go`;构建窗口识别出 Go Modules,运行入口输出 `Hello, Gopher!`。 +2. GOROOT 下拉列出电脑上的 Go,默认选中版本最新的一个。名称填 `Hello-Go`,保持默认创建:项目里有 `go.mod` + (`module hello-go`,`go` 行是所选 Go 的版本)、`.gitignore` 和 `main.go`,创建后打开 `main.go`;构建窗口识别出 + Go Modules,运行入口输出 `Hello, Gopher!`;「构建、执行、部署 › 工具链」显示项目固定了这个 Go。 3. 关闭“添加示例代码”再创建:没有 `main.go`,创建后打开 `go.mod`。 4. 名称里有空格(如 `My App`)时,模块路径显示问题,改成合法路径后才能创建。 -5. 展开高级选项修改 Go 版本,`go.mod` 的 `go` 行随之改变。 +5. 换一个 GOROOT,高级选项里的 Go 版本跟着变;手动修改 Go 版本后再换 GOROOT,Go 版本保持手动填写的值, + `go.mod` 的 `go` 行是这个值。 +6. 电脑上没有 Go(或只有低于 1.21 的 Go)时 GOROOT 留空,高级选项自动展开并提示填写 Go 版本,填写后可以创建。 diff --git a/docs/releases/v0.1.0.md b/docs/releases/v0.1.0.md index cb569f5..21e32c5 100644 --- a/docs/releases/v0.1.0.md +++ b/docs/releases/v0.1.0.md @@ -2,7 +2,8 @@ 功能: - 调试:「调试」窗口里的 Go (Delve) 适配器用你电脑上的 `dlv dap` 调试当前文件所在的包,支持断点、单步、调用栈、变量和表达式求值;程序结束后会话自动结束,程序输出留在调试控制台。 -- 新建项目:「新建项目」对话框里的 Go 生成 `go.mod` 和 `.gitignore`,可选生成示例 `main.go`;可以填写模块路径(默认是小写的项目名)和 Go 版本(高级,默认 1.21)。不运行 `go mod init`,创建项目不需要联网。 +- 新建项目:「新建项目」对话框里的 Go 生成 `go.mod` 和 `.gitignore`,可选生成示例 `main.go`;可以选择 GOROOT(从电脑上找到的 Go 里选,默认最新的一个,创建后项目固定使用它),填写模块路径(默认是小写的项目名)和 Go 版本(高级,默认是所选 GOROOT 的版本)。不运行 `go mod init`,创建项目不需要联网;没有找到 Go 时 GOROOT 留空,Go 版本需要手动填写。 +- 工具链:插件声明 `go` 工具,Lithe 在 Homebrew、`/usr/local/go`、`~/sdk/go*` 等位置找到 Go 并读出版本,列在「构建、执行、部署 › 工具链」里。没有设置 Go executable 时,构建、检查、测试和运行使用项目固定的 Go,没有固定时依次使用全局默认、`GOROOT`、`PATH` 里的 `go` 和找到的最新安装。 - 插件设置的中文名称和说明(`l10n/zh-Hans.json`)。 权限:新增 `debug.launch`(启动 Delve)和 `project.generate`(新建项目),原有 `languageServer.launch`、`process.build` 不变。 @@ -10,7 +11,7 @@ 依赖的程序:调试需要 `PATH` 里的 `dlv`(`go install github.com/go-delve/delve/cmd/dlv@latest`);不调试可以不装。 兼容性: -- 需要固定了 Rust Core a58e07e 或更新版本、并能启动 `tcpAnnounced` 调试适配器的桌面端(1lck/Lithe-IDEA#1954)。更早的桌面端会拒绝安装本版本:它的 Core 不认识调试配置里的 `target.directory` 绑定。 +- 需要固定了 Rust Core 6477e9a 或更新版本、并能启动 `tcpAnnounced` 调试适配器的桌面端(1lck/Lithe-IDEA#1954、1lck/Lithe-IDEA#1964)。更早的桌面端会拒绝安装本版本:它的 Core 不认识调试配置里的 `target.directory` 绑定(Core a58e07e 起支持),也不接受以子命令开头的版本探针 `go version`(Core 6477e9a 起支持)。 - 新建项目的字段名称和调试适配器名称目前只有英文:插件语言文件还不能翻译这两类文字。 - 只能装进新版 Lithe 桌面端(`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。 - 本版本是预发布,Lithe Store 的自动追踪会跳过它。 diff --git a/e2e/host/desktop/internal/projectgen/go_integration_test.go b/e2e/host/desktop/internal/projectgen/go_integration_test.go index d92a556..6fb8f7b 100644 --- a/e2e/host/desktop/internal/projectgen/go_integration_test.go +++ b/e2e/host/desktop/internal/projectgen/go_integration_test.go @@ -2,20 +2,24 @@ package projectgen import ( "context" + "encoding/json" "os" "os/exec" "path/filepath" + "regexp" "slices" "strings" "testing" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) // The Go plugin's project generator, run through Core's form and plan and this // executor. It is an integration test: LITHE_PLUGIN_GO_DIR names the directory -// that holds the plugin's plugin.json, and the build check needs an installed go. +// that holds the plugin's plugin.json. The checks that build the module, and the +// ones that find this machine's Go, need an installed go. func goPluginDirectory(t *testing.T) (string, []byte) { t.Helper() directory := os.Getenv("LITHE_PLUGIN_GO_DIR") @@ -29,13 +33,57 @@ func goPluginDirectory(t *testing.T) (string, []byte) { return directory, manifest } -// generateGoModule runs the go-module generator for name with the given field -// values and returns the created project. -func generateGoModule(t *testing.T, ctx context.Context, name string, values map[string]any, edited []string) Result { +// goInstallation is one Go the plugin's tool definition found, with the +// provider the host records in a pin. +type goInstallation struct { + core.ProjectToolInstallation + Provider string +} + +// localGoInstallations lists the Go installations the plugin's "go" tool +// definition finds on this machine, the way New Project lists them for the +// GOROOT field: discovery in an empty directory, so no project pin applies. +func localGoInstallations(t *testing.T, ctx context.Context, manifest []byte) []goInstallation { + t.Helper() + snapshot, err := toolchain.Load(ctx, core.NewClient(), t.TempDir(), ".", []json.RawMessage{manifest}, toolchain.Options{}) + if err != nil { + t.Fatal(err) + } + var found []goInstallation + for _, tool := range snapshot.Tools { + if tool.ID != "go" { + continue + } + for _, installation := range tool.Installations { + found = append(found, goInstallation{ + ProjectToolInstallation: core.ProjectToolInstallation{ + Home: installation.Home, + Executable: installation.Executable, + Version: installation.Version, + }, + Provider: installation.Provider, + }) + } + } + return found +} + +func projectInstallations(found []goInstallation) []core.ProjectToolInstallation { + installations := make([]core.ProjectToolInstallation, 0, len(found)) + for _, installation := range found { + installations = append(installations, installation.ProjectToolInstallation) + } + return installations +} + +// generateGoModule runs the go-module generator with input and returns the plan +// and the created project. savePins, when set, records the plan's tool pins. +func generateGoModule(t *testing.T, ctx context.Context, input core.ProjectGeneratorFormInput, + savePins func(context.Context, string, core.ProjectGenerationPlan) error, +) (core.ProjectGenerationPlan, Result) { t.Helper() directory, manifest := goPluginDirectory(t) kernel := core.NewClient() - input := core.ProjectGeneratorFormInput{ProjectName: name, Values: values, Edited: edited} form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", input) if err != nil || !form.Valid { t.Fatalf("form = %+v, %v", form, err) @@ -47,34 +95,128 @@ func generateGoModule(t *testing.T, ctx context.Context, name string, values map if len(plan.Steps) == 0 { t.Fatalf("plan = %+v, want the template steps", plan) } - result := Run(ctx, Request{Parent: t.TempDir(), Name: name, Plan: plan, Kernel: kernel}) + result := Run(ctx, Request{Parent: t.TempDir(), Name: input.ProjectName, Plan: plan, Kernel: kernel, SavePins: savePins}) if result.Failure != nil { t.Fatalf("%v\n%s", result.Failure, result.Failure.Tail) } - return result + return plan, result } -// goCommand runs go in dir and returns what it printed. -func goCommand(t *testing.T, ctx context.Context, dir string, args ...string) string { +// goCommand runs the go executable in dir and returns what it printed. +func goCommand(t *testing.T, ctx context.Context, executable, dir string, args ...string) string { t.Helper() - command := exec.CommandContext(ctx, "go", args...) + command := exec.CommandContext(ctx, executable, args...) command.Dir = dir - // The module needs nothing from the network, and the build cache stays out of the user's. - command.Env = append(os.Environ(), "GOPROXY=off", "GOCACHE="+t.TempDir()) + // The module needs nothing from the network, the build cache stays out of the + // user's, and the chosen Go builds it instead of a downloaded toolchain. + command.Env = append(os.Environ(), "GOPROXY=off", "GOTOOLCHAIN=local", "GOCACHE="+t.TempDir()) output, err := command.CombinedOutput() if err != nil { - t.Fatalf("go %s failed: %v\n%s", strings.Join(args, " "), err, output) + t.Fatalf("%s %s failed: %v\n%s", executable, strings.Join(args, " "), err, output) } return string(output) } +// goEnvironment returns the GOROOT and release of the go on PATH. It skips the +// test when there is none, or when that go is a development build without a +// release number. +func goEnvironment(t *testing.T, ctx context.Context) (root, version string) { + t.Helper() + path, err := exec.LookPath("go") + if err != nil { + t.Skip("no go on PATH") + } + output, err := exec.CommandContext(ctx, path, "env", "GOROOT", "GOVERSION").Output() + if err != nil { + t.Fatalf("go env: %v", err) + } + lines := strings.Split(strings.TrimSpace(string(output)), "\n") + if len(lines) != 2 { + t.Fatalf("go env printed %q", output) + } + release := regexp.MustCompile(`^go(\d+(?:\.\d+)*)$`).FindStringSubmatch(strings.TrimSpace(lines[1])) + if release == nil { + t.Skipf("go on PATH is %q, not a release", lines[1]) + } + return strings.TrimSpace(lines[0]), release[1] +} + +func samePath(t *testing.T, a, b string) bool { + t.Helper() + resolvedA, errA := filepath.EvalSymlinks(a) + resolvedB, errB := filepath.EvalSymlinks(b) + return errA == nil && errB == nil && resolvedA == resolvedB +} + +func TestGoPluginToolDefinitionFindsTheLocalGo(t *testing.T) { + _, manifest := goPluginDirectory(t) + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + root, version := goEnvironment(t, ctx) + found := localGoInstallations(t, ctx, manifest) + for _, installation := range found { + if samePath(t, installation.Home, root) { + if installation.Version != version { + t.Fatalf("installation %+v, want version %s from go env GOVERSION", installation, version) + } + return + } + } + t.Fatalf("installations = %+v, want the GOROOT %s of the go on PATH", found, root) +} + func TestGoPluginGeneratesAModuleWithSampleCode(t *testing.T) { + _, manifest := goPluginDirectory(t) ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) defer cancel() - result := generateGoModule(t, ctx, "Hello-Go", nil, nil) + found := localGoInstallations(t, ctx, manifest) + local := len(found) > 0 + if !local { + // No Go on this machine: a listed installation still decides the go line. + home := t.TempDir() + found = []goInstallation{{ProjectToolInstallation: core.ProjectToolInstallation{ + Home: home, Executable: filepath.Join(home, "bin", "go"), Version: "1.22.3", + }}} + } + kernel := core.NewClient() + input := core.ProjectGeneratorFormInput{ + ProjectName: "Hello-Go", + Tools: map[string][]core.ProjectToolInstallation{"goroot": projectInstallations(found)}, + } + form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", input) + if err != nil { + t.Fatal(err) + } + // Without a choice the GOROOT field holds the newest installation. + var chosen goInstallation + for _, installation := range found { + if installation.Home == fieldState(form, "goroot").Value { + chosen = installation + } + } + if chosen.Home == "" { + t.Fatalf("goroot = %+v, want one of %+v", fieldState(form, "goroot"), found) + } + // The project records the chosen GOROOT the way New Project does. + savePins := func(ctx context.Context, root string, plan core.ProjectGenerationPlan) error { + var edits []toolchain.Edit + for _, pin := range plan.ToolPins { + edits = append(edits, toolchain.Edit{Tool: pin.Tool, Pin: &core.ToolchainPin{Home: pin.Home, Version: chosen.Version, Provider: chosen.Provider}}) + } + _, _, err := toolchain.SavePins(ctx, kernel, root, ".", edits, nil) + return err + } + if !local { + savePins = nil + } + plan, result := generateGoModule(t, ctx, input, savePins) goMod, err := os.ReadFile(filepath.Join(result.Path, "go.mod")) - if err != nil || string(goMod) != "module hello-go\n\ngo 1.21\n" { - t.Fatalf("go.mod = %q, %v; want the lowercased project name and the plugin's minimum Go", goMod, err) + if want := "module hello-go\n\ngo " + chosen.Version + "\n"; err != nil || string(goMod) != want { + t.Fatalf("go.mod = %q, %v; want %q: the lowercased project name and the chosen Go's version", goMod, err, want) + } + wantPins := []core.ProjectPlanToolPin{{Field: "goroot", Tool: "go", PinAs: "project", Home: chosen.Home, Executable: chosen.Executable}} + if !slices.Equal(plan.ToolPins, wantPins) { + t.Fatalf("tool pins = %+v, want %+v", plan.ToolPins, wantPins) } if _, err := os.Stat(filepath.Join(result.Path, "main.go")); err != nil { t.Fatalf("the sample program was not generated: %v", err) @@ -89,27 +231,40 @@ func TestGoPluginGeneratesAModuleWithSampleCode(t *testing.T) { if !slices.Equal(result.OpenFiles, []string{"main.go"}) { t.Fatalf("open files = %v, want main.go", result.OpenFiles) } - if _, err := exec.LookPath("go"); err != nil { + if !local { return } - goCommand(t, ctx, result.Path, "vet", "./...") - if output := goCommand(t, ctx, result.Path, "run", "."); output != "Hello, Gopher!\n" { + // The build resolves the go tool to the pinned GOROOT, and that Go builds the module. + selection, err := toolchain.Resolve(ctx, kernel, result.Path, ".", "go", "1.21", nil, []json.RawMessage{manifest}, toolchain.Options{}) + if err != nil || selection.Home == nil || !samePath(t, *selection.Home, chosen.Home) { + t.Fatalf("selection = %+v, %v; want the pinned GOROOT %s", selection, err, chosen.Home) + } + goCommand(t, ctx, selection.Executable, result.Path, "vet", "./...") + if output := goCommand(t, ctx, selection.Executable, result.Path, "run", "."); output != "Hello, Gopher!\n" { t.Fatalf("go run printed %q", output) } } -func TestGoPluginGeneratesAnEmptyModule(t *testing.T) { +func TestGoPluginGeneratesAnEmptyModuleWithoutAGoroot(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) defer cancel() - result := generateGoModule(t, ctx, "tool", map[string]any{ - "addSampleCode": false, - "modulePath": "github.com/example/tool", - "goVersion": "1.23", - }, []string{"addSampleCode", "modulePath", "goVersion"}) + // GOROOT is optional: with no Go found, a typed version still creates the module. + plan, result := generateGoModule(t, ctx, core.ProjectGeneratorFormInput{ + ProjectName: "tool", + Values: map[string]any{ + "addSampleCode": false, + "modulePath": "github.com/example/tool", + "goVersion": "1.23", + }, + Edited: []string{"addSampleCode", "modulePath", "goVersion"}, + }, nil) goMod, err := os.ReadFile(filepath.Join(result.Path, "go.mod")) if err != nil || string(goMod) != "module github.com/example/tool\n\ngo 1.23\n" { t.Fatalf("go.mod = %q, %v", goMod, err) } + if len(plan.ToolPins) != 0 { + t.Fatalf("tool pins = %+v, want none without a GOROOT", plan.ToolPins) + } if _, err := os.Stat(filepath.Join(result.Path, "main.go")); !os.IsNotExist(err) { t.Fatalf("main.go exists without sample code: %v", err) } @@ -118,14 +273,76 @@ func TestGoPluginGeneratesAnEmptyModule(t *testing.T) { } } +func TestGoPluginGoVersionFollowsTheGoroot(t *testing.T) { + _, manifest := goPluginDirectory(t) + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + kernel := core.NewClient() + base := t.TempDir() + install := func(name, version string) core.ProjectToolInstallation { + home := filepath.Join(base, name) + return core.ProjectToolInstallation{Home: home, Executable: filepath.Join(home, "bin", "go"), Version: version} + } + older, newer, tooOld := install("go1.22", "1.22.3"), install("go1.25", "1.25.0"), install("go1.20", "1.20.14") + evaluate := func(input core.ProjectGeneratorFormInput) core.ProjectGeneratorForm { + t.Helper() + input.ProjectName = "hello" + form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", input) + if err != nil { + t.Fatal(err) + } + return form + } + // The host sends an empty list, never null, for a tool it did not find. + tools := func(installations ...core.ProjectToolInstallation) map[string][]core.ProjectToolInstallation { + return map[string][]core.ProjectToolInstallation{"goroot": append([]core.ProjectToolInstallation{}, installations...)} + } + + // No Go found: GOROOT stays empty without a problem, and the version must be typed. + for _, found := range [][]core.ProjectToolInstallation{nil, {tooOld}} { + form := evaluate(core.ProjectGeneratorFormInput{Tools: tools(found...)}) + goroot, goVersion := fieldState(form, "goroot"), fieldState(form, "goVersion") + if form.Valid || goroot.Value != "" || goroot.Problem != "" || goVersion.Value != "" || goVersion.Problem != "required" { + t.Fatalf("found %v: form = %+v; want an empty optional GOROOT and a required Go version", found, form) + } + } + // The version starts as the newest Go's, then as the chosen one's. + form := evaluate(core.ProjectGeneratorFormInput{Tools: tools(older, newer)}) + if !form.Valid || fieldState(form, "goroot").Value != newer.Home || fieldState(form, "goVersion").Value != "1.25.0" { + t.Fatalf("form = %+v, want the newest GOROOT and its version", form) + } + form = evaluate(core.ProjectGeneratorFormInput{Values: map[string]any{"goroot": older.Home}, Tools: tools(older, newer)}) + if !form.Valid || fieldState(form, "goVersion").Value != "1.22.3" { + t.Fatalf("form = %+v, want the chosen GOROOT's version", form) + } + // A typed version stays when the GOROOT changes. + form = evaluate(core.ProjectGeneratorFormInput{ + Values: map[string]any{"goroot": older.Home, "goVersion": "1.21"}, + Edited: []string{"goVersion"}, + Tools: tools(older, newer), + }) + if !form.Valid || fieldState(form, "goVersion").Value != "1.21" { + t.Fatalf("form = %+v, want the typed version kept", form) + } + // A Go older than the plugin's minimum can be chosen but is reported. + form = evaluate(core.ProjectGeneratorFormInput{Values: map[string]any{"goroot": tooOld.Home}, Tools: tools(tooOld, newer)}) + if form.Valid || fieldState(form, "goroot").Problem == "" { + t.Fatalf("form = %+v, want a problem on a GOROOT below Go 1.21", form) + } +} + func TestGoPluginFormRejectsAModulePathWithSpaces(t *testing.T) { _, manifest := goPluginDirectory(t) ctx, cancel := context.WithTimeout(t.Context(), time.Minute) defer cancel() kernel := core.NewClient() + home := t.TempDir() + tools := map[string][]core.ProjectToolInstallation{ + "goroot": {{Home: home, Executable: filepath.Join(home, "bin", "go"), Version: "1.24.2"}}, + } // The module path follows the project name until it is edited, and a space is // not valid in one. - form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", core.ProjectGeneratorFormInput{ProjectName: "My App"}) + form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", core.ProjectGeneratorFormInput{ProjectName: "My App", Tools: tools}) if err != nil { t.Fatal(err) } @@ -136,12 +353,13 @@ func TestGoPluginFormRejectsAModulePathWithSpaces(t *testing.T) { ProjectName: "My App", Values: map[string]any{"modulePath": "example.com/my-app"}, Edited: []string{"modulePath"}, + Tools: tools, }) if err != nil || !form.Valid { t.Fatalf("form = %+v, %v; want the edited module path accepted", form, err) } - if goVersion := fieldState(form, "goVersion"); goVersion.Value != "1.21" { - t.Fatalf("goVersion = %+v, want the default 1.21", goVersion) + if goVersion := fieldState(form, "goVersion"); goVersion.Value != "1.24.2" { + t.Fatalf("goVersion = %+v, want the GOROOT's version 1.24.2", goVersion) } } diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 76a7009..816511a 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": "cebbe0def689aed04385156143308e66733f8ed7", + "revision": "b03dbf0c02117f0d56b1a430e0d40b347ba9ddcc", "packages": { "./internal/projectgen": "^TestGoPlugin", "./internal/workbench": "^TestOfficialGoPlugin(BuildsAndServesAModule|DebugsAModuleWithDelve)$" diff --git a/io.github.lithe-idea.go-support/plugin.json b/io.github.lithe-idea.go-support/plugin.json index ff49eb5..22c07b8 100644 --- a/io.github.lithe-idea.go-support/plugin.json +++ b/io.github.lithe-idea.go-support/plugin.json @@ -10,7 +10,8 @@ "languageServers": 0, "languages": 0, "projectGenerators": 0, - "settings": 0 + "settings": 0, + "toolDefinitions": 0 }, "vendor": { "id": "io.github.lithe-idea", @@ -174,6 +175,11 @@ "kind": "setting", "settingID": "goExecutable" }, + { + "id": "toolchain", + "kind": "toolchain", + "toolchainID": "go" + }, { "id": "path", "kind": "runtime", @@ -452,6 +458,214 @@ } } ], + "toolDefinitions": [ + { + "id": "go", + "displayName": "Go", + "icon": { + "host": "plugin" + }, + "executableLayouts": [ + { + "path": "bin/go", + "platforms": [ + "macos", + "linux" + ] + }, + { + "path": "bin/go.exe", + "platforms": [ + "windows" + ] + } + ], + "executables": [ + { + "id": "pinned", + "kind": "setting", + "settingID": "executable", + "layer": "project" + }, + { + "id": "project-request", + "kind": "toolchain", + "scope": "project" + }, + { + "id": "default", + "kind": "setting", + "settingID": "executable", + "layer": "global" + }, + { + "id": "global-request", + "kind": "toolchain", + "scope": "global" + }, + { + "id": "home", + "kind": "environment", + "variable": "GOROOT", + "path": "bin/go", + "platforms": [ + "macos", + "linux" + ] + }, + { + "id": "home-windows", + "kind": "environment", + "variable": "GOROOT", + "path": "bin/go.exe", + "platforms": [ + "windows" + ] + }, + { + "id": "shell", + "kind": "command", + "command": "go" + }, + { + "id": "detected", + "kind": "toolchain", + "scope": "installed" + } + ], + "version": { + "arguments": [ + "version" + ], + "pattern": "go version (?:devel )?go(\\d+(?:\\.\\d+)*)" + }, + "discovery": [ + { + "root": { + "kind": "absolute", + "path": "/usr/local" + }, + "pattern": "go", + "platforms": [ + "macos", + "linux" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/opt/homebrew/Cellar" + }, + "pattern": "go/*/libexec", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/opt/homebrew/Cellar" + }, + "pattern": "go@*/*/libexec", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/local/Cellar" + }, + "pattern": "go/*/libexec", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/local/Cellar" + }, + "pattern": "go@*/*/libexec", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/home/linuxbrew/.linuxbrew/Cellar" + }, + "pattern": "go/*/libexec", + "platforms": [ + "linux" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/lib" + }, + "pattern": "go", + "platforms": [ + "linux" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/lib" + }, + "pattern": "go-*", + "platforms": [ + "linux" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files" + }, + "pattern": "Go", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "home" + }, + "pattern": "scoop/apps/go/*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "home" + }, + "pattern": "sdk/go*" + }, + { + "root": { + "kind": "home" + }, + "pattern": "go/go*" + } + ], + "homeVariable": "GOROOT", + "commands": [ + "go" + ], + "pathPrepend": [ + "${home}/bin" + ], + "launch": [ + "${executable}", + "${arguments}" + ] + } + ], "projectGenerators": [ { "id": "go-module", @@ -464,6 +678,16 @@ "mode": "original" }, "fields": [ + { + "id": "goroot", + "type": "tool", + "title": "GOROOT", + "description": "The Go installation the project builds and runs with. The project keeps this choice.", + "tool": "go", + "minimumVersion": "1.21", + "pinAs": "project", + "optional": true + }, { "id": "addSampleCode", "type": "boolean", @@ -483,9 +707,9 @@ "id": "goVersion", "type": "text", "title": "Go version", - "description": "The go line of go.mod: the oldest Go release the module needs. A newer Go builds it too.", + "description": "The go line of go.mod: the oldest Go release the module needs. It starts as the version of the GOROOT above; a newer Go builds the module too.", "advanced": true, - "default": "1.21", + "default": "${field.goroot.version}", "pattern": "1\\.[0-9]+(\\.[0-9]+)?", "maxLength": 16 }