From 4751afd68c5ae3dce9337d8f1f5c6b1ffd7a82eb Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:47:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=94=A8=20Delve=20=E8=B0=83=E8=AF=95?= =?UTF-8?q?=20Go=20=E5=8C=85=EF=BC=8C=E6=96=B0=E5=BB=BA=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E9=87=8C=E5=8A=A0=E5=85=A5=20Go=20=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - debugAdapters[delve]:启动 PATH 里的 dlv dap,传输方式 tcpAnnounced, 从 stdout 读取 DAP 地址公告;program 绑定 target.directory(当前文件所在的包)。 - projectGenerators[go-module]:新建项目左侧的 Go,只写 go.mod、.gitignore 和可选的 main.go,不运行 go mod init,创建时不需要联网或安装 go。 - 插件版本 0.1.0,v0.1.0 发成预发布;新增 l10n/zh-Hans.json 翻译插件设置。 - e2e/host:固定宿主 cebbe0def(1lck/Lithe-IDEA#1958),新增 Delve 调试端到端测试 和生成器集成测试;构建输出改从运行控制台读取。 - 功能矩阵新增 go-debug-delve、go-project-generator。 --- .github/workflows/release.yml | 4 +- README.md | 70 ++++++-- docs/feature-matrix.md | 81 ++++++++- docs/releases/v0.1.0.md | 16 ++ .../projectgen/go_integration_test.go | 155 +++++++++++++++++ .../official_go_plugin_debug_e2e_test.go | 163 ++++++++++++++++++ .../workbench/official_go_plugin_e2e_test.go | 13 +- e2e/host/lithe-host.json | 10 +- .../icons/go-project.svg | 4 + .../l10n/zh-Hans.json | 35 ++++ io.github.lithe-idea.go-support/plugin.json | 142 ++++++++++++++- .../templates/go/module/dot-gitignore | 18 ++ .../templates/go/module/go.mod | 3 + .../templates/go/sample/main.go | 8 + 14 files changed, 698 insertions(+), 24 deletions(-) create mode 100644 docs/releases/v0.1.0.md create mode 100644 e2e/host/desktop/internal/projectgen/go_integration_test.go create mode 100644 e2e/host/desktop/internal/workbench/official_go_plugin_debug_e2e_test.go create mode 100644 io.github.lithe-idea.go-support/icons/go-project.svg create mode 100644 io.github.lithe-idea.go-support/l10n/zh-Hans.json create mode 100644 io.github.lithe-idea.go-support/templates/go/module/dot-gitignore create mode 100644 io.github.lithe-idea.go-support/templates/go/module/go.mod create mode 100644 io.github.lithe-idea.go-support/templates/go/sample/main.go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7df4d3e..54fe7eb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,7 +30,9 @@ jobs: GH_TOKEN: ${{ github.token }} # v0.0.1 follows plugin contract v0, which only the new desktop # client installs, and that client ships as desktop-v* pre-releases. - PRERELEASE_TAGS: v0.0.1 + # v0.1.0's Delve adapter needs the host's tcpAnnounced transport, + # which no desktop release has yet. + PRERELEASE_TAGS: v0.0.1 v0.1.0 run: | prerelease=false for tag in $PRERELEASE_TAGS; do diff --git a/README.md b/README.md index 3c76bd5..155b499 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,19 @@ 为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Go 支持:用你电脑上的 `gopls` 提供代码智能, 用声明式构建系统接口(`buildSystems`)识别 Go 模块,在构建窗口里列出包,运行 `go build`、`go vet`、 -`go test` 和 `go run`,查看模块依赖。 -这是一个**社区插件**,按插件契约 v0 编写。插件只有一份 `plugin.json`,不附带任何可执行文件,也没有后端进程。 +`go test` 和 `go run`,查看模块依赖;用你电脑上的 Delve(`dlv`)调试,在「新建项目」里创建 Go 模块。 +这是一个**社区插件**,按插件契约 v0 编写。插件只有一份 `plugin.json` 和几份项目模板,不附带任何可执行文件, +也没有后端进程。 -> English: Go support for Lithe — code intelligence through your own `gopls`, and the Go Modules build system -> (package model, build, vet, test, run and the module list) through the declarative `buildSystems` contract. -> The plugin is a single `plugin.json` with no executables and no backend process. +> English: Go support for Lithe — code intelligence through your own `gopls`, the Go Modules build system +> (package model, build, vet, test, run and the module list) through the declarative `buildSystems` contract, +> debugging through your own Delve, and a Go module entry in New Project. +> The plugin is a `plugin.json` and a few project templates, with no executables and no backend process. > **预发布**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 -> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。 +> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。0.1.0 的调试需要宿主支持 `tcpAnnounced` 调试适配器 +> ([1lck/Lithe-IDEA#1954](https://github.com/1lck/Lithe-IDEA/pull/1954)),在包含它的桌面端版本发布前, +> 这个版本只作为预发布提供。 ## 功能 @@ -24,6 +28,8 @@ | 诊断 | 把 `文件:行:列: 消息` 形式的编译输出显示为问题 | | 依赖 | `go list -m -json all` 列出模块依赖(含版本和是否间接依赖) | | 同步 | `go.mod`、`go.sum`、`go.work` 变化后重新读取模块 | +| 调试 | 「调试」窗口里选 Go (Delve),调试当前打开的 `.go` 文件所在的包:断点、单步、调用栈、变量和表达式求值,程序输出显示在调试控制台 | +| 新建项目 | 「新建项目」里的 Go:生成 `go.mod`、`.gitignore`,可选生成示例 `main.go`;模块路径默认是小写的项目名 | ## 设置和构建选项 @@ -49,22 +55,50 @@ 选项会加到构建、检查、测试和运行的命令里。 +## 调试 + +打开「调试」窗口,适配器选 **Go (Delve)**,打开要调试的 `.go` 文件,在行号旁设好断点后点「开始」。 + +- 调试的是当前文件所在的包:Delve 先构建这个包,再在断点处停下。所以要调试 `cmd/server` 的程序, + 打开 `cmd/server` 里的任意文件即可。 +- 程序的工作目录是项目根目录。 +- 程序结束后会话自动结束,程序的输出留在调试控制台里。 +- Delve 在项目根目录生成名为 `__debug_bin…` 的临时程序,会话结束时自己删除;新建项目生成的 `.gitignore` + 已经忽略它。 +- 目前只支持启动调试(launch),不支持附加到运行中的进程,也不支持调试测试。 + +## 新建项目 + +「新建项目」对话框左侧有 **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.mod` 由模板直接写出,不运行 `go mod init`,所以创建项目不需要联网,也不依赖 `go` 的安装位置。 +这些字段目前只有英文名称:插件语言文件还不能翻译新建项目的字段。 + ## 依赖的程序 | 程序 | 用途 | 查找方式 | | --- | --- | --- | | `go` 1.21 或更新版本 | 读取模块、构建、检查、测试、运行、依赖 | 插件设置 Go executable;留空时找 `PATH` 里的 `go` | | `gopls` | 代码智能 | `PATH` 里的 `gopls` | +| `dlv`(Delve,需要有 `dlv dap` 命令,已用 1.27.2 验证) | 调试 | `PATH` 里的 `dlv`;Delve 构建程序时用 `PATH` 里的 `go` | -安装插件时 Lithe 会列出这些程序和插件需要的权限(启动语言服务器、运行构建命令),确认后才会安装。 -没有这两个程序的话可以先安装: +安装插件时 Lithe 会列出这些程序和插件需要的权限(启动语言服务器、运行构建命令、启动调试器、创建项目), +确认后才会安装。没有这些程序的话可以先安装: ```bash brew install go go install golang.org/x/tools/gopls@latest +go install github.com/go-delve/delve/cmd/dlv@latest ``` -`go install` 把 gopls 装在 `$(go env GOPATH)/bin`,这个目录需要在 Lithe 能看到的 `PATH` 里。 +`go install` 把 gopls 和 dlv 装在 `$(go env GOPATH)/bin`,这个目录需要在 Lithe 能看到的 `PATH` 里。 +不调试的话可以不装 dlv。 ## 安装 @@ -80,13 +114,21 @@ go install golang.org/x/tools/gopls@latest - 运行入口由 Lithe 从模型里的 `main` 包生成:每个带 `application` 标签的包一条,名称是导入路径的最后一段。 - gopls 由 Lithe 按 `languageServers` 的声明启动,插件设置通过 `workspaceConfiguration` 里的 `${setting:}` 传给它。 +- Delve 由 Lithe 按 `debugAdapters` 的声明启动为 `dlv dap`。Delve 在标准输出打印 + `DAP server listening at: <地址>`,Lithe 读到这一行后连接这个本机地址(`tcpAnnounced` 传输)。 + 调试的包由当前文件所在目录决定(`target.directory` 绑定到 Delve 的 `program`)。 +- 新建项目由 `projectGenerators` 声明,Lithe 把 `templates/go/` 里的模板展开到新目录; + 模板名以 `dot-` 开头的文件生成为点文件。 - 插件目录在运行时保持只读。 ## 诊断日志 插件没有自己的进程,也不发送 `lithe/log`。gopls 由 Lithe 启动,它的启动结果、`window/logMessage` 和有界的 stderr 由 Lithe 记进语言服务的日志;`go` 命令的输出显示在构建输出里,不复制进诊断日志。 -排障时使用 Lithe 的日志窗口和诊断导出,不要开启 gopls 的 RPC dump,也不要把源码、环境变量或完整命令行写进日志。 +Delve 也由 Lithe 启动:每次调试的适配器启动结果(解析、启动、超时、退出、initialize 失败或成功)由 Lithe +记在插件的日志通道里;Delve 和被调试程序的输出显示在调试控制台里,不复制进诊断日志。 +排障时使用 Lithe 的日志窗口和诊断导出,不要开启 gopls 的 RPC dump 或 Delve 的 `--log`, +也不要把源码、环境变量或完整命令行写进日志。 ## 本地打包 @@ -111,11 +153,11 @@ node scripts/package.mjs ([1lck/Lithe-IDEA#1915](https://github.com/1lck/Lithe-IDEA/pull/1915))移到这里:主仓库不读取本仓库, `e2e/host/lithe-host.json` 记录测试最后一次通过时的宿主版本。 -需要 Node.js 22+、Go、Rust 工具链(构建宿主固定的 Rust Core)、`git`,以及测试要用的 `go` 和 `gopls`: +需要 Node.js 22+、Go、Rust 工具链(构建宿主固定的 Rust Core)、`git`,以及测试要用的 `go`、`gopls` 和 `dlv`: ```bash node scripts/package.mjs -LITHE_TEST_GO_PLUGIN_ARCHIVE="$PWD/dist/go-support-0.0.1-darwin.zip" node scripts/e2e-host.mjs +LITHE_TEST_GO_PLUGIN_ARCHIVE="$PWD/dist/go-support-0.1.0-darwin.zip" node scripts/e2e-host.mjs ``` 插件包路径要写绝对路径。脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`, @@ -135,12 +177,12 @@ Lithe 主仓库的功能矩阵不收录插件能力,改动插件行为时在 2. 推送同名标签: ```bash - git tag v0.0.1 && git push origin v0.0.1 + git tag v0.1.0 && git push origin v0.1.0 ``` 3. `Release` 工作流会核对标签与版本一致、打包并发布 Release(说明里附 SHA-256 和 `docs/releases/v<版本>.md`)。`release.yml` 里 `PRERELEASE_TAGS` 列出的版本会标为预发布版本: - 目前是只能装进新版桌面端的 `v0.0.1`。 + 目前是只能装进新版桌面端的 `v0.0.1`,以及调试依赖宿主 #1954 的 `v0.1.0`。 4. Lithe Store 的自动追踪会发现稳定版本并开合并请求,合并后用户即可在 Lithe 中更新。自动追踪会跳过预发布版本; 需要收录时在 Store 中手工提交条目,并使用已发布 ZIP 的实际 SHA-256。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index ab90753..4069c46 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -20,7 +20,9 @@ | ID | 能力 | macOS | Windows | 最近验证 | | --- | --- | --- | --- | --- | -| `go-support-plugin` | gopls 代码智能、Go Modules 构建、运行与 `go test` | implemented / pending | missing / not-applicable | 2026-11-14 macOS 宿主端到端测试通过 | +| `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-support-plugin @@ -43,7 +45,7 @@ 的 `pluginhost.go` 开头列出了这些能力的服务范围;语言服务器的 code action、signature help 和 inlay hints 宿主还没有界面,插件声明了也不会显示。 -**最近验证**:2026-11-14,macOS(Apple Silicon),插件 0.0.1 发布包,宿主 `059d878d4`。 +**最近验证**:2026-11-15,macOS(Apple Silicon),插件 0.1.0 发布包,宿主 `cebbe0def`(1lck/Lithe-IDEA#1958 的分支提交)。 `node scripts/e2e-host.mjs` 通过 `TestOfficialGoPluginBuildsAndServesAModule`,覆盖识别 `go.mod`、`go list` 模型和 `application` 目标、Build、Vet、运行入口、Go executable 设置重新读取模型并用于后续构建、gopls 诊断、 gofumpt 设置立即生效,以及工作流结束后安装目录逐字节不变。没有覆盖 `go test`、依赖列表、`go.mod` 变化后重新读取、 @@ -67,3 +69,78 @@ gofumpt 设置立即生效,以及工作流结束后安装目录逐字节不变 在 #1915 中删除。原条目写的是旧 Swift 宿主上官方包 `dev.lithe.plugin.go-support` 迁移到社区版 0.1.0 的流程, 以及 Viva 宿主当时还没有运行和测试入口的状态。插件已按契约 v0 重写并从 0.0.1 重新发布,宿主也已经支持 `buildSystems` 的运行和测试,这两部分不再适用,本条按当前插件重写。 + +## go-debug-delve + +**能力**:「调试」窗口里的 Go (Delve) 适配器。Lithe 启动用户 `PATH` 里的 `dlv dap`,读到 Delve 在标准输出打印的 +`DAP server listening at: <地址>` 后连接这个本机地址;调试当前文件所在的包(`target.directory` 绑定到 `program`), +工作目录是项目根目录。支持断点、单步、调用栈、变量和表达式求值,程序输出显示在调试控制台,程序结束后会话自动结束。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | implemented | pending | 需要宿主支持 `tcpAnnounced` 调试适配器(1lck/Lithe-IDEA#1954)、Rust Core a58e07e 或更新版本的 `target.directory` 绑定,以及宿主按工作目录设置子进程 `PWD`(1lck/Lithe-IDEA#1958;没有它时,项目路径经过符号链接的话 Delve 编译会失败) | +| Windows | missing | not-applicable | 没有 Windows 包 | + +**证据**: + +- `io.github.lithe-idea.go-support/plugin.json`:`debugAdapters` 里的 `delve`,以及 `debug.launch` 权限和 `onDebug:delve` 激活事件。 +- `e2e/host/desktop/internal/workbench/official_go_plugin_debug_e2e_test.go`:宿主端到端测试。 + +**依赖的宿主能力**:`debugAdapters` 的 `tcpAnnounced` 传输(宿主启动适配器进程,交给 Core 判断哪一行是地址公告, +再连接公告的本机端口)、`target.directory` 绑定(Core a58e07e,Lithe-core-rust#47)。 + +**限制**:只支持 launch,不支持 attach 和调试测试;适配器只在打开 `.go` 文件时可选(选择器是 `file` 加 `go` 语言), +从构建窗口的运行入口启动调试还不支持。Delve 在项目根目录生成 `__debug_bin…` 临时程序,会话结束时删除。 +适配器名称 Go (Delve) 目前不能翻译:插件语言文件还不覆盖调试适配器。 + +**最近验证**:2026-11-15,macOS(Apple Silicon),插件 0.1.0 发布包,宿主 `cebbe0def`(1lck/Lithe-IDEA#1958 的分支提交), +Go 1.27.4、Delve 1.27.2。`node scripts/e2e-host.mjs` 通过 `TestOfficialGoPluginDebugsAModuleWithDelve`,覆盖下面验证方法的 +第 2 步、第 3 步的断点停下、调用栈顶和局部变量、第 4 步和第 7 步,并确认 Delve 的地址公告没有显示在调试控制台里。 +没有覆盖安装对话框里的权限(第 1 步)、单步和表达式求值、调试子包(第 5 步)、缺少 `dlv` 时的提示(第 6 步),也没有做手工验收。 + +**验证方法**(macOS): + +1. 安装插件包,确认安装对话框列出启动调试器权限;`PATH` 里有 `dlv`。 +2. 打开含 `go.mod` 的项目,打开 `main.go`,在一行上设断点,在「调试」窗口选 Go (Delve) 后点「开始」。 +3. 程序停在断点:调用栈顶是 `main.main` 和断点所在行,变量里能看到局部变量的值;单步、表达式求值可用。 +4. 点「继续」:程序运行到结束,输出显示在调试控制台,会话自动结束,项目根目录里没有留下 `__debug_bin…`。 +5. 调试 `cmd/<名字>` 这样的子包:打开该包里的文件后开始,调试的是这个包。 +6. `PATH` 里没有 `dlv` 时,开始调试给出缺少程序的提示,不崩溃。 +7. 整个过程中插件安装目录不被写入。 + +## go-project-generator + +**能力**:「新建项目」对话框里的 Go。生成 `go.mod`(`module` 行是模块路径,默认是小写的项目名;`go` 行默认 1.21) +和 `.gitignore`,可选生成打印 `Hello, Gopher!` 的示例 `main.go`。`go.mod` 由模板写出,不运行 `go mod init`, +创建项目不需要联网,也不需要 `go`。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | implemented | pending | | +| Windows | missing | not-applicable | 没有 Windows 包 | + +**证据**: + +- `io.github.lithe-idea.go-support/plugin.json`:`projectGenerators` 里的 `go-module`,以及 `project.generate` 权限。 +- `io.github.lithe-idea.go-support/templates/go/`:模块和示例代码模板。 +- `e2e/host/desktop/internal/projectgen/go_integration_test.go`:经 Core 的表单、生成计划和宿主执行器的集成测试。 + +**限制**:字段名称和说明目前只有英文,插件语言文件还不覆盖新建项目。 + +**最近验证**: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 步)、创建后在构建窗口里的识别, +也没有做手工验收。 + +**验证方法**(macOS): + +1. 安装插件包,打开「新建项目」:左侧出现 Go,图标在浅色和深色外观下都清楚。 +2. 名称填 `Hello-Go`,保持默认创建:项目里有 `go.mod`(`module hello-go`、`go 1.21`)、`.gitignore` 和 `main.go`, + 创建后打开 `main.go`;构建窗口识别出 Go Modules,运行入口输出 `Hello, Gopher!`。 +3. 关闭“添加示例代码”再创建:没有 `main.go`,创建后打开 `go.mod`。 +4. 名称里有空格(如 `My App`)时,模块路径显示问题,改成合法路径后才能创建。 +5. 展开高级选项修改 Go 版本,`go.mod` 的 `go` 行随之改变。 diff --git a/docs/releases/v0.1.0.md b/docs/releases/v0.1.0.md new file mode 100644 index 0000000..cb569f5 --- /dev/null +++ b/docs/releases/v0.1.0.md @@ -0,0 +1,16 @@ +0.1.0 加入 Delve 调试和新建 Go 项目。 + +功能: +- 调试:「调试」窗口里的 Go (Delve) 适配器用你电脑上的 `dlv dap` 调试当前文件所在的包,支持断点、单步、调用栈、变量和表达式求值;程序结束后会话自动结束,程序输出留在调试控制台。 +- 新建项目:「新建项目」对话框里的 Go 生成 `go.mod` 和 `.gitignore`,可选生成示例 `main.go`;可以填写模块路径(默认是小写的项目名)和 Go 版本(高级,默认 1.21)。不运行 `go mod init`,创建项目不需要联网。 +- 插件设置的中文名称和说明(`l10n/zh-Hans.json`)。 + +权限:新增 `debug.launch`(启动 Delve)和 `project.generate`(新建项目),原有 `languageServer.launch`、`process.build` 不变。 + +依赖的程序:调试需要 `PATH` 里的 `dlv`(`go install github.com/go-delve/delve/cmd/dlv@latest`);不调试可以不装。 + +兼容性: +- 需要固定了 Rust Core a58e07e 或更新版本、并能启动 `tcpAnnounced` 调试适配器的桌面端(1lck/Lithe-IDEA#1954)。更早的桌面端会拒绝安装本版本:它的 Core 不认识调试配置里的 `target.directory` 绑定。 +- 新建项目的字段名称和调试适配器名称目前只有英文:插件语言文件还不能翻译这两类文字。 +- 只能装进新版 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 new file mode 100644 index 0000000..d92a556 --- /dev/null +++ b/e2e/host/desktop/internal/projectgen/go_integration_test.go @@ -0,0 +1,155 @@ +package projectgen + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// 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. +func goPluginDirectory(t *testing.T) (string, []byte) { + t.Helper() + directory := os.Getenv("LITHE_PLUGIN_GO_DIR") + if directory == "" { + t.Skip("LITHE_PLUGIN_GO_DIR is not set") + } + manifest, err := os.ReadFile(filepath.Join(directory, "plugin.json")) + if err != nil { + t.Fatal(err) + } + 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 { + 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) + } + plan, err := kernel.ProjectGenerationPlanOf(ctx, manifest, "go-module", directory, input) + if err != nil { + t.Fatal(err) + } + 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}) + if result.Failure != nil { + t.Fatalf("%v\n%s", result.Failure, result.Failure.Tail) + } + return result +} + +// goCommand runs go in dir and returns what it printed. +func goCommand(t *testing.T, ctx context.Context, dir string, args ...string) string { + t.Helper() + command := exec.CommandContext(ctx, "go", 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()) + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("go %s failed: %v\n%s", strings.Join(args, " "), err, output) + } + return string(output) +} + +func TestGoPluginGeneratesAModuleWithSampleCode(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + result := generateGoModule(t, ctx, "Hello-Go", nil, nil) + 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 _, err := os.Stat(filepath.Join(result.Path, "main.go")); err != nil { + t.Fatalf("the sample program was not generated: %v", err) + } + ignore, err := os.ReadFile(filepath.Join(result.Path, ".gitignore")) + if err != nil || !strings.Contains(string(ignore), "__debug_bin*") { + t.Fatalf(".gitignore = %q, %v; want the dot- template renamed and Delve's binary ignored", ignore, err) + } + if _, err := os.Stat(filepath.Join(result.Path, "dot-gitignore")); !os.IsNotExist(err) { + t.Fatalf("dot-gitignore was copied under its template name: %v", err) + } + 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 { + return + } + goCommand(t, ctx, result.Path, "vet", "./...") + if output := goCommand(t, ctx, result.Path, "run", "."); output != "Hello, Gopher!\n" { + t.Fatalf("go run printed %q", output) + } +} + +func TestGoPluginGeneratesAnEmptyModule(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"}) + 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 _, err := os.Stat(filepath.Join(result.Path, "main.go")); !os.IsNotExist(err) { + t.Fatalf("main.go exists without sample code: %v", err) + } + if !slices.Equal(result.OpenFiles, []string{"go.mod"}) { + t.Fatalf("open files = %v, want go.mod", result.OpenFiles) + } +} + +func TestGoPluginFormRejectsAModulePathWithSpaces(t *testing.T) { + _, manifest := goPluginDirectory(t) + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + kernel := core.NewClient() + // 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"}) + if err != nil { + t.Fatal(err) + } + if form.Valid || fieldState(form, "modulePath").Problem == "" { + t.Fatalf("form = %+v, want a problem on modulePath", form) + } + form, err = kernel.ProjectGeneratorFormOf(ctx, manifest, "go-module", core.ProjectGeneratorFormInput{ + ProjectName: "My App", + Values: map[string]any{"modulePath": "example.com/my-app"}, + Edited: []string{"modulePath"}, + }) + 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) + } +} + +func fieldState(form core.ProjectGeneratorForm, id string) core.ProjectFieldState { + for _, field := range form.Fields { + if field.ID == id { + return field + } + } + return core.ProjectFieldState{} +} diff --git a/e2e/host/desktop/internal/workbench/official_go_plugin_debug_e2e_test.go b/e2e/host/desktop/internal/workbench/official_go_plugin_debug_e2e_test.go new file mode 100644 index 0000000..5976dfd --- /dev/null +++ b/e2e/host/desktop/internal/workbench/official_go_plugin_debug_e2e_test.go @@ -0,0 +1,163 @@ +package workbench + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// goDebugSample is main.go of the debugged module. Zero-based line 6 is the +// Printf call, where main's local name already holds "Gopher". +const goDebugSample = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tname := \"Gopher\"\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n}\n" + +// samePath reports whether two paths name the same file, so a path Delve +// reports through a symbolic link (macOS's /var is /private/var) still matches. +func samePath(a, b string) bool { + resolvedA, errA := filepath.EvalSymlinks(a) + resolvedB, errB := filepath.EvalSymlinks(b) + return errA == nil && errB == nil && resolvedA == resolvedB +} + +// debugBinaries lists the programs Delve built in dir for a debug session. +func debugBinaries(t *testing.T, dir string) []string { + t.Helper() + matches, err := filepath.Glob(filepath.Join(dir, "__debug_bin*")) + if err != nil { + t.Fatal(err) + } + return matches +} + +// clickNamedWithoutSettling clicks the named control of the current frame and paints +// the result once. The harness's clickNamed waits for every background task, which +// never happens while a language server runs, so the caller awaits the click's effect. +func clickNamedWithoutSettling(t *testing.T, h *harness, name string) { + t.Helper() + if err := h.driver.Pump(); err != nil { + t.Fatal(err) + } + point := center(h.pageHit(name).Bounds) + if err := h.driver.Click(point.X, point.Y); err != nil { + t.Fatal(err) + } + if err := h.driver.Pump(); err != nil { + t.Fatal(err) + } +} + +// TestOfficialGoPluginDebugsAModuleWithDelve covers the Delve adapter of the Go +// Support archive: the Debug window starts the user's dlv dap, the host reads the +// address Delve announces and connects, a breakpoint in main.go stops main.main +// with its local variable, Continue runs the program to its end and the session +// ends by itself, and Delve removes the program it built for the session. +func TestOfficialGoPluginDebugsAModuleWithDelve(t *testing.T) { + archive := os.Getenv("LITHE_TEST_GO_PLUGIN_ARCHIVE") + if archive == "" { + t.Skip("set LITHE_TEST_GO_PLUGIN_ARCHIVE to a go-support--darwin.zip") + } + for _, command := range []string{"go", "gopls", "dlv"} { + if _, err := exec.LookPath(command); err != nil { + t.Fatalf("%s is not on PATH: %v", command, err) + } + } + h := newHarness(t, &testKernel{Client: core.NewClient()}) + // Lithe asks Core for the stop time when its window opens, which the harness never + // does. Without it a stopped process is killed at once, and a killed Delve cannot + // remove the program it built. + previousGrace := buildprocess.StopGrace() + t.Cleanup(func() { buildprocess.SetStopGrace(previousGrace) }) + h.app.refreshStopGrace() + awaitStateWithin(t, h, 20*time.Second, "Core's stop time", func() bool { return buildprocess.StopGrace() > 0 }) + installed := installOfficialPluginArchive(t, h, archive, "io.github.lithe-idea.go-support") + before := packageDigest(t, installed) + h.app.reloadPluginLanguages() + root := t.TempDir() + writePluginFixture(t, root, map[string]string{ + "go.mod": "module example.com/hello\n\ngo 1.21\n", + "main.go": goDebugSample, + }) + p := openHostedPanel(t, h, root) + if declaration := p.debug.adapters[0].Declaration; declaration.Transport != "tcpAnnounced" || declaration.LaunchKind != "systemCommand" { + t.Fatalf("declaration = %+v, want Delve started as dlv dap and announcing its address", declaration) + } + // Opening main.go starts gopls, whose tasks run until the project closes, so from + // here on every step waits for its own state instead of for all background work. + source := filepath.Join(root, "main.go") + h.app.openFileAtPosition(p, source, 6, 0) + awaitStateWithin(t, h, 30*time.Second, "main.go with the caret on the Printf line", func() bool { + d := p.selectedDocument(p.docs.group) + if d == nil || !samePath(d.path, source) { + return false + } + line, _ := d.view.Caret() + return line == 6 + }) + clickNamedWithoutSettling(t, h, h.shared("native.viewBreakpoints")) + awaitStateWithin(t, h, 10*time.Second, "the Breakpoints dialog", func() bool { return p.panels.breakpointsOpen }) + clickNamedWithoutSettling(t, h, h.app.text.Debug.ToggleBreakpoint) + awaitStateWithin(t, h, 10*time.Second, "the breakpoint on main.go:7", func() bool { + for path, lines := range p.debug.breakpoints { + if samePath(path, source) && len(lines) == 1 && lines[0].line == 7 { + return true + } + } + return false + }) + clickNamedWithoutSettling(t, h, h.shared("ui.done")) + awaitStateWithin(t, h, 10*time.Second, "the closed Breakpoints dialog", func() bool { return !p.panels.breakpointsOpen }) + + clickNamedWithoutSettling(t, h, h.app.text.Debug.Start) + // Delve builds the package before it runs it, so the first stop waits for a build. + awaitStateWithin(t, h, 2*time.Minute, "Delve to stop at the breakpoint", func() bool { + if p.debug.failure != "" { + t.Fatalf("debug start failed: %s\noutput: %q", p.debug.failure, p.debug.output) + } + return p.debug.state == "paused" && len(p.debug.frames) > 0 + }) + top := p.debug.frames[0] + if top.Name != "main.main" || top.Line != 7 || !samePath(top.SourcePath, source) { + t.Fatalf("top frame = %+v, want main.main at main.go:7", top) + } + // The locals open by themselves once the stop's scopes arrive. + awaitStateWithin(t, h, time.Minute, "main's local name in Variables", func() bool { + for _, scope := range p.debug.vars.scopes { + if scope.container == nil { + continue + } + for _, node := range scope.container.nodes { + if node.name == "name" && node.value == `"Gopher"` { + return true + } + } + } + return false + }) + // The announcement is how the host found Delve, not console output. + if output := strings.Join(p.debug.output, "\n"); strings.Contains(output, "DAP server listening at") { + t.Fatalf("the console shows Delve's announcement: %q", output) + } + + clickNamedWithoutSettling(t, h, h.app.text.Debug.Continue) + awaitStateWithin(t, h, time.Minute, "the program to end its session", func() bool { + return p.debug.activeSession() == nil && p.debug.state == "terminated" + }) + if output := strings.Join(p.debug.output, "\n"); !strings.Contains(output, "Hello, Gopher!") { + t.Fatalf("the console does not show the program's output: %q", output) + } + // The ended session closes Delve's connection and asks Delve to stop within the stop + // time; Delve then deletes the program it built, so nothing is left in the module. + awaitStateWithin(t, h, 30*time.Second, "Delve to remove its debug binary", func() bool { + return len(debugBinaries(t, root)) == 0 + }) + + h.app.closeProject() + awaitStateWithin(t, h, 30*time.Second, "the closed project", func() bool { return h.app.project == nil }) + h.settle() + assertPackageUnchanged(t, installed, before) +} diff --git a/e2e/host/desktop/internal/workbench/official_go_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/official_go_plugin_e2e_test.go index 781d962..ae7fa13 100644 --- a/e2e/host/desktop/internal/workbench/official_go_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/official_go_plugin_e2e_test.go @@ -151,6 +151,15 @@ func awaitBuildModel(t *testing.T, h *harness, p *project, buildSystemID string, return instance } +// runConsoleText is the console of the Run window's shown session, which holds the +// output of the latest execution. +func runConsoleText(p *project) string { + if run := p.activeRun(); run != nil { + return run.output.all() + } + return "" +} + // runBuildTaskToEnd runs one task of the selected instance and waits for it to end. func runBuildTaskToEnd(t *testing.T, h *harness, p *project, projectID, taskID string, limit time.Duration) string { t.Helper() @@ -159,7 +168,7 @@ func runBuildTaskToEnd(t *testing.T, h *harness, p *project, projectID, taskID s t.Fatalf("start %s: %v", taskID, err) } awaitStateWithin(t, h, limit, "the "+taskID+" task", func() bool { return p.build.operation == nil }) - output := strings.Join(p.build.output, "") + output := runConsoleText(p) if p.build.status != h.app.text.Build.Succeeded { t.Fatalf("%s did not succeed: status=%q output=%q", taskID, p.build.status, output) } @@ -180,7 +189,7 @@ func runTargetEntryToEnd(t *testing.T, h *harness, p *project, instance *buildIn t.Fatalf("run %s did not start", entry.Name) } awaitStateWithin(t, h, limit, "the "+entry.Name+" run", func() bool { return p.build.operation == nil }) - output := strings.Join(p.build.output, "") + output := runConsoleText(p) if p.build.status != h.app.text.Build.Succeeded { t.Fatalf("run %s did not succeed: status=%q output=%q", entry.Name, p.build.status, output) } diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 7b8d487..76a7009 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,10 +1,14 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "059d878d4284e1a1fd218aeaa56c29d9753d4dfa", + "revision": "cebbe0def689aed04385156143308e66733f8ed7", "packages": { - "./internal/workbench": "^TestOfficialGoPluginBuildsAndServesAModule$" + "./internal/projectgen": "^TestGoPlugin", + "./internal/workbench": "^TestOfficialGoPlugin(BuildsAndServesAModule|DebugsAModuleWithDelve)$" }, "requiredEnvironment": { - "LITHE_TEST_GO_PLUGIN_ARCHIVE": "go-support--darwin.zip to install, for example dist/go-support-0.0.1-darwin.zip" + "LITHE_TEST_GO_PLUGIN_ARCHIVE": "go-support--darwin.zip to install, for example dist/go-support-0.1.0-darwin.zip" + }, + "repositoryEnvironment": { + "LITHE_PLUGIN_GO_DIR": "io.github.lithe-idea.go-support" } } diff --git a/io.github.lithe-idea.go-support/icons/go-project.svg b/io.github.lithe-idea.go-support/icons/go-project.svg new file mode 100644 index 0000000..e6cb3d1 --- /dev/null +++ b/io.github.lithe-idea.go-support/icons/go-project.svg @@ -0,0 +1,4 @@ + + + + diff --git a/io.github.lithe-idea.go-support/l10n/zh-Hans.json b/io.github.lithe-idea.go-support/l10n/zh-Hans.json new file mode 100644 index 0000000..041ab1e --- /dev/null +++ b/io.github.lithe-idea.go-support/l10n/zh-Hans.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/plugin-l10n.schema.json", + "settings": { + "goExecutable": { + "title": "Go 程序", + "description": "读取模块、构建、检查、测试和运行时使用的 go 程序。留空表示使用 PATH 中的 go。", + "placeholder": "自动:PATH 中的 go" + }, + "staticcheck": { + "title": "Staticcheck 分析", + "description": "把 staticcheck 的额外检查结果报告为诊断。大模块上会占用更多 CPU 和内存。" + }, + "gofumpt": { + "title": "使用 gofumpt 格式化", + "description": "格式化 Go 文件时使用 gofumpt 更严格的规则。" + }, + "usePlaceholders": { + "title": "补全时填入参数占位符", + "description": "补全函数调用时为函数的参数插入占位符。" + }, + "hoverKind": { + "title": "悬停文档", + "description": "悬停提示显示多少文档。", + "options": { + "FullDocumentation": "完整文档", + "SynopsisDocumentation": "第一句", + "SingleLine": "一行", + "NoDocumentation": "只显示签名" + } + } + }, + "sections": { + "Go toolchain": "Go 工具链" + } +} diff --git a/io.github.lithe-idea.go-support/plugin.json b/io.github.lithe-idea.go-support/plugin.json index 6990782..ff49eb5 100644 --- a/io.github.lithe-idea.go-support/plugin.json +++ b/io.github.lithe-idea.go-support/plugin.json @@ -2,12 +2,14 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.go-support", "displayName": "Go Support", - "version": "0.0.1", + "version": "0.1.0", "pluginAPIVersion": 0, "requires": { "buildSystems": 0, + "debugAdapters": 0, "languageServers": 0, "languages": 0, + "projectGenerators": 0, "settings": 0 }, "vendor": { @@ -16,11 +18,14 @@ "signatureRequirement": "none" }, "permissions": [ + "debug.launch", "languageServer.launch", - "process.build" + "process.build", + "project.generate" ], "activationEvents": [ "onBuildSystem:go", + "onDebug:delve", "onLanguage:go" ], "settings": [ @@ -391,5 +396,138 @@ ] } } + ], + "debugAdapters": [ + { + "id": "delve", + "displayName": "Go (Delve)", + "adapterID": "go", + "requests": [ + "launch" + ], + "selectors": [ + { + "targetKinds": [ + "file" + ], + "languageIDs": [ + "go" + ] + } + ], + "configurationTypes": [ + "go" + ], + "configurations": { + "launch": { + "arguments": { + "mode": "debug" + }, + "targetBindings": { + "program": "target.directory", + "cwd": "target.workingDirectory", + "args": "target.arguments", + "env": "target.environment" + } + } + }, + "launch": { + "process": { + "launch": { + "kind": "systemCommand", + "commands": [ + "dlv" + ] + }, + "arguments": [ + "dap" + ] + }, + "transport": "tcpAnnounced", + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + } + } + } + ], + "projectGenerators": [ + { + "id": "go-module", + "displayName": "Go", + "description": "A Go module built with the go command.", + "section": "project", + "order": 30, + "icon": { + "path": "icons/go-project.svg", + "mode": "original" + }, + "fields": [ + { + "id": "addSampleCode", + "type": "boolean", + "title": "Add sample code", + "default": true + }, + { + "id": "modulePath", + "type": "text", + "title": "Module path", + "description": "The module line of go.mod: the import path other code uses for this module, such as example.com/hello or github.com/you/hello.", + "default": "${project.name|lower}", + "pattern": "[A-Za-z0-9_~][A-Za-z0-9._~-]*(/[A-Za-z0-9_~][A-Za-z0-9._~-]*)*", + "maxLength": 200 + }, + { + "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.", + "advanced": true, + "default": "1.21", + "pattern": "1\\.[0-9]+(\\.[0-9]+)?", + "maxLength": 16 + } + ], + "requirements": [ + { + "languageID": "go" + }, + { + "buildSystemID": "go" + } + ], + "steps": [ + { + "kind": "files", + "source": "templates/go/module" + }, + { + "kind": "files", + "source": "templates/go/sample", + "when": { + "field": "addSampleCode", + "equals": true + } + } + ], + "openFiles": [ + { + "path": "main.go", + "when": { + "field": "addSampleCode", + "equals": true + } + }, + { + "path": "go.mod", + "when": { + "field": "addSampleCode", + "equals": false + } + } + ] + } ] } diff --git a/io.github.lithe-idea.go-support/templates/go/module/dot-gitignore b/io.github.lithe-idea.go-support/templates/go/module/dot-gitignore new file mode 100644 index 0000000..32ac62c --- /dev/null +++ b/io.github.lithe-idea.go-support/templates/go/module/dot-gitignore @@ -0,0 +1,18 @@ +# Programs and libraries go build writes +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binaries and coverage profiles +*.test +*.out +coverage.* + +# Programs Delve builds for a debug session +__debug_bin* + +# Local workspace files +go.work +go.work.sum diff --git a/io.github.lithe-idea.go-support/templates/go/module/go.mod b/io.github.lithe-idea.go-support/templates/go/module/go.mod new file mode 100644 index 0000000..a907fb8 --- /dev/null +++ b/io.github.lithe-idea.go-support/templates/go/module/go.mod @@ -0,0 +1,3 @@ +module {{ field.modulePath }} + +go {{ field.goVersion }} diff --git a/io.github.lithe-idea.go-support/templates/go/sample/main.go b/io.github.lithe-idea.go-support/templates/go/sample/main.go new file mode 100644 index 0000000..e75e733 --- /dev/null +++ b/io.github.lithe-idea.go-support/templates/go/sample/main.go @@ -0,0 +1,8 @@ +package main + +import "fmt" + +func main() { + name := "Gopher" + fmt.Printf("Hello, %s!\n", name) +}