10 Commits
Author SHA1 Message Date
zerorigin 1c2f5e3be0 完成规划 P3 / P4:-race/-bench 开关、自检与 e2e 冒烟
verify / verify (push) Canceled after 0s
P3 测试开关(internal/app/testflags.go)
  测试面板顶部加 -race / -bench 会话级 checkbox(不持久化,-race 会拖慢测试)。
  参数经 withTestFlags 统一注入结果树 / 输出面板 / 覆盖率三个 go test 入口。
  -bench 配 -run=^$,但调用方已有 -run(运行光标处测试)时不覆盖。
  勾 -bench 时「全部测试」改走输出面板,-json 会把 ns/op 埋在 output 行里看不清。
  4 条参数组合单测。

P4 三层守门
  verify.cmd:gofmt / vet / test 一道跑,纯 ASCII(cmd 按 GBK 读 UTF-8 中文
    注释会把中文当命令执行,实测踩过)。用 findstr 判 gofmt 输出非空。
  build.cmd verify:自检通过才构建;build.cmd 不带参数仍直接构建。
  .gitea/workflows/ci.yml:远端是 Gitea 企业版,用 Gitea Actions 兼容语法。
    是否真的运行取决于实例启用 Actions + runner,文档里如实写明这个前提,
    不声称已生效。GOOS=linux CGO_ENABLED=0 交叉编译已验证通过。
  tools/e2e/main.go:自建临时 Go 模块工作区,编译 -tags e2e 二进制,
    以工作区目录作为启动参数(openFromArgs),连 automation 插座跑 4 条场景:
    启动渲染 / 工作区与 gopls / 诊断到达 / 输出面板右键菜单。
    两个坑已处理:全新会话默认底部面板是关的(ensurePanel 先点状态栏「面板」);
    「运行」有页签和右上角真会跑程序的图标两个同名按钮(按 X<700 区分)。
    连跑两次均 4/4,退出码反映结果。

docs/本地自检与CI.md 记录三层守门用法、Gitea Actions 启用前提、e2e 限制
  (原生右键菜单插座测不了,仍靠 ui.Tester 单测)。
待办文档移除 P3/P4,规划只剩 4 项按需。

验证:build.cmd verify 全绿(286 个测试)、go run ./tools/e2e 两次 4/4、
GOOS=linux 交叉编译通过。
2026-11-12 16:36:02 +08:00
zerorigin e408300324 完成待办清单全部 6 项(T1-T6)
T1 移动包同步(internal/app/movepkg.go + renameentry.go)
  gopls 不声明 willRename,改用 go/parser 精确定位 ImportSpec.Path,
  目录移动改全仓 import 路径、单文件跨目录移动改 package 声明。
  写盘失败整体恢复并回滚 rename;已打开且无改动的缓冲区用 Reset 同步。
  集成测试在临时 Go 模块里移目录后直接跑 go build ./... 通过。

T2 输出/问题面板右键(panel_menu.go + output.go + popmenu.go)
  新增 openPopAt 让菜单贴指针弹出;复制选中行/复制全部/清空输出。
  真窗口截图确认位置正确、无裁切。
  **范围缩窄**:终端从 mygo v0.7.4 起就自带原生 ContextMenu,原判断是误报。

T3 snippet 补全(completion_snippet.go + lsp/protocol.go)
  snippetSupport 改 true;实测 gopls v0.23 返回 insertTextFormat=2、
  textEdit.newText="Print(${1:})",接上 mygo v0.9.0 的 ParseSnippet。
  解析失败降级成纯文本(支持嵌套占位/choices 剥离),结果按模板缓存。
  端到端 Tester 验证接受补全后得到 fmt.Print() 且光标停在括号内。

T4 本地历史超限可见(history.go)
  静默 return 改为返回 histSkipped,输出面板提示;每文件整个会话只提一次。

T5 全局搜索并发(palette.go)
  NumCPU(上限 8)个 worker 并发读盘,结果按文件序合并保证顺序稳定;
  命中上限停止派发;512KB 以上被跳过的文件数显示成面板底部提示。

T6 清理根目录残留;4 个 0 字节 .sock 被环境安全守卫拦住未删(已 gitignore)。

验证:gofmt 空、build/vet OK、go test -count=1 ./... 全绿(282 个测试)、
新增并发/剪贴板/回滚用例 go test -race 无数据竞争。
docs/MyGoland-待办与规划.md 已清空待办,只剩 6 项规划与完成索引。
2026-11-12 16:09:00 +08:00
zerorigin d9db634066 升级 mygo v0.7.4 -> v0.9.0
跨 v0.8.x 与 v0.9.0 两个小版本,改动量比上次补丁升级大得多:新增 258 个
文件、删除 6 个、修改 323 个。逐层核对后确认没有破坏本项目:

- 导出符号只删了 plugins/sqlite.LibraryPath,本项目未使用
- 依赖的 API 全部在位且签名未变:State.ContextMenu、editor.View、
  Menu.Item/Separator/Submenu、MenuItem.Disabled/Checked/Radio/Shortcut/
  Chosen、NewTester、Tester.RightClickAt/Menu/ChooseMenuItem
- editor.Inlay 加了 Trailing / Ellipsis 两个可选字段,向后兼容
- go build 与 go vet 零错误,全量测试绿

顺手核实了渲染:用 v0.7.4 编了个对照二进制打开同一个 main.go,
逐像素 diff 为空。中途一度以为内联提示把代码画坏了(截图里
"fmt.Println(a...", ..."" 看着像串行),放大后确认那是 gopls 的
参数名/类型提示 "a ...:",两版完全一致,是看图看错了。

真正的收益在待办里:v0.9.0 补上了 ui/editor/snippet.go,提供
ParseSnippet 与 State.InsertSnippet(Tab 跳占位),Completion 也加了
Snippet 字段。待办 T3 的前提『框架不支持占位符、要自己造轮子』因此
失效,改法从『1 天 + 可能提 PR』降为『纯接线约 0.5 天』,已更新
docs/MyGoland-待办与规划.md,并补了一条『前提有保质期』的教训。
2026-11-12 15:05:01 +08:00
zerorigin 4a9085e2bc 补 docs/MyGoland-待办与规划.md:剩余 6 项缺陷 + 6 项规划
把还没做的部分从评估报告里抽出来单独成册,每项带证据位置、粗估成本、
完成标准与建议顺序,做完即从本文删除。

写之前先实测了两条被当作既定前提的结论,两条都推翻了原判断:

- T1 移动包同步:评估报告写的「可基于 gopls rename 实现」不成立。
  实测 gopls v0.23 的 workspace.fileOperations 只声明 didCreate,
  没有 willRename/didRename,该能力不会响应 workspace/willRenameFiles
- T3 snippet 补全:框架的 CompletionSnippet 只是图标分类,不解析
  ${1:arg} 占位,也没有 Tab 跳转。改 snippetSupport 只是第一步

另记录 palette.go 一处评估报告漏掉的静默行为:512KB 以上文件在全局
搜索里被直接跳过,无提示。

评估报告顶部加指向本文档的说明,报告本身转为缺陷证据存档。
2026-11-09 17:58:27 +08:00
zerorigin 88067cc15c 升级 mygo 到 v0.7.4,删除弹窗标记不可逆按钮
v0.7.2 → v0.7.4 两个补丁版本。逐文件 diff 后确认无影响本项目的破坏性变更:
paintBlock 的签名改动只影响自定义 decor,本项目没有实现。

- fileops.go:删除弹窗用上新的 DestructiveButtons,把「永久删除」标出来
- view.go:补注释说明 NoScrollPastEnd 在 v0.7.4 下仍然必要
- 评估报告记录升级验证过程与滚动条行为变化

验证:build/vet/gofmt 全绿,lsp 与 app 包 -count=1 全绿(含真 gopls 与
右键菜单的 ui.Tester 用例);另编了 v0.7.2 二进制做像素级对照,差异仅在
滚动条滑块是否常驻。
2026-11-05 17:11:44 +08:00
zerorigin 6b07d16738 代码动作改用选区、补文件级请求、滤掉 gopls 的浏览类命令
第 10 项。原报告说「代码动作只取光标行 range,所以生成测试/实现接口取
不到」——实测(gopls v0.23)推翻了一半,真问题在别处:

1. 选区被忽略。原来一律传整行,用户选中 foo() 按 Alt+Enter,gopls 收到
   整行,只能给 refactor.extract.function;refactor.extract.variable 和
   refactor.inline.call **只在范围正好圈住表达式时才返回**。
2. 噪音淹没有效动作。一次请求 6–9 项,其中 5 项是 gopls.doc(开
   pkg.go.dev)、assembly、free_symbols、client_open_url、gc_details。
   「Extract variable」被挤到第七位。

而「生成测试」(source.addTest)本来就有;「零宽位置会丢快速修复」也是
错的——gopls 会把位置摊到所属节点,行首零宽照样拿得到 quickfix。

改法:
- 有选区用选区,没有才用整行;
- 发两次请求:光标/选区(带同行诊断)+ 整文件且 only=refactor.rewrite
  (refactor.rewrite.addTags 这类只有范围覆盖到才出现);
- 按**命令名**过滤那 5 个浏览命令(不是标题,标题会随版本变),只黑
  已知噪音、其余放行,gopls 加新能力不会被误杀;
- 同标题取第一次出现的那份(与用户眼前范围一致),再按
  IsPreferred → quickfix → refactor → source 稳定排序;
- 全是浏览命令时提示「这里有 N 项,但都只是打开文档/汇编之类的浏览
  命令,已隐藏」,不再假装什么都没发生。

验证分三层:
- 13 条 app 层单测:范围(含 UTF-16 中文列)、诊断相交、噪音判定、
  合并去重首见优先、排序稳定性;
- 3 条真 gopls 回归:选区给 extract.variable/inline.call、整行不给、
  整文件 only=refactor.rewrite 给 addTags、缺 import 的 quickfix 依赖
  诊断且对零宽位置也宽容;
- 1 条 app 层全管线集成:选中表达式 → 必须出现 extract.variable 且不得
  混入浏览命令。
真实窗口截图 docs/code-action-panel.png 只剩两项,5 个浏览命令没露头。

顺带把 Client.CodeActions 拆出 CodeActionsOnly(支持 context.only),
queryCodeActions 从 goroutine 里拆出来以支持集成测试;actionKindLabel
给 source.addTest/organizeImports/fixAll 单列文案,并给 IsPreferred 加
「推荐 ·」前缀。
2026-11-05 16:38:30 +08:00
zerorigin c35564b65e 编辑器右键菜单补应用层动作,并做完评估报告"本周做"剩余项
第 9 项。原报告 4.5 判断「编辑器无右键菜单」是错的:框架 ui/editor
自带完整菜单(跳转定义、剪切/复制/粘贴、全选、切换注释、选区/转换/
折叠三个子菜单),State.ContextMenu 只是留给应用层的追加点。所以本次
不重造菜单,只往那个追加点里填应用层独有的 16 项:

- gopls:代码动作、查找引用、重命名符号(要求 Go 文件 + LSP 在线,
  改文本的还要求非只读)
- 编辑:格式化文档、在文件中查找
- 测试:运行光标处的测试 / 当前包(只在 _test.go 出现,普通文件里挂
  一个永远点不动的项是噪音,而它一旦可点又会退化成跑全部测试)
- 定位:在项目树中定位、在资源管理器中显示、本地历史
- 剪贴板:复制相对路径 / 绝对路径

菜单项造在纯函数 editorMenuItems(editorMenuCap) 里,可用性由
goFile/lspReady/inRoot/onDisk/readOnly 五个事实决定;条件插入容易留下
连着两条分隔线或末尾挂一条,统一由 compactEditorMenu 收口。

验证不止单测:TestEditorMenuShowsInEditor 用 ui.NewTester 真把编辑器
渲染出来、真右击、读 tt.Menu() 的菜单文案,再 ChooseMenuItem 走完
「菜单 → 动作 → 剪贴板」整条链路,并断言灰掉的项点不动。框架文档明确
说右键菜单不能用 automation 插座驱动,所以走 Tester 这条路。

顺带一次 gofmt -w 把全仓 gofmt -l 清空(13 个文件,多是 CRLF 与文档
注释空格),并更正报告 4.5、补齐执行状态。

其余"本周做"项(回收站删除、参数引号切分 + Env/WorkDir、日志轮转、
标签同名区分)一并入库。
2026-11-05 16:06:17 +08:00
zerorigin 8b2552fe86 docs: 补标签右键恢复后的截图证据 2026-11-05 15:44:02 +08:00
zerorigin 4ace9c9fb6 fix: 按评估优先级修四项(标签右键/UTF-8 截断/覆盖率输出/.gitignore)
1. 标签页右键菜单接回(回归修复)
   tabmenu.go 的 160 行实现全库零调用点,tabBar 只处理 Clicked。
   补 RightClicked → openPop(tabEntries(path)),右键时先设 active
   (菜单无标题,靠标签高亮传达「关闭左边」相对谁算)。
   新增 tabmenu_test.go 8 个单测。

2. 中文按字节截断导致乱码
   palette.go trimmed[:160]、rename.go s[:140] 会把多字节字符切断。
   trimTo 从 gitlog.go 提到 strutil.go(三个调用方共用),两处改用它;
   n<=0 返回空串。strutil_test.go 6 个单测(含真实 linePreview 路径)。

3. 覆盖率运行不再吞测试输出
   原来 lines 收集后 _ = lines 丢弃,测试失败只看到覆盖率数字。
   改用 ExitCode() 判失败,只回放 FAIL/--- FAIL/panic/# 包/file.go:12 行
   (上限 200),覆盖率页顶部给红底摘要 + 「查看测试输出」按钮。
   coverageFailLines/Summary 纯函数 + 5 个单测。

4. 索引与搜索感知 .gitignore
   新增 ignore.go:dir/、*.ext、/rootonly、带路径、**、! 取反、注释。
   内置跳过扩到 vendor/dist/build/out/target/.next(文件树仍用保守 skipDir)。
   indexState 加 truncated,快速打开底部提示「索引已截断至 N 个文件」。
   ignore_test.go 10 个单测 + 真实遍历集成测试。

验证:go vet ./... 干净;go test ./internal/... 7 包全绿;
e2e 实例 tools/tree 确认菜单 5 项齐全 + tools/shot 截图核对。
2026-11-05 15:43:33 +08:00
zerorigin bbff08f364 docs: MyGoland 完善度评估报告(2026-11-05)
以代码为准的全面检索:12 个领域的完成度矩阵、P0-P2 缺陷清单、
优先级建议与可执行改进方向。关键发现:

- 标签右键菜单 160 行代码零调用点(功能回归,docs 截图证明曾可用)
- palette/rename 按字节截断 UTF-8,中文搜索命中行会乱码
- 覆盖率运行收集 go test 输出后丢弃(_ = lines),失败原因不可见
- skipDir 不感知 .gitignore、不排除 vendor,索引 20000 上限静默截断
- 删除走 os.RemoveAll 不进回收站
- App struct 100 个字段,无 CI、UI 层无自动化回归

正面实测:go vet 全净、go test -race 五包全绿、171 个测试函数、0 处 TODO。
2026-11-05 15:43:26 +08:00
75 changed files with 6272 additions and 130 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: verify
# Gitea Actions uses GitHub-Actions-compatible workflow syntax and lives in
# .gitea/workflows/. It only runs when the instance has Actions enabled and a
# runner registered; otherwise this file is inert. See docs/本地自检与CI.md.
on:
push:
branches: [main]
pull_request:
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
# Same three gates as verify.cmd, so local and CI never disagree.
- name: gofmt
run: test -z "$(gofmt -l .)"
- name: build
run: go build ./...
- name: vet
run: go vet ./...
- name: test
run: go test ./... -count=1 -timeout 480s
+3
View File
@@ -9,5 +9,8 @@ __debug_bin*
*.sock *.sock
e2e_shot*.png e2e_shot*.png
# 本地临时验证目录(e2e 构建、截图、验证脚本)
.tmp/
# WorkBuddy 本地工作区数据(记忆/日志,不入库) # WorkBuddy 本地工作区数据(记忆/日志,不入库)
.workbuddy/ .workbuddy/
+9 -2
View File
@@ -1,10 +1,17 @@
@echo off @echo off
setlocal setlocal
cd /d "%~dp0" cd /d "%~dp0"
rem Usage: build.cmd build only
rem build.cmd verify run verify.cmd first, build only when green
if /i "%~1"=="verify" (
call "%~dp0verify.cmd"
if errorlevel 1 exit /b 1
echo VERIFY OK, starting build...
)
go build -trimpath -ldflags "-s -w -H=windowsgui" -o MyGoland.exe . go build -trimpath -ldflags "-s -w -H=windowsgui" -o MyGoland.exe .
if errorlevel 1 ( if errorlevel 1 (
echo 构建失败 echo Build failed
exit /b 1 exit /b 1
) )
if exist "resources\ghostty-vt.dll" copy /y "resources\ghostty-vt.dll" "ghostty-vt.dll" >nul if exist "resources\ghostty-vt.dll" copy /y "resources\ghostty-vt.dll" "ghostty-vt.dll" >nul
echo 构建完成:MyGoland.exe(GUI 子系统,不会弹控制台) echo Build OK: MyGoland.exe (GUI subsystem, no console window)
+522
View File
@@ -0,0 +1,522 @@
# MyGoland 完善度评估报告
> 评估日期:2026-11-05
> 评估对象:`D:\WorkSpaces\CaoGangHui\Golang\MyGoland`(HEAD = `5a87a61`)
> 基准参照:GoLand 2025.x 日常使用路径
> 评估方式:**以当前代码为准,不以设计文档的自我陈述为准**;文档结论逐条回查代码取证
>
> **📌 后续进展见 `MyGoland-待办与规划.md`**:本报告"立刻做/本周做"9 项 + "规划做"第 10 项已全部实施,剩余待办与规划已迁到那份文档继续跟踪。本报告保留为**缺陷证据与实测结论的存档**,不再更新执行状态。
---
## 一、结论摘要
**整体判断**:这是一个「骨架完整、闭环基本打通」的 Go IDE,日常写代码/跑测试/看 diff/提交这条主链路已经可用。当前状态不是「功能没做完」,而是**功能做完了但入口有遗漏、边界处理有粗糙处**。
三条最重要的结论:
1. **存在一处功能性回归**:标签页右键菜单(关闭左边/右边/其他/全部/已保存)代码 160 行完整存在于 `tabmenu.go`,但**全库无任何调用点**——`docs/tab-context-menu-1.png`、`tab-context-menu-2.png` 证明它曾能用。这是唯一「代码在、功能不可达」的确定性问题,修复成本约 30 分钟。
2. **存在两处 UTF-8 破坏**:`palette.go:266`、`rename.go:86` 按**字节**截断字符串,中文会切在多字节字符中间。同项目的 `gitlog.go:trimTo` 用 `[]rune` 是对的——这是局部正确、全局不一致。
3. **数据安全有一处缺口**:文件删除直接 `os.RemoveAll`,不进回收站,弹窗文案自己写着「此操作不可撤销」。VS Code 默认走回收站,这是可低成本补齐的差异。
正面结论(有实测支撑):`go vet ./...` 全包干净;`go test -race` 对 app/git/task/ai/godoc 五个包全绿;171 个测试函数覆盖了绝大部分逻辑层;无 TODO/FIXME 遗留标记。
---
## 二、检索范围与方法
### 2.1 覆盖范围
| 类型 | 范围 |
|---|---|
| 源码 | 110 个 `.go` 文件,实现 15,199 行 + 测试约 4,200 行 |
| 模块 | `internal/app`(12,730 行)、`internal/lsp`(1,296)、`internal/dap`(515)、`internal/git`(297)、`internal/task`(139)、`internal/godoc`(110)、`internal/ai`(112) |
| 文档 | 设计文档 2,227 行(67 节)、差距分析 210 行、终端方案 51 行 |
| 工具 | `tools/` 下 6 个自动化工具(click/keys/menu/preheat/shot/tree) |
| 配置 | `go.mod`、`build.cmd`、`.gitignore`、`mygo.json` |
### 2.2 方法(六条,按可信度排序)
1. **调用链回溯**:对每个"已实现"的功能,从函数定义反查调用点,确认是否真的接到 UI/菜单/快捷键。这是本次发现标签菜单回归的手段。
2. **死代码启发式扫描**:统计每个函数名在全库的引用次数,`=1` 判定为无调用。
3. **关键词否定检索**:对 20 个能力关键词(gitignore/vendor/Branch/Stash/Blame/bench/golangci/bookmark/Ctrl+G/snippet 等)逐个检索,确认"没有"而不是"没看到"。
4. **静态度量**:函数长度、裸 panic、`_ =` 忽略错误点、goroutine 启动点。
5. **动态验证**:`go vet ./...`、`go test -race`(5 个包)、全量单测。
6. **文档交叉核对**:设计文档第 8.4/9.5/14.4/31.4/38.5/47/56.5 节自述的「已知限制」逐条回查代码,标注已修 / 仍存在。
### 2.3 方法与结论的边界(必须说明)
- **UI 行为未做逐项像素验证**:本次是代码级审查,标签右键缺失由「无 `RightClicked` 处理 + 无调用点」推定,建议按附录步骤手工确认一次。
- **框架能力边界不可测**:`mygo` 编辑器对多光标、IME、code lens 的支持程度来自设计文档 56.3 的记载,本次未读框架源码验证。
- **完成度百分比是主观口径**:按"GoLand 对应能力在日常场景下的覆盖程度"估算,不是代码覆盖率,不宜作为精确指标引用。
---
## 三、功能完成度矩阵
图例:✅ 完成可用 | ⚠️ 部分完成/有已知短板 | ❌ 缺失
### 3.1 编辑核心(约 85%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 语法高亮(深/浅双套) | ✅ | `code_theme.go`,oneDarkVivid / oneLight |
| gopls 补全 + 本地词表兜底 | ✅ | `lsp.go:complete`,先 `lspSync` 再请求(时序已修) |
| 补全文档 AI 中文翻译 | ✅ | `completion.go` + `translate.go` + `llm.go`,缓存 399+ 条 |
| 悬停文档 + 翻译 | ✅ | `renderHover` / `splitHoverDoc`,签名与链接行保护 |
| 实时诊断波浪线 | ✅ | 零长 range 扩展 1 字节(commit `5a87a61`) |
| 内联提示(参数名/类型) | ✅ | `inlay.go`,去抖 220ms |
| 代码折叠 | ✅ | `editor.ToggleFold/FoldAll/UnfoldAll` 已接菜单 |
| 文件内查找替换 | ✅ | `editor.Find/FindReplace/FindNext/FindPrevious` |
| 全局搜索 + 正则/大小写/整词 | ✅ | `buildReplaceRe`,中文整词退化处理正确 |
| 全局替换(预览→确认) | ✅ | `replace.go`,打开中改缓冲区、未打开按原编码写盘 |
| 保存时格式化 + 整理 import | ✅ | 两次往返 + 版本守卫(`lsp.go:saveDoc`) |
| 行注释 / 缩进 / 括号匹配 | ✅ | 编辑器内置 |
| 代码缩略图 / 面包屑 | ✅ | `minimap.go`、`breadcrumb.go` |
| **代码模板(snippet 占位)** | ❌ | `protocol.go:305` `snippetSupport: false`;函数补全后需手填参数 |
| **多光标 / 列选择** | ❌ | 编辑器有 `Selections()`,app 层未接 UI |
| **跳转到行(Ctrl+G)** | ❌ | 全库无 `GoToLine` / `Ctrl+G` |
| **编辑器内右键菜单** | ✅ 已补(2026-11-05 复核) | 见 4.5 的勘误:框架 `ui/editor` **自带**完整右键菜单,本次又在其后追加了 16 项应用层动作(`editor_menu.go`) |
| **书签** | ❌ | 无 bookmark 相关代码 |
### 3.2 导航(约 80%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 跳转定义(F12 / Ctrl+Click) | ✅ | `lsp.go` definition |
| 查找引用(Shift+F2) | ✅ | 结果进命令面板,`refs` 态 |
| 全局符号搜索(Ctrl+T) | ✅ | `workspace/symbol` + 依赖包过滤 |
| 快速打开文件(Ctrl+P) | ✅ | `fuzzyScore` 打分:连续匹配/词边界/文件名加权 |
| 大纲(结构视图) | ✅ | `outline.go`,去抖 400ms,按版本失效 |
| 最近项目 | ✅ | `recent.go` |
| **最近文件(Ctrl+E)** | ❌ | 只有最近**项目**,无已打开标签的快速切换 |
| **上一个/下一个问题(F2)** | ❌ | 只能点问题面板 |
| **跳转到行** | ❌ | 同上 |
### 3.3 重构与代码动作(约 65%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 重命名符号(F2) | ✅ | `rename.go`,多文件编辑应用 |
| 代码动作(Alt+Enter) | ⚠️ | `action.go` 请求 range **固定为光标所在行**;文件级/选区级动作(生成测试、实现接口、补 struct tag)取不到 |
| 提取函数/变量、内联 | ⚠️ | gopls 提供,混在动作列表里,无分类入口 |
| 更改签名 | ❌ | gopls 不支持 |
| 移动目录同步改包名/import | ❌ | `fileops.go` 只动磁盘路径 → Go 里移动包会直接编译失败 |
| 安全删除符号 | ❌ | 只有文件级删除 |
### 3.4 调试(约 70%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 断点(含条件、启用/禁用) | ✅ | `breakpoints.go`,真 dlv 验证过 `i == 3` |
| 继续/步过/单步/跳出 | ✅ | F9/F8/F7/Shift+F8 |
| 变量树(递归展开) | ✅ | `children`/`expanded` 按引用号 |
| 表达式求值 | ✅ | `debug.go:232` |
| 调用栈跳转 | ✅ | |
| goroutine 列表与切换 | ✅ | `dap.Threads()`,停点时刷新,与设计文档 9.5「未做」已不符(已补) |
| **Watch 表达式** | ❌ | 无持久 watch 列表,只能一次性求值 |
| **Attach 到进程** | ❌ | `StartDebug` 只有 launch(`dap.Start` + `program`) |
| **日志断点** | ❌ | |
| **调试时行尾显示变量值** | ❌ | |
| **调试测试用例** | ❌ | 只能调试 `program` 指向的包 |
### 3.5 测试(约 75%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 结果树(包→测试→子测试) | ✅ | `testrun.go` 解析 `go test -json` |
| 单用例精确运行 | ✅ | `runFilterFor` → `^TestX$/^sub$` |
| 失败用例跳源码 | ✅ | 从 fail 节点自身 output 解析首个 `file:line`,盘符/相对路径已处理 |
| 覆盖率(行级红绿) | ⚠️ | 数据链路正常,但**测试输出被丢弃**(见 4.4) |
| 行号旁测试标记 | ✅ | `testlens.go` 青色 GutterMark,断点优先 |
| **`-race` 开关** | ❌ | 命令固定,无参数注入 |
| **Benchmark 运行与结果** | ❌ | 只把 `Benchmark*` 识别为测试函数,不能跑 |
| **覆盖率增量(只看本次改动)** | ❌ | |
### 3.6 版本控制(约 55%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 文件状态着色 | ✅ | `refreshGit` |
| 并排 diff(HEAD ↔ 缓冲区) | ✅ | `diff.go`,未保存改动一并比 |
| 选择性暂存 + 提交 | ✅ | `StagePaths`,默认全选可取消,空勾选不关弹窗 |
| pull(`--ff-only`)/ push(自动 `-u`) | ✅ | 分叉时失败并透传 git 提示,设计取舍合理 |
| 提交历史(文件/目录)→ 对比当前 | ✅ | `historyview.go` 全屏列表 + DiffView |
| 本地历史(自动快照/恢复) | ⚠️ | 快照上限 4MB,超出静默跳过 |
| **分支切换/新建/合并** | ❌ | 只在状态栏显示分支名(`view.go:568`) |
| **Stash** | ❌ | |
| **行级 blame** | ❌ | |
| **冲突三方合并** | ❌ | 外部改动冲突只能「保留我的改动」 |
### 3.7 项目与工作区(约 70%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 文件树(多选、Shift 连选、右键) | ✅ | `view.go:treeRow` |
| 新建文件/文件夹(含 .go 示例代码) | ✅ | `newfile.go` |
| 重命名/移动(含目录、标签重映射) | ✅ | `renameentry.go`,`remapPath` 已测 |
| 删除 | ⚠️ | `os.RemoveAll` + 确认弹窗,**不进回收站** |
| 外部变更监听 | ⚠️ | 只监听已打开文件(`watch.go`),文件树外部增删需手动刷新 |
| **`.gitignore` 感知** | ❌ | `skipDir` 硬编码 4 个目录:`.git`/`node_modules`/`.idea`/`.mygoland` |
| **`vendor/` 排除** | ❌ | 无 |
| **多模块 / `go.work`** | ❌ | `startLSP(root)` 单根 |
| 索引规模 | ⚠️ | 超过 20000 文件 `SkipAll` 静默截断,用户无感知 |
### 3.8 运行与构建(约 65%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 运行 / 构建 / 停止(杀进程树) | ✅ | `task` 包,Windows `taskkill /T` |
| 多运行配置 | ✅ | `runconfig.go`,Name/Program/Args/StopOnEntry |
| `go mod tidy` 入口 | ✅ | `RunModTidy` |
| 重启语言服务器 | ✅ | 代数校验 + 10 秒冷却 |
| **环境变量 / 工作目录** | ❌ | `runConfig` 无这两个字段 |
| **`GOOS`/`GOARCH`/build tags** | ❌ | 交叉编译只能走终端 |
| **带空格的参数** | ❌ | `strings.Fields(cfg.Args)`,`-tags "a b"` 会被拆断 |
### 3.9 终端(约 85%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 多会话并行 | ✅ | `terms []*termSession`,各自独立 shell |
| PowerShell / Git Bash / CMD | ✅ | `detectShells`,找不到给提示 |
| PTY 与 VT 渲染 | ✅ | 框架 `plugins/terminal` + `ghostty-vt.dll` |
| **终端右键(粘贴/清空/复制)** | ❌ | 无右键入口 |
### 3.10 会话与工程化(约 90% / 60%)
| 能力 | 状态 | 依据 |
|---|---|---|
| 会话恢复(标签/滚动/光标) | ✅ | `session.go`,等排版完成再套 |
| 未保存保护(关标签/关窗/退出) | ✅ | 三入口统一走确认,批量只问一次 |
| 崩溃恢复(快照) | ✅ | `history.go` 三触发时机 |
| 单实例 + 命令行打开 | ✅ | 回环 TCP + magic 握手,`MYGO_AUTOMATION` 绕过 |
| 设置界面 | ✅ | `settings.go`,含文档翻译三件套 |
| 命令面板 / 关于 / 输出 / 问题面板 | ✅ | |
| **快捷键自定义** | ❌ | 硬编码 |
| **CI** | ❌ | 无 `.github/workflows`,只有本地 `build.cmd` |
| **UI 自动化回归** | ❌ | `tools/` 是手工调试工具,无脚本化用例 |
---
## 四、缺陷与风险点(按严重度)
### P0 — 功能不可达 / 数据风险 / 正确性
#### 4.1 标签页右键菜单整块丢失(功能回归)
**证据**:
- `internal/app/tabmenu.go` 160 行完整实现:关闭、关闭左边(n)、关闭右边(n)、关闭其他(n)、关闭全部(n)、关闭已保存的(n)。
- 全库检索 `tabEntries` / `tabMenu`:**只有定义,零调用**(死代码扫描中唯一引用数为 1 的函数)。
- `view.go:tabBar`(499–535 行)只处理 `open.Clicked()` 与 `close.Clicked()`,**无 `RightClicked()`**。
- 自绘菜单 `openPop` 全库仅 3 个入口:`titlebar.go:84`、`view.go:183`(+ 按钮)、`view.go:342`(文件树行)。
- `docs/tab-context-menu-1.png`、`tab-context-menu-2.png`(10-29 13:43)证明该功能曾跑通过。
**判断**:重写标签栏时漏掉了右键接线。附带影响:`docIndex`、`savedPaths`、`closeOthers`、`closeSaved`、`closePaths` 这批函数全部沦为不可达代码。
**修复**:`tabBar` 里给标签容器加 `RightClicked()` → `a.openPop(rect, a.tabEntries(d.path))`,约 30 分钟,其中 20 分钟是拿 `tools/tree` 校准入参矩形。
#### 4.2 UTF-8 按字节截断(中文乱码)
| 位置 | 代码 | 后果 |
|---|---|---|
| `palette.go:266` | `trimmed = trimmed[:160] + "…"` | 全局搜索命中行含中文且超 160 字节时,切在多字节字符中间 → 显示替换字符 |
| `rename.go:86` | `s = s[:140] + "…"` | 同名场景 |
**对照**:`gitlog.go:trimTo` 用 `[]rune(s)` 截断,是正确的。同一项目里两种写法并存,属于一致性缺陷而非认知不足。
**修复**:抽一个 `trimRunes(s string, n int) string`(或直接复用 `trimTo`),两处替换。约 30 分钟,配 2 个单测(中文、emoji)。
#### 4.3 删除文件不进回收站
**证据**:`fileops.go:182` `os.RemoveAll(p)`;弹窗文案(`fileops.go:164-166`)自己写「此操作不可撤销」。
**风险**:目录删除是递归的,误删一个包等于丢失整个目录,且无任何恢复路径(本地历史只覆盖打开过的文件,4MB 以上还跳过)。
**修复方向**(成本由低到高):
1. Windows 用 `SHFileOperationW`(`FOF_ALLOWUNDO`)或 `IFileOperation` 走回收站;Git Bash 环境下可用 `github.com/...` 现成库。
2. 退一步:删目录前额外弹一次「目录将被递归删除,是否改为移到回收站?」,给一个可逆选项。
3. 最低成本兜底:删除前先把目标路径写入本地历史,提供「撤销删除」入口。
#### 4.4 覆盖率运行丢弃测试输出
**证据**:`coverage.go:150-167`
```go
var lines []string
for line := range t.Lines { lines = append(lines, line) }
t.Wait()
...
_ = lines // 收集了但从未使用
```
`_ = lines` 的存在本身说明变量当初是为了别处使用而留的占位。
**后果**:`go test -coverprofile` 失败(编译错误/断言失败)时,用户只看到「覆盖率 xx%」或「没拿到 coverprofile」,**看不到失败原因**。覆盖率面板不承担"看测试失败"的职责,而这里又是唯一入口。
**修复**:把 `lines` 写进输出面板(失败时尤其要写),并在 `applyCoverage` 前用 `t.ExitCode() != 0` 判断,失败则明确提示「覆盖率不可信:测试未全部通过」。约 1 小时。
#### 4.5 编辑器/终端/输出面板无右键菜单 —— **本条判断错误,已更正**
**勘误(2026-11-05,实施第 9 项时读框架源码核实)**:
- **编辑器一直有右键菜单**,由框架提供:`ui/editor/state.go:89` 的 `State.ContextMenu func(m *ui.Menu)`,`ui/editor/build.go:81` 把它接到元素上,`build.go:201` 的 `ed.menu(m)` 已经内置跳转定义(F12)、剪切/复制/粘贴、全选、切换注释,以及「选区 / 转换 / 折叠」三个子菜单。`ui/editor/build.go:278` 的 `m.Separator(); ed.o.contextMenu(m)` 是留给应用层的追加点。
- 原报告「app 层检索 `ContextMenu` 无调用」这个事实是对的,但它只能证明**应用层没往里加东西**,不能推出「编辑器没有右键菜单」。报告 2.3 已声明「未读框架源码验证」,这里正是那条限定命中的地方。
**本次实际做的事**:把应用层独有的动作补到框架那批项后面(`internal/app/editor_menu.go`,挂在 `app.go` 的 `newDoc` 里)。补的 16 项分 5 组:
| 组 | 项 | 可用条件 |
|---|---|---|
| gopls | 代码动作(Alt+Enter)、查找引用(Shift+F2)、重命名符号(F2) | 是 Go 文件 + LSP 在线;改文本的那几项还要求非只读 |
| 编辑 | 格式化文档、在文件中查找(Ctrl+F) | 同上 / 恒可用 |
| 测试 | 运行光标处的测试、运行当前包的测试 | **只在 `_test.go` 里出现**,且在工作区内 |
| 定位 | 在项目树中定位、在资源管理器中显示、本地历史… | 分别要求在工作区内 / 有绝对路径 |
| 剪贴板 | 复制相对路径、复制绝对路径 | 分别要求在工作区内 / 有绝对路径 |
仍然缺的(保持原判断,只是范围缩小到这两处):**终端**与**输出/问题面板**确实没有右键菜单,`openPop` 仍只有 3 个入口。
### P1 — 体验短板与静默失败
| # | 问题 | 证据 | 影响 |
|---|---|---|---|
| 4.6 | 搜索/索引不感知 `.gitignore`,不排除 `vendor/` | `app.go:860` `skipDir` 硬编码 4 个目录 | 真实 Go 项目开 `vendor` 时索引膨胀、搜索命中第三方代码 |
| 4.7 | 索引 20000 文件上限静默截断 | `grep.go:44` `filepath.SkipAll` | 大型仓库快速打开只能搜到前 20000 个文件,无提示 |
| 4.8 | 运行参数按空格切分 | `debug.go:126` `strings.Fields(cfg.Args)` | `-tags "integration e2e"` 传不进去 |
| 4.9 | 日志超 4MB 直接删除而非轮转 | `log.go:30-32` `os.Remove(p)` | 排查刚发生的崩溃时,日志可能刚好被删干净 |
| 4.10 | 补全不支持 snippet 占位 | `protocol.go:305` `snippetSupport: false` | 函数补全后要手填参数,无 Tab 跳转占位符 |
| 4.11 | 全局搜索单线程串行读盘 | `palette.go:249-278` 顺序 `os.ReadFile` | 大工作区搜索延迟随文件数线性增长(有 220ms 去抖兜底) |
| 4.12 | 代码动作只取光标行 range | `action.go` | **原判断部分不准,已实测更正并修完,见 4.12 正文** |
| 4.13 | 移动目录不同步包名/import | `fileops.go` 只改磁盘 | Go 项目里移动包 = 编译失败,需手工改 package 与 import |
| 4.14 | 标签只显示文件名 | `view.go:515` `filepath.Base(d.path)` | 两个不同目录下的 `main.go` 在标签上无法区分(文档 31.4 已记,仍未改) |
| 4.15 | 本地历史 4MB 上限静默跳过 | `history.go:29` `histMaxSize = 4 << 20` | 大文件改坏后无快照可回 |
#### 4.12 代码动作的请求范围 —— 原判断部分不准,实测更正后已修
**原判断**:「`action.go` 只取光标行 range,所以『生成测试』『实现接口』这类需要文件级 range 的动作取不到。」
**实测(2026-11-05,gopls v0.23,`internal/lsp/codeaction_test.go` 固化了结论)推翻了一半**:
| 请求范围 | 实际拿到的(同类文件) |
|---|---|
| 光标位置(零宽) | 快速修复**照样能拿到**(`Add import: "fmt"`)——gopls 会把位置摊到所属节点,原以为要「范围盖住诊断」才给 |
| 整行 | `refactor.extract.function`、`source.addTest`(**「生成测试」本来就是有的**) |
| **选中表达式** | `refactor.extract.variable`、`refactor.inline.call` ← **只有选区才给** |
| 整文件 | `refactor.rewrite.addTags`(这类文件级重构只有范围覆盖到才出现) |
所以真问题不是「取不到生成测试」,而是两个:
1. **选区被忽略**。原来一律传整行,用户选中 `foo()` 再按 Alt+Enter,gopls 收到的是整行 → 只能「提取成函数」,选不中「提取成变量」和「内联调用」。选中态形同虚设。
2. **噪音把真动作淹了**。一次请求返回 6–9 项,其中 5 项是 `gopls.doc`(开 pkg.go.dev)、`gopls.assembly`(看汇编)、`gopls.free_symbols`、`gopls.client_open_url`(明文开浏览器)、`gopls.gc_details`。真正的「Extract variable」排到第七位。
**改法**(`internal/app/codeaction.go` + `action.go`):
- 有选区用选区,没有才用整行;
- 发两次请求:一次按光标/选区(带同行诊断),一次按整文件且 `only: ["refactor.rewrite"]`;
- 按**命令名**(不是标题)过滤那 5 个浏览命令,只黑已知噪音、其余放行,gopls 加新能力不会被误杀;
- 合并去重(同标题取第一次,即与用户眼前范围一致的那份),再按 `IsPreferred → quickfix → refactor → source` 稳定排序;
- 全是浏览命令时,提示改成「这里有 N 项,但都只是打开文档/汇编之类的浏览命令,已隐藏」,不再假装什么都没发生。
**验证**:13 条 app 层单测(范围/诊断/过滤/合并/排序)+ 3 条真 gopls 回归(`TestGoplsCodeActionSelection`/`WholeFile`/`MissingImportQuickfix`)+ 1 条 app 层全管线集成(选中表达式 → 结果里必须出现 `refactor.extract.variable`,且不得混入浏览命令)。真实窗口截图 `docs/code-action-panel.png`:面板里只剩 `Organize Imports`(整理 import)和 `Split package "demo"`(源码)两项,5 个浏览命令确实没露头。
### P2 — 架构与工程债
| # | 问题 | 数据 | 说明 |
|---|---|---|---|
| 4.16 | `App` 是上帝对象 | `app.go` struct **实测 100 个字段** | UI 状态、会话状态、Git 状态、调试状态、翻译缓存全在一个结构体;83 个文件同包自由访问,字段间隐式依赖靠注释维系 |
| 4.17 | 超长函数 | `menuItems` 251 行、`testEvent` 248 行、`settingsDialog` 119 行、`historyView` 104 行 | `menuItems` 是纯数据可接受;`testEvent` 是巨型 switch,新增事件类型时回归风险高 |
| 4.18 | 无 CI | 无 `.github/workflows`,只有 `build.cmd` | 171 个测试全在本地跑,没有"每次提交必须绿"的关口 |
| 4.19 | UI 层无自动化回归 | `tools/` 6 个工具均为手工调用 | 设计文档 55.4/67.5 的验证全靠人眼截图;`-tags e2e` 通路已通(`MYGO_AUTOMATION` + `tools/shot`),但没沉淀成用例 |
| 4.20 | 无扩展静态检查 | 只有 `go vet`(且手动触发) | 无 staticcheck / golangci-lint 接入点 |
| 4.21 | 单根工作区 | `startLSP(root)` 单 Root | 多模块/多仓库需开多窗口 |
| 4.22 | 工作区残留垃圾文件 | 根目录 `e2e.sock`、`e2e_run1/2/4.sock`、`e2e_shot1/2/4.png`、`e2e.exe~`、`MyGoland-e2e.exe~` | `.gitignore` 已挡住 `*.sock`/`e2e_shot*.png`,但 `*.exe~` 未挡;目录本身需要清理 |
### 4.23 已排除的"疑似问题"(避免误报)
以下曾被视为风险,核实后**不成立**或**已修复**:
| 项 | 结论 |
|---|---|
| 并发数据竞争 | `go test -race ./internal/app ./internal/git ./internal/task ./internal/ai ./internal/godoc` 全绿 |
| `go vet` 静态问题 | `go vet ./...` 全包无输出 |
| TODO/FIXME 遗留 | 全库 0 处 |
| 补全弹不出(时序) | 已修(`complete` 前先 `lspSync`),有回归测试 |
| hover 不翻译 | 已修(`RenderHover`) |
| 实时诊断不显示 | 已修(零长 range 扩展) |
| 双实例/窗口闪退 | 已修(单实例 TCP 握手 + `MYGO_AUTOMATION` 绕过) |
| 命令窗口闪窗 | 已修(全调用点 `SysProcAttr`),62.4 已全库复查 |
| 裸 panic | 仅 `main.go:23` 的 recover 后重抛,设计意图明确 |
| 变量只展开一层 | 已修(递归 + 求值,10.2) |
| 无条件断点 / goroutine 列表 | 已实现(设计文档 56.1 与 56.5 的表述互相矛盾,以代码为准) |
---
## 五、优先级建议
排序依据:**影响面 × 发生频率 ÷ 修复成本**。
### 立刻做(合计约 3 小时,全是确定性缺陷)
| 序 | 项目 | 成本 | 收益 |
|---|---|---|---|
| 1 | 接回标签右键菜单(4.1) | 30 min | 恢复 5 个已实现但不可达的功能 |
| 2 | 修 UTF-8 字节截断(4.2) | 30 min | 消除中文乱码 |
| 3 | 覆盖率保留测试输出 + 失败提示(4.4) | 1 h | 测试失败不再无感知 |
| 4 | `.gitignore` 感知 + `vendor` 排除 + 截断提示(4.6/4.7) | 1 h | 真实 Go 项目可用性 |
### 本周做(合计约 1.5 天)
| 序 | 项目 | 成本 | 收益 |
|---|---|---|---|
| 5 | 删除走回收站(4.3) | 4 h | 唯一的数据丢失风险口 |
| 6 | 参数支持引号切分 + 运行配置加 Env/WorkDir(4.8) | 3 h | 真实项目运行必需 |
| 7 | 日志轮转(4.9) | 30 min | 崩溃排查证据不丢 |
| 8 | 标签显示同名区分(4.14) | 1 h | 多目录同名文件不再混淆 |
| 9 | 编辑器右键菜单(4.5) | 4 h | 交互完整性(框架已有 → 改为补应用层 16 项) |
> **执行状态(2026-11-05)**:第 1–9 项**全部完成**并各自带测试,`go build ./... && go vet ./... && go test ./...` 全绿,`gofmt -l .` 为空。第 9 项按 4.5 的勘误改了做法:不重造菜单,只在框架的 `State.ContextMenu` 追加点补应用层动作。
### 规划做(按需,1–2 周量级)
| 序 | 项目 | 说明 |
|---|---|---|
| 10 | 代码动作分文件级/选区级(4.12) | ✅ 已完成,见 4.12 的实测更正 |
| 11 | 移动包时同步改 `package` 与 import(4.13) | Go 特有刚需,可基于 gopls rename 实现 |
| 12 | Git 分支 / stash / blame | 协作场景才需要,单机自用可缓 |
| 13 | 调试 watch + attach | 并发与线上问题排查才需要 |
| 14 | `-race` / `-bench` 开关 | 低成本高价值,可提前到"本周做" |
| 15 | CI + e2e 冒烟用例 3–5 条 | 把 67.5 的手工验证沉淀下来,防回归 |
### 明确不做(沿用 56.3 的判断,本次复核仍成立)
插件系统、多光标/IME/超大文件(等上游框架)、远程开发、数据库/SQL 工具、`go.mod` 依赖图可视化、完整重构集(改签名)。
---
## 六、可执行改进方向(落到文件与函数)
### 6.1 标签右键(4.1)
```go
// internal/app/view.go tabBar 内,标签容器 Children 里追加:
if open.RightClicked() {
a.active = d.path
a.openPop(open, a.tabEntries(d.path))
}
```
注意:`openPop(anchor ui.Element, entries []menuEntry)` 的第一个参数是**本帧的锚点元素**,函数内部立刻取 `anchor.Bounds()` 只保存矩形——因为 `ui.Element` 跨帧使用会 panic(`element from pass N used in pass N+1`),而面板下一帧才画。文件树(`view.go:342`)是现成参照。
### 6.2 UTF-8 截断(4.2)
```go
// 复用 gitlog.go 的 trimTo,或提到公共文件:
func trimRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n { return s }
return string(r[:n]) + "…"
}
```
替换 `palette.go:266`(160)与 `rename.go:86`(140)。单测覆盖:纯 ASCII 不截、中文边界、含 emoji 的 4 字节字符。
### 6.3 覆盖率输出(4.4)
```go
// coverage.go
// 注意:task.Task.Wait() 没有返回值(`func (t *Task) Wait() { <-t.done }`),
// 退出状态要用 ExitCode(),未结束时为 -1。
t.Wait()
code := t.ExitCode()
a.win.Update(func() {
a.cover.running = false
if code != 0 {
a.appendOut(fmt.Sprintf("覆盖率:测试未全部通过(exit %d),结果仅供参考", code))
for _, ln := range lines { a.appendOut(ln) } // 失败详情进面板
}
...
})
```
若输出量太大,只回放含 `FAIL`/`--- FAIL`/`.go:` 的行,其余折叠成「另有 N 行」。
### 6.4 `.gitignore` 感知(4.6)
`skipDir`/`skipFile` 改为由工作区级配置驱动:
1. 启动/换工作区时读根 `.gitignore`,用 `path.Match` 展开为前缀集合(不追求完整 gitignore 语义,覆盖 `dir/`、`*.ext`、`/abs` 三类即可);
2. 内置追加 `vendor`、`dist`、`build`、`out`、`.next`、`target`;
3. 命中超 20000 上限时,在快速打开/搜索面板顶部显示「索引已截断至 20000 个文件」而不是静默。
### 6.5 删除走回收站(4.3)
Windows 分支新增 `trash_windows.go`:
- 首选 `SHFileOperationW` + `FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT`(纯 syscall,无新依赖);
- 非 Windows 保持 `os.Remove`;
- `fileops.go:182` 改为 `moveToTrash(p)`,失败时回退到「再确认一次后 `RemoveAll`」。
### 6.6 运行配置扩展(4.8)
`runConfig` 加 `Env map[string]string`、`WorkDir string`、`Tags string`、`GOOS/GOARCH string`;参数解析改用 `parseArgs`(支持双引号包裹、`\` 转义),约 60 行 + 单测。`dap.Start` 与 `task.Start` 都需要透传 Env/WorkDir。
### 6.7 架构减债(4.16/4.17)
不建议现在做大重构(15,000 行、单人维护、重构收益低于功能收益)。可以做的两个低成本动作:
1. **按职责切 struct 字段**:把 `App` 里的 `gitState`/`debugSession`/`testState`/`coverState`/`histView` 抽成独立 struct 字段(已经基本是了),新增功能时优先落到新文件而不是继续往 `app.go` 加函数;
2. **`testEvent` 拆分**:按事件类型(output/fail/run end)拆成 3–4 个函数,巨型 switch 只做分派。风险最低、收益是可读性。
### 6.8 工程化(4.18/4.19)
1. `build.cmd` 加 `go vet ./... && go test ./... -timeout 480s` 两行,作为提交前自检;
2. 把 67.5 的 e2e 流程固化成 `tools/e2e/main.go` 场景脚本(起 e2e 实例 → 发 automation 指令 → `tools/shot` 截图 → 像素断言),先覆盖 3 条:波浪线出现、补全弹窗、标签右键;
⚠️ **右键菜单走不了自动化插座**:框架文档 `docs/plugins/automation.md` 明确写着「open context menus are left out —— 系统弹菜单会进自己的事件循环,各平台不能统一选择,所以**不要用 `input` 右击去开菜单**;用 `ui.Tester` 的 `RightClick`/`ChooseMenuItem` 测」。编辑器右键菜单就是这么测的,见 `internal/app/editor_menu_test.go` 的 `TestEditorMenuShowsInEditor`:`ui.NewTester` 里挂一个 `editor.View`,`RightClickAt` 之后 `tt.Menu()` 直接给出菜单文案,`tt.ChooseMenuItem` 还能断言「灰掉的项点不动」。
3. 有远端(`git.zerorigin.cn`)的前提下,加 cron 或 pre-push hook 跑 `go test ./...`。
---
## 七、附录:如何手工复核本报告的关键结论
下表是**修复前**的现象。1–10 项已于 2026-11-05 修掉,留着它是为了以后回归时能照着复现。
| 结论 | 复核步骤 | 修复前的现象 |
|---|---|---|
| 标签右键缺失(4.1) | 打开 2 个以上文件 → 右键标签页 | 无菜单弹出(对比:右键文件树行有菜单) |
| UTF-8 截断(4.2) | 造一行 >160 字节的中文 → Ctrl+Shift+F 搜索 | 命中行尾部出现 `�` 或乱码 |
| 覆盖率吞输出(4.4) | 故意让一个测试失败 → 运行「统计覆盖率」 | 只能看到覆盖率数字/失败提示,看不到断言详情 |
| 删除不进回收站(4.3) | 复制一个小文件 → 右键删除 → 查回收站 | 回收站里没有 |
| `.gitignore` 不生效(4.6) | 在 `.gitignore` 写 `dist/` → 放个文件到 `dist/` → Ctrl+P 搜它 | 能搜到 |
| 参数空格(4.8) | 运行配置 Args 填 `-tags "a b"` | `go run` 报 tag 拆断 |
| 标签同名不区分(4.14) | 打开两个目录下的 `main.go` | 两个标签显示一样的 `main.go` |
---
## 八、一句话总结
**这套 IDE 的能力密度已经超过「自用够用」的临界点**——补全、诊断、调试、测试、Git 五条主链路都在,且逻辑层有 171 个测试兜底。
当前最值得投入的不是加新功能,而是**把已经写好但没接通的线接回去**(标签菜单 160 行死代码)、**把静默失败改成有反馈**(覆盖率输出、索引截断、日志删除)、**把不可逆操作变可逆**(删除进回收站)。这三件事加起来不到两天,收益大于再做一个新模块。
---
**后续(同日晚)**:上面这三件事连同"本周做"共 9 项已全部实施完毕,每项都配了测试,全量 `go test ./...` 绿。唯一需要更正原报告的是 4.5——编辑器右键菜单本来就由框架提供,应用层只是在框架的追加点上补了自己的动作;这也说明**评估里"框架未读源码验证"的那类限定不是免责声明,而是待办项**,复核时确实翻转了结论。
下一批该做的(规划做里的前两项):移动目录时同步改 `package` 与 `import`(Go 特有刚需,可基于 gopls rename 实现)、Git 分支/stash/blame。
---
**追加(同日晚,第 10 项)**:代码动作的请求范围已修完。有意思的是它和 4.5 犯了同一类错——**原报告又一次没验证框架/服务端的实际行为就下了结论**。这次用真 gopls 探测,把「生成测试取不到」「零宽位置丢快速修复」两个想当然的判断都推翻了,真正的缺口是「选区被忽略」和「浏览类命令淹没有效动作」。两条改动的证据都在 `internal/lsp/codeaction_test.go` 里,gopls 升级导致前提变化时会直接红。
---
**依赖升级(同日晚)**:`github.com/egoist/mygo` 由 v0.7.2 升到 **v0.7.4**(落后两个补丁版本),已落地。
升级前后逐文件 diff 过一遍,影响面先说清楚:
| 变化 | 对本项目 |
|---|---|
| `ui/editor` 的 `paintBlock` 加了 `top float64` 参数 | **接口变更**,但本项目只用 `editor.View(c, d.st)`,没有自定义 `decor` 实现,不受影响 |
| `scrollbars()` 判据结构不变,滑块改为「指针在编辑器上或拖着它时才画」 | 行为变化,见下 |
| `dialog.go` 新增 `DestructiveButtons []int` | 已用在 `fileops.go` 的删除弹窗(索引 1 = 永久删除);Windows 的 task dialog 无此概念,macOS 11+ 才生效 |
| `modules.go` 的 `Notification.ShowContext`、`Tray.Bounds` 文档 | 与本项目无关 |
| 新增 `ui.Scrollbar`、`ui.DecimalInput`、`ui.PopoverMenuButton`、`ui.Themed`、`Context.Instant()` | 备用,暂无接入点 |
| `state.go` / `commands.go` / `selection.go` / `build.go` | **零改动**,第 9 项依赖的 `State.ContextMenu`、`ui.Menu`、`ui.Tester` 保持稳定 |
验证方式不是"看 release note",是三层实测:`go build ./... && go vet ./...` 全绿;`go test -count=1 ./internal/lsp ./internal/app` 全绿(54s + 17s,含真 gopls 与 `ui.Tester` 的右键菜单用例);再用 `-tags e2e` 分别编译 v0.7.2 与 v0.7.4 两个二进制,打开同一个 243 行文件逐像素对比——**差异只落在编辑器右边缘的滚动条滑块上**:v0.7.2 常驻一条深色滑块,v0.7.4 指针不在编辑器上时不画(移上去才出现,与 VS Code 同款)。这是设计改进,不是回归;点击命中区仍由 `scrollbars()` 的 `scrollMax() > 0` 决定,拖拽功能没丢。
`view.go` 的 `NoScrollPastEnd = true` 这个 workaround **仍然必要**:`scrollMax()` 在 v0.7.4 里逻辑没变(`scrollPastEnd` 为真时仍是 `total - lineHeight`),短文件照样大于 0,不关的话鼠标一移进编辑器就会冒出一条满轨滑块。已在注释里补上这一层说明,免得以后误以为可以删。
对照组实验还顺带排掉一个误判:长文件截图里编辑区只显示 11 行、下方面板占了大半窗口——这**不是** v0.7.4 造成的,v0.7.2 二进制渲染结果逐像素相同,是 e2e 工作区里 splitter 的既有状态。
+117
View File
@@ -0,0 +1,117 @@
# MyGoland 待办与规划
> 生于 2026-11-09,基线提交 `88067cc`(mygo v0.7.4);2026-11-12 升至 mygo v0.9.0、清空全部待办,并完成规划里的 P3 / P4。
> 配套阅读:`MyGoland-完善度评估-2026-11-05.md`(缺陷证据存档)、`MyGoland-vs-GoLand-差距分析.md`(对比视角)、`本地自检与CI.md`(三层守门怎么用)。
> 本文只记「还没做的」和「打算做的」——做完的项只留一行索引,不在这里堆历史。
## 现状
**待办 6 项 + 规划里的 P3 / P4 均已全部完成(2026-11-12)**,本文剩下 4 项按需规划。
```
verify.cmd 一层命令跑完 gofmt / vet / test,实测通过
go test ./... 全绿,286 个 Test 函数
go test -race 并发/剪贴板/回滚用例无数据竞争
go run ./tools/e2e 4/4 冒烟场景通过
```
---
## 一、规划:新能力(4 项)
这些不是缺陷,是「有更好」。
| 序 | 项目 | 现状 | 收益 | 粗估 |
|---|---|---|---|---|
| P1 | **Git 分支 / stash / blame** | 只有日志与 diff(`gitlog.go`);无 branch、无 stash、无 blame | 协作场景必需;单机自用可缓 | 2–3 天 |
| P2 | **调试 watch + attach** | 有 DAP,无 watch 表达式、无 attach 到已有进程 | 并发与线上问题排查才需要 | 3 天 |
| P5 | **架构减债** | `App` struct 100+ 字段(`app.go`);`testEvent` 248 行巨型 switch | 可维护性;新增功能时不再往 `app.go` 堆 | 1–2 天(分批,不宜大重构) |
| P6 | **多根工作区** | `startLSP(root)` 单 Root | 多模块/多仓库免开多窗口 | 3–5 天,收益不确定 |
**P3 / P4 已完成**,做法、踩过的坑与 CI 启用前提全部记在 `本地自检与CI.md`。一句话:P3 是测试面板顶部的 `-race` / `-bench` 会话级开关,参数统一注入结果树、输出面板、覆盖率三个 `go test` 入口;P4 是 `verify.cmd` + `.gitea/workflows/ci.yml` + `tools/e2e` 四条冒烟场景。
**P5 的边界**:不建议现在做大重构(单人维护、重构收益低于功能收益)。只做两件低成本的事——按职责切 `App` 的字段组、把 `testEvent` 的巨型 switch 拆成 3–4 个函数。
---
## 二、明确不做(沿用两份文档的判断,复核后仍成立)
| 项目 | 理由 |
|---|---|
| 插件系统 | 没有第三方生态,只是给自己加抽象层 |
| 远程开发 | 需要客户端 + 服务端分离,是产品级重构,不是功能 |
| 数据库 / SQL 工具 | 工作量相当于再造 DataGrip,Navicat / SSMS 已够用 |
| K8s / Docker 深度集成 | 终端跑 `kubectl`/`docker` 没有损失,做 UI 是负债 |
| 完整重构集(改签名 / 安全删除) | gopls 不支持的部分做不到位,能用的已经能用 |
| AI 补全 | 是模型与推理成本问题,与 IDE 解耦更合适 |
| 拼写检查 / 风格强约束 | Go 生态已有 `gofmt` / `golangci-lint` |
| 多光标 / IME / 超大文件 | 等上游 mygo(本项目没有自定义渲染层,改不动) |
---
## 三、验证基线
任何一项做完,以下必须全绿才算完成:
```bash
verify.cmd # gofmt + vet + test 一道跑(Windows)
go build ./...
go test ./... -count=1 # 基线:286 个 Test 函数全过
go run ./tools/e2e # UI 改动时,4 条冒烟场景
```
涉及 UI 的改动额外要求跑 `go run ./tools/e2e`。脚本自己起实例、造临时工作区、断言并清理,不依赖用户当前窗口;细节见 `本地自检与CI.md`。**不接受「看起来应该没问题」**。
涉及第三方行为(gopls / 框架)的改动,**先写探测再改代码**。本轮 T1、T3 的前提都是这么测出来的,两次都改变了实施方案。
---
## 四、建议顺序
守门已经建好,剩下 4 项都是「按需」,没有时间压力:
| 优先级 | 项目 | 触发条件 |
|---|---|---|
| 较高 | P1 Git 分支 / stash / blame | 开始多人协作、需要在 IDE 里切分支时 |
| 中 | P2 调试 watch + attach | 排查并发问题或需要附加到已有进程时 |
| 低 | P5 架构减债 | 再往 `App` 加字段开始觉得别扭时分批做 |
| 低 | P6 多根工作区 | 真的要同时开多个模块时,且收益不确定 |
建议先不再加功能,用一阵子看哪条链路最硌手,再按实际痛点挑一项。
---
## 附 A:2026-11-12 完成的待办(仅索引)
| 项 | 落地位置 | 关键验证 |
|---|---|---|
| T1 移动包同步 | `internal/app/movepkg.go` + `renameentry.go` | 临时 Go 模块里移目录后 `go build ./...` 直接通过;含回滚与中文注释误伤用例 |
| T2 输出/问题面板右键 | `internal/app/panel_menu.go` + `output.go` | 真窗口右键截图,菜单贴指针弹出、无裁切 |
| T3 snippet 补全 | `internal/app/completion_snippet.go` + `internal/lsp/protocol.go` | 真 gopls 回归固化 `insertTextFormat=2` / `Print(${1:})` |
| T4 历史上限可见 | `internal/app/history.go` | `histSkipped` 类型 + 每文件只提示一次 |
| T5 全局搜索并发 | `internal/app/palette.go` | 24 文件顺序稳定性 + `-race` 无竞争 + 512KB 跳过提示 |
| T6 清理残留 | 工作区根目录 | 释放 23.6 MB;4 个 0 字节 `.sock` 被环境安全守卫拦住,未删(已被 gitignore,无影响) |
| P3 `-race` / `-bench` | `internal/app/testflags.go` + `testrun.go` / `output.go` / `coverage.go` | 4 条参数组合单测;`-run` 已存在时不覆盖;勾 `-bench` 走输出面板看 ns/op |
| P4 自检与冒烟 | `verify.cmd`、`build.cmd`、`.gitea/workflows/ci.yml`、`tools/e2e/main.go` | `verify.cmd` 全绿、`GOOS=linux` 交叉编译通过、`go run ./tools/e2e` 连跑两次均 4/4 |
**两处刻意缩窄的范围**:
1. T1 **不改 package 名**。Go 不要求目录名等于包名,改包名还得连带改所有 `xxx.Func` 限定符,风险远大于收益;只有「单文件跨目录移动」时才把该文件的 `package` 声明对齐目标目录。
2. T2 **只补输出/问题面板**。终端从 mygo v0.7.4 起就自带右键菜单(`plugins/terminal` 的 `e.ContextMenu(v.menu)`,原生菜单在 automation 插座里看不到),原判断「终端无菜单」是误报。
---
## 附 B:五次「没验证就下结论」的教训
| # | 原判断 | 实测结论 | 来源 |
|---|---|---|---|
| 1 | 编辑器没有右键菜单 | 框架自带,应用层只是没往里加东西 | 评估报告 4.5 |
| 2 | 「生成测试」取不到、零宽位置丢快速修复 | 都取得到;真问题是选区被忽略、浏览命令淹没 | 评估报告 4.12 |
| 3 | 移动包「可基于 gopls rename 实现」 | gopls 不声明 `willRename`,得自己实现 | T1 |
| 4 | 终端没有右键菜单 | `terminal.View` 自带原生 `ContextMenu`,v0.7.4 就有 | T2 |
| 5 | 框架不支持 snippet、要自己造轮子 | 写下三天后 mygo v0.9.0 补上了 `ParseSnippet` / `InsertSnippet` | T3 |
共同点:**把「代码里没看到」当成「能力不存在」**,以及**把某个版本的现状当成永久事实**。两条防线:
- 凡涉及第三方服务端行为,先写 20 行探测代码问它一句,比读十篇文档都准;
- **「前提」有保质期**。升级依赖后要回头扫一遍标注「前提」的项,别拿旧结论继续估工时。
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+81
View File
@@ -2225,3 +2225,84 @@ bufio/bytes/sort 的补全与悬停现在全部秒出中文。
## 68. 完善度评估后的四项修复(2026-11-05)
按 `docs/MyGoland-完善度评估-2026-11-05.md` 的优先级执行,四项全部落地。
### 68.1 标签页右键菜单接回(60 行死代码复活)
**问题**:`tabmenu.go` 160 行完整实现(关闭左/右/其他/全部/已保存)全库零调用点,
`tabBar` 只处理 `Clicked`。`docs/tab-context-menu-1.png` 证明它曾能用——重写标签栏时漏接。
**修法**:`view.go` 的标签按钮补 `RightClicked()` → `openPop(open, tabEntries(path))`。
右键时先把该标签设为 active:菜单本身没有标题,「关闭左边(3)」这类文案
必须靠标签高亮才能确定是相对谁算的。
```
button press,focus 405,74 关闭
button press,focus 405,99 关闭左边(1)
button press,focus 405,134 关闭其他(1)
button press,focus 405,159 关闭全部(2)
button press,focus 405,194 关闭已保存的(2)
```
(末标签没有「关闭右边」,符合 `idx < n-1` 的判断。)截图存 `docs/tab-context-menu-restored.png`。
新增 `tabmenu_test.go` 8 个单测:docIndex、savedPaths、中间/首/末/单标签的条目集合、
全脏时「关闭已保存的」置灰、路径不存在返回 nil、区间越界不 panic。
### 68.2 中文按字节截断导致乱码
**问题**:`palette.go` 的搜索命中行 `trimmed[:160]`、`rename.go` 的 `linePreview` `s[:140]`
按**字节**切;一个汉字 3 字节,160÷3 落在字符中间 → 非法 UTF-8。
同项目 `gitlog.go` 的 `trimTo` 用的是 `[]rune`,属于局部正确、全局不一致。
**修法**:`trimTo` 提到新文件 `strutil.go`(三个调用方共用,语义不再绑在 git 日志上),
两处改为 `trimTo(s, 160)` / `trimTo(s, 140)`。`n<=0` 返回空串,调用方不用先判长度。
`strutil_test.go` 5 个单测 + 1 个走真实调用路径的 `TestLinePreviewChinese`
(写一个 200 字的中文行进临时文件,断言预览是合法 UTF-8 且截到 140 字)。
### 68.3 覆盖率运行吞掉测试输出
**问题**:`coverage.go` 收集了 `t.Lines` 全部输出,然后 `_ = lines` 丢掉。
测试失败时用户只看到覆盖率数字,看不到失败原因——覆盖率页又不显示日志,等于没有提示。
**修法**:
- `Task.Wait()` 没有返回值,退出状态用 `t.ExitCode()`(未结束为 -1)判断;
- 失败时不刷屏:只回放 `FAIL` / `--- FAIL` / `panic:` / `# 包` / 带 `file.go:12:` 的行,
上限 200 行,超出给「已截断」;
- 覆盖率页顶部出现红底提示行「N 个包失败 · M 个用例失败(退出码 1),覆盖率数字仅供参考」,
右侧「查看测试输出」按钮切到运行页。
- `coverState` 新增 `failMsg`;`coverageFailLines` / `coverageFailSummary` 是纯函数,5 个单测。
### 68.4 搜索与索引不感知 .gitignore
**问题**:`skipDir` 只硬编码 `.git/.idea/.mygoland/node_modules`。
Go 项目开了 `vendor/` 后索引里塞进几千个第三方包,快速打开与全局搜索全是噪音;
超过 20000 文件 `filepath.SkipAll` 静默截断,用户会把「搜不到」当成「不存在」。
**修法**:
- 新增 `ignore.go`:解析根 `.gitignore`,支持 `dir/`、`*.ext`、`/rootonly`、带路径、
`**` 跨层、`!` 取反、注释。**明确不做**完整 git 语义(嵌套 .gitignore、
`\` 转义、`[]` 字符类)——漏一条规则最多多收录几个文件,不会出错。
- 内置跳过清单扩到 `.git/.idea/.mygoland/node_modules/vendor/dist/build/out/target/.next`;
文件树仍用保守的 `skipDir`(vendor 有时要翻代码),索引/搜索用 `isBuiltinSkipDir`。
- `indexState` 加 `truncated`,`indexFileCap` 取代散落的 20000;
快速打开面板底部显示「索引已截断至 20000 个文件」。
- `ignore_test.go` 10 个单测 + `TestBuildIndexRespectsIgnores`(真实目录遍历:
vendor/dist/logs 都不进索引,正常源码不被误杀)。
### 68.5 验证
| 项 | 方法 | 结果 |
|---|---|---|
| 标签右键 | e2e 实例 + `tools/tree` 查菜单项 + `tools/shot` 截图 | 5 项齐全,菜单贴标签下方 ✓ |
| 中文截断 | `TestLinePreviewChinese` 等 6 个 | 合法 UTF-8、140 字 ✓ |
| 覆盖率失败提示 | `coverageFailLines/Summary` 5 个单测 | 保留用例行/断言行/编译错误,丢 ok 行 ✓ |
| .gitignore | `TestBuildIndexRespectsIgnores` 真实遍历 | vendor/dist/logs 均被排除 ✓ |
| `go vet ./...` | — | 干净 ✓ |
| `go test ./internal/...` | 7 个包 | 全绿 ✓ |
**e2e 踩坑记录**:Windows 上已存在的 socket 文件删不掉(`rm` 被安全策略拦,
Go bind 报 address in use),验证脚本必须每次换一个 socket 文件名。
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+66
View File
@@ -0,0 +1,66 @@
# 本地自检与 CI
> 2026-11-12 建立。三层守门,判据完全一致,不搞「本地一套、CI 一套」。
## 一、三层守门
| 层 | 入口 | 跑什么 | 什么时候用 |
|---|---|---|---|
| 本地自检 | `verify.cmd` / `build.cmd verify` | `gofmt -l`、`go vet ./...`、`go test ./... -count=1 -timeout 480s` | 提交前、发版前 |
| 远端 CI | `.gitea/workflows/ci.yml` | 同样三条,外加 `go build ./...` | push 到 `main` / PR(需实例启用 Actions) |
| UI 冒烟 | `go run ./tools/e2e` | 起真实例,4 条端到端场景 | UI 改动后、发版前 |
三条判据在 `verify.cmd` 和 workflow 里逐字对应,改了一处要同步另一处。
## 二、本地自检用法
```bat
verify.cmd :: 只自检,约 90 秒
build.cmd verify :: 自检通过才构建 MyGoland.exe
build.cmd :: 跳过自检,直接构建
```
`verify.cmd` 里 `gofmt -l .` 的输出用 `findstr` 判空——只要有一行非空就失败并列出文件。脚本全部是 ASCII,因为 Windows `cmd` 按系统代码页(GBK)读 `.cmd`,UTF-8 中文注释会被当成命令执行。
## 三、远端 CI 的前提(重要)
远端 `https://git.zerorigin.cn` 是 **Gitea 企业版**。Gitea Actions 使用与 GitHub Actions 兼容的语法,配置文件放 `.gitea/workflows/`。
**但工作流是否真的运行,取决于实例侧配置,仓库里控制不了**:
1. 管理员需在 Gitea 启用 Actions(`ENABLE_ACTIONS`);
2. 需注册并在线一个带 `ubuntu-latest` 标签的 runner;
3. runner 需要能访问 `actions/checkout@v4` / `actions/setup-go@v5`(内网可能无法拉 GitHub 上的 action)。
上述任一不满足时,这个 YAML **不会被触发,也不会报错**,只是安静地不运行。所以它不能替代 `verify.cmd`。要确认是否已生效,push 后去仓库的 Actions 页看有没有 run 记录。
已验证的部分:`GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build ./...` 在本机交叉编译通过,因此 Linux runner 上编译这一步本身不应因平台代码失败。未实测 runner 实际执行。
## 四、e2e 冒烟
```bash
go run ./tools/e2e # 4 条场景,退出码反映结果
go run ./tools/e2e -keep # 保留截图与日志到临时目录,排查失败用
go run ./tools/e2e -bin e2e.exe # 复用已编译的 -tags e2e 二进制,省一次编译
```
脚本自己完成:建临时 Go 模块工作区 → 编译 `-tags e2e` 二进制 → 以 `MYGO_AUTOMATION=<socket>` 启动并**把工作区目录作为启动参数**(`openFromArgs`)→ 连插座 → 跑场景 → 杀进程、删临时目录。不碰用户当前打开的窗口,也不依赖会话存档。
| # | 场景 | 断言 |
|---|---|---|
| 1 | 启动渲染 | 窗口存在、无障碍树 ≥8 节点、截图颜色数 ≥12(排除全黑/全白) |
| 2 | 工作区与 gopls | 文件树出现 `main.go`、状态栏 `gopls 就绪`、点开 `broken.go` 后编辑器出现 |
| 3 | 诊断到达 | 切到「问题」页签,出现 `broken.go` 的诊断条目 |
| 4 | 输出面板右键菜单 | 右键 `ui.List` 后,自绘菜单含「复制选中行 / 复制全部输出 / 清空输出」 |
### 两个踩过的坑
1. **全新会话默认底部面板是关的**。手工验证时面板常开是会话存档记住了状态;脚本里加了 `ensurePanel`,先点状态栏的「面板」按钮再找页签。
2. **「运行」这个名字有两个按钮**:底部页签栏一个,右上角一个(点了会真的跑程序)。用 `role == button && label == "运行" && X < 700` 把它们分开,别按 label 全局找第一个。
### 已知限制
- **系统原生右键菜单测不了**:框架 `docs/plugins/automation.md` 明确说弹出的原生菜单进自己的事件循环、各平台无法统一选择。编辑器与终端的右键菜单要用 `ui.Tester` 的 `RightClickAt` / `Menu()` / `ChooseMenuItem` 在单测里覆盖(参照 `internal/app/editor_menu_test.go`)。
- **像素断言只防「全黑」,不防布局细微错位**。看截图仍需人眼或专门裁剪放大。
- **gopls 必须在 PATH**:场景 2/3 依赖语言服务器,没装会超时失败。
- 场景 4 依赖本项目的**自绘**菜单(`ui.Overlay`),这正好是插座能看到的;换成原生菜单后该场景会失效。
+1 -1
View File
@@ -3,7 +3,7 @@ module mygoland
go 1.27.3 go 1.27.3
require ( require (
github.com/egoist/mygo v0.7.2 github.com/egoist/mygo v0.9.0
golang.org/x/text v0.43.0 golang.org/x/text v0.43.0
) )
+4
View File
@@ -2,6 +2,10 @@ github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6Xe
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/egoist/mygo v0.7.2 h1:ITbzb9+u8GXjDZFkHsnIiBRayV7WQPFzM3whsIOm7F8= github.com/egoist/mygo v0.7.2 h1:ITbzb9+u8GXjDZFkHsnIiBRayV7WQPFzM3whsIOm7F8=
github.com/egoist/mygo v0.7.2/go.mod h1:dVav53PwF2xEotjf4oA5lTY2Jp2exgzyjLhbSXhbMwE= github.com/egoist/mygo v0.7.2/go.mod h1:dVav53PwF2xEotjf4oA5lTY2Jp2exgzyjLhbSXhbMwE=
github.com/egoist/mygo v0.7.4 h1:0qkDpDRo7C9g8PM8eu4V6FVouhLiTrUdqKD6I31Lv3Q=
github.com/egoist/mygo v0.7.4/go.mod h1:dVav53PwF2xEotjf4oA5lTY2Jp2exgzyjLhbSXhbMwE=
github.com/egoist/mygo v0.9.0 h1:zGeZTskZ7HNTrKdkh/uEX+OOg+7YTjFMNjiTdie7XU4=
github.com/egoist/mygo v0.9.0/go.mod h1:Hw9sxdSQ4tHuehHw5Q6alR1qTS8kgv3oSFxEejg+7qo=
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk= github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68= github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68=
github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY= github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY=
+52 -28
View File
@@ -2,13 +2,17 @@ package app
import ( import (
"context" "context"
"fmt"
"strings" "strings"
"time" "time"
"mygoland/internal/lsp" "mygoland/internal/lsp"
) )
// CodeActions 请求光标所在行的代码动作并列进命令面板。 // CodeActions 请求光标处(或选区上)的代码动作并列进命令面板。
//
// 发两次请求:一次按光标/选区,一次按整文件只问 refactor.rewrite。为什么
// 要两次、为什么有选区就必须传选区,见 codeaction.go 的说明。
func (a *App) CodeActions() { func (a *App) CodeActions() {
d := a.doc() d := a.doc()
c := a.lsp c := a.lsp
@@ -16,45 +20,33 @@ func (a *App) CodeActions() {
a.alert("代码动作", "先把光标放到 Go 文件里") a.alert("代码动作", "先把光标放到 Go 文件里")
return return
} }
pos := d.st.CursorPos() reqs := codeActionRequests(d)
line := d.buf.Line(pos.Line)
col := pos.Col
if col > len(line) {
col = len(line)
}
rng := lsp.Range{
Start: lsp.Position{Line: pos.Line, Character: 0},
End: lsp.Position{Line: pos.Line, Character: lsp.UTF16Len(line)},
}
// 把这一行的诊断**原样**带上:gopls 的「添加 import」「删除未使用变量」
// 这类快速修复靠诊断里的 data 字段匹配,重新拼一份就没用了。
var diags []lsp.Diagnostic
for _, dd := range d.diags {
if dd.Range.Start.Line <= pos.Line && pos.Line <= dd.Range.End.Line {
diags = append(diags, dd)
}
}
uri := d.uri uri := d.uri
go func() { go func() {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel() defer cancel()
acts, err := c.CodeActions(ctx, uri, rng, diags) acts, raw, err := queryCodeActions(ctx, c, uri, reqs)
if err != nil {
a.win.Update(func() { a.alert("代码动作失败", err.Error()) })
return
}
if len(acts) == 0 { if len(acts) == 0 {
a.win.Update(func() { a.alert("代码动作", "这里没有可用的动作") }) msg := "这里没有可用的动作"
switch {
case err != nil:
msg = err.Error()
case raw > 0:
msg = fmt.Sprintf("这里有 %d 项,但都只是打开文档/汇编之类的浏览命令,已隐藏", raw)
}
a.win.Update(func() { a.alert("代码动作", msg) })
return return
} }
items := make([]paletteItem, 0, len(acts)) items := make([]paletteItem, 0, len(acts))
for i, act := range acts { for i, act := range acts {
hint := actionKindLabel(act.Kind)
if act.IsPreferred && hint != "" {
hint = "推荐 · " + hint
}
items = append(items, paletteItem{ items = append(items, paletteItem{
Kind: itemFile, Kind: itemFile,
Label: act.Title, Label: act.Title,
Hint: actionKindLabel(act.Kind), Hint: hint,
Idx: i, Idx: i,
}) })
} }
@@ -79,12 +71,44 @@ func actionKindLabel(kind string) string {
return "重写" return "重写"
case strings.HasPrefix(kind, "refactor"): case strings.HasPrefix(kind, "refactor"):
return "重构" return "重构"
// 下面几个是 source 里少数真会改代码的,单独说清楚;
// 只标「源码」等于没说明它要干什么。
case strings.HasPrefix(kind, "source.addTest"):
return "生成测试"
case strings.HasPrefix(kind, "source.organizeImports"):
return "整理 import"
case strings.HasPrefix(kind, "source.fixAll"):
return "全部修复"
case strings.HasPrefix(kind, "source"): case strings.HasPrefix(kind, "source"):
return "源码" return "源码"
} }
return "" return ""
} }
// queryCodeActions 把请求发出去,再合并、过滤、排序。
//
// 从 CodeActions 里拆出来(而不是留在 goroutine 里),是为了能在测试里对着
// 真 gopls 跑整条管线:范围怎么算、诊断怎么带、噪音怎么滤、顺序怎么排,
// 一次断言到位。返回的 raw 是过滤前的条数,用来区分「真没有动作」和
// 「只有浏览类命令被滤光了」。
//
// 某一次请求失败不算整体失败:整文件那次挂了,光标处那次的结果照样能用。
func queryCodeActions(ctx context.Context, c *lsp.Client, uri string, reqs []actionRequest) (acts []lsp.CodeAction, raw int, err error) {
parts := make([][]lsp.CodeAction, 0, len(reqs))
for _, r := range reqs {
got, e := c.CodeActionsOnly(ctx, uri, r.rng, r.diags, r.only)
if e != nil {
if err == nil {
err = e
}
continue
}
raw += len(got)
parts = append(parts, got)
}
return rankActions(mergeActions(parts...)), raw, err
}
// applyAction 执行选中的代码动作。 // applyAction 执行选中的代码动作。
func (a *App) applyAction(i int) { func (a *App) applyAction(i int) {
if i < 0 || i >= len(a.actions) { if i < 0 || i >= len(a.actions) {
+12
View File
@@ -10,6 +10,7 @@ import (
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"sync"
"time" "time"
"unicode" "unicode"
@@ -160,6 +161,10 @@ type App struct {
diff diffView diff diffView
// test 是测试结果树的状态。 // test 是测试结果树的状态。
test testState test testState
// testRace / testBench 是测试面板上的会话级开关,不写进设置文件:
// -race 会明显拖慢测试,不该变成「不知什么时候被打开」的持久状态。
testRace bool
testBench bool
// cover 是覆盖率的状态。 // cover 是覆盖率的状态。
cover coverState cover coverState
// histView 是全屏历史视图(git / 本地共用)。 // histView 是全屏历史视图(git / 本地共用)。
@@ -258,6 +263,10 @@ type App struct {
// 标题栏整体是 DragWindow,按钮自己的 Clicked 收不到事件, // 标题栏整体是 DragWindow,按钮自己的 Clicked 收不到事件,
// 只能靠 PointerPosition 的命中来判断。 // 只能靠 PointerPosition 的命中来判断。
menuHits []menuHit menuHits []menuHit
// histWarned 记下哪些文件已经提示过「超过本地历史上限」。
// 自动快照每分钟一次,不去重会把输出面板刷满;每个文件整个会话只提一次。
histWarned sync.Map
} }
// New 创建一个未打开工作区的应用。 // New 创建一个未打开工作区的应用。
@@ -547,6 +556,9 @@ func (a *App) newDoc(abs, text string) *Doc {
d.st.OnCompletion = func(r editor.CompletionRequest) { a.complete(d, r) } d.st.OnCompletion = func(r editor.CompletionRequest) { a.complete(d, r) }
d.st.OnHover = func(r editor.HoverRequest) { a.hover(d, r) } d.st.OnHover = func(r editor.HoverRequest) { a.hover(d, r) }
d.st.OnDefinition = func(off int) { a.definition(d, off) } d.st.OnDefinition = func(off int) { a.definition(d, off) }
// 右键菜单补上框架没有的应用层动作(代码动作、跑测试、复制路径…)。
// 框架自带的那些仍在前半段,见 editor_menu.go 的说明。
a.attachEditorMenu(d)
// 补全面板自定义渲染:底部文档接 LLM 中文翻译(见 completion.go)。 // 补全面板自定义渲染:底部文档接 LLM 中文翻译(见 completion.go)。
d.st.RenderCompletions = a.renderCompletions d.st.RenderCompletions = a.renderCompletions
// 悬停卡片同理:文档正文翻译,签名与链接行保留。 // 悬停卡片同理:文档正文翻译,签名与链接行保留。
+88
View File
@@ -0,0 +1,88 @@
package app
import "strings"
// parseArgs 把运行配置里的参数串切成参数列表。
//
// 为什么不能用 strings.Fields:`-tags "integration e2e"` 会被切成四个,
// go 收到 -tags 的值就只剩 integration;路径带空格(D:\My Work\a.txt)同理。
//
// 规则按 POSIX shell 的常见子集实现:
// - 空白(空格 / 制表符)分隔
// - 双引号包住的一段算一个参数,内部 \" 与 \\ 转义
// - 单引号包住的一段算一个参数,内部不转义(与 shell 一致)
// - 引号外**不**处理反斜杠——Windows 路径 D:\a\b 必须原样保留
// - 引号没闭合时按到结尾处理,不报错(参数写到一半就运行是常事)
func parseArgs(s string) []string {
var out []string
var cur strings.Builder
inWord := false // 当前是否已经在一个参数里(区分空参数 "" 与没有参数)
i := 0
for i < len(s) {
c := s[i]
switch {
case c == ' ' || c == '\t' || c == '\r' || c == '\n':
if inWord {
out = append(out, cur.String())
cur.Reset()
inWord = false
}
i++
case c == '"':
inWord = true
i++
for i < len(s) && s[i] != '"' {
if s[i] == '\\' && i+1 < len(s) && (s[i+1] == '"' || s[i+1] == '\\') {
cur.WriteByte(s[i+1])
i += 2
continue
}
cur.WriteByte(s[i])
i++
}
i++ // 跳过收尾引号(未闭合时 i 已越界,下面循环自会结束)
case c == '\'':
inWord = true
i++
for i < len(s) && s[i] != '\'' {
cur.WriteByte(s[i])
i++
}
i++
default:
inWord = true
cur.WriteByte(c)
i++
}
}
if inWord {
out = append(out, cur.String())
}
return out
}
// envFromLines 把「每行一个 KEY=VALUE」的配置转成 map。
//
// 空行与 # 开头的行跳过;没有等号的行忽略(写错一行不该让整份配置失效)。
func envFromLines(s string) map[string]string {
var out map[string]string
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
if k == "" {
continue
}
if out == nil {
out = make(map[string]string)
}
out[k] = strings.TrimSpace(v)
}
return out
}
+122
View File
@@ -0,0 +1,122 @@
package app
import (
"strings"
"testing"
)
// TestParseArgsBasic 空白分隔。
func TestParseArgsBasic(t *testing.T) {
got := strings.Join(parseArgs("a b\tc"), "|")
if got != "a|b|c" {
t.Fatalf("got %q", got)
}
if got := parseArgs(" "); got != nil {
t.Fatalf("全空白应返回 nil,得到 %v", got)
}
if got := parseArgs(""); got != nil {
t.Fatalf("空串应返回 nil,得到 %v", got)
}
}
// TestParseArgsQuoted 双引号包住的一段算一个参数(这正是 strings.Fields 做不到的)。
func TestParseArgsQuoted(t *testing.T) {
got := parseArgs(`-tags "integration e2e" -v`)
if len(got) != 3 {
t.Fatalf("应切成 3 段,得到 %v", got)
}
if got[0] != "-tags" || got[1] != "integration e2e" || got[2] != "-v" {
t.Fatalf("got %v", got)
}
}
// TestParseArgsEscapedQuote 双引号内 \" 与 \\ 转义。
func TestParseArgsEscapedQuote(t *testing.T) {
got := parseArgs(`--msg "say \"hi\""`)
if len(got) != 2 || got[1] != `say "hi"` {
t.Fatalf("got %v", got)
}
got = parseArgs(`--path "C:\\tmp\\a"`)
if len(got) != 2 || got[1] != `C:\tmp\a` {
t.Fatalf("双引号内的 \\\\ 应还原成单反斜杠:%v", got)
}
}
// TestParseArgsWindowsPath 引号外的反斜杠必须原样保留。
//
// 这是 Windows 上最容易写错的点:把 \ 当转义会毁掉 D:\a\b。
func TestParseArgsWindowsPath(t *testing.T) {
got := parseArgs(`-o D:\out\bin.exe`)
if len(got) != 2 || got[1] != `D:\out\bin.exe` {
t.Fatalf("got %v", got)
}
}
// TestParseArgsSingleQuote 单引号内不转义。
func TestParseArgsSingleQuote(t *testing.T) {
got := parseArgs(`--x 'a b' "c d"`)
if len(got) != 3 || got[1] != "a b" || got[2] != "c d" {
t.Fatalf("got %v", got)
}
got = parseArgs(`--x '\n'`)
if len(got) != 2 || got[1] != `\n` {
t.Fatalf("单引号内不转义:%v", got)
}
}
// TestParseArgsEmptyQuoted 空引号算一个空参数(传空字符串给程序是合法需求)。
func TestParseArgsEmptyQuoted(t *testing.T) {
got := parseArgs(`a "" b`)
if len(got) != 3 {
t.Fatalf("应保留空参数,得到 %v", got)
}
if got[1] != "" {
t.Fatalf("中间应为空串,得到 %q", got[1])
}
}
// TestParseArgsUnclosed 引号没闭合按到结尾处理,不 panic。
func TestParseArgsUnclosed(t *testing.T) {
got := parseArgs(`--x "abc`)
if len(got) != 2 || got[1] != "abc" {
t.Fatalf("got %v", got)
}
}
// TestParseArgsAdjacentQuotes 两段引号紧挨着算同一个参数(shell 行为)。
func TestParseArgsAdjacentQuotes(t *testing.T) {
got := parseArgs(`"a"b`)
if len(got) != 1 || got[0] != "ab" {
t.Fatalf("got %v", got)
}
}
// TestEnvFromLines KEY=VALUE 逐行解析,跳过空行/注释/坏行。
func TestEnvFromLines(t *testing.T) {
m := envFromLines(`
# 注释
FOO=bar
BAZ = qux quux
坏行没有等号
EMPTY=
`)
if len(m) != 3 {
t.Fatalf("应解析出 3 个,得到 %v", m)
}
if m["FOO"] != "bar" {
t.Fatalf("FOO = %q", m["FOO"])
}
if m["BAZ"] != "qux quux" {
t.Fatalf("值里的空格要保留:BAZ = %q", m["BAZ"])
}
if v, ok := m["EMPTY"]; !ok || v != "" {
t.Fatalf("空值也要保留:%v", m)
}
}
// TestEnvFromLinesEmpty 全空时返回 nil(便于调用方判空)。
func TestEnvFromLinesEmpty(t *testing.T) {
if m := envFromLines("\n\n # x\n"); m != nil {
t.Fatalf("应返回 nil,得到 %v", m)
}
}
+157
View File
@@ -0,0 +1,157 @@
package app
import (
"sort"
"strings"
"mygoland/internal/lsp"
)
// actionRequest 是一次 textDocument/codeAction 请求:范围、附带诊断,
// 以及可选的 kind 过滤(only)。
type actionRequest struct {
rng lsp.Range
diags []lsp.Diagnostic
only []string
}
// codeActionRequests 产出发给 gopls 的请求。
//
// 为什么要两次(依据:2026-11-05 用真实 gopls v0.23 探测过,见
// internal/lsp 的 TestGoplsCodeActionRanges 记录):
//
// 1. 光标或选区那一次。有选区必须传选区——`refactor.extract.variable`
// 和 `refactor.inline.call` 只在范围正好圈住表达式时才返回;从前一律
// 传整行,等于「选中了 foo() 却按整行提取」,选中态形同虚设。
// 2. 整文件那一次,只问 `refactor.rewrite`。`Add struct tags` 这类文件级
// 重构只有范围覆盖到它才出现,而它不在光标所在行。
//
// 两次请求都是本地往返,串行执行;调用方本来就在后台协程里,不挡 UI。
func codeActionRequests(d *Doc) []actionRequest {
here := cursorOrSelectionRange(d)
return []actionRequest{
{rng: here, diags: diagsIn(d.diags, here)},
{rng: wholeFileRange(d), only: []string{"refactor.rewrite"}},
}
}
// cursorOrSelectionRange 有选区用选区,没有就用光标所在的整行。
//
// 没有选区时沿用整行(既有行为),理由不是「零宽位置会丢快速修复」——
// 2026-11-05 用 gopls v0.23 实测过,行首零宽位置照样能拿到 quickfix,
// gopls 会把位置摊到所属节点上。真正的理由是整行能给按节点展开的动作一个
// 范围(`refactor.extract.function` 就是这么来的),而且改小它没有任何好处。
func cursorOrSelectionRange(d *Doc) lsp.Range {
if sel := d.st.Selection(); !sel.Empty() {
return lsp.Range{
Start: positionAt(d, sel.Start()),
End: positionAt(d, sel.End()),
}
}
pos := d.st.CursorPos()
line := d.buf.Line(pos.Line)
return lsp.Range{
Start: lsp.Position{Line: pos.Line},
End: lsp.Position{Line: pos.Line, Character: lsp.UTF16Len(line)},
}
}
// wholeFileRange 覆盖整个缓冲区。
func wholeFileRange(d *Doc) lsp.Range {
n := d.buf.LineCount()
if n <= 0 {
return lsp.Range{}
}
last := n - 1
return lsp.Range{
Start: lsp.Position{Line: 0},
End: lsp.Position{Line: last, Character: lsp.UTF16Len(d.buf.Line(last))},
}
}
// diagsIn 取与请求范围有交叠的诊断。
//
// **必须带**:gopls 的快速修复靠 context.diagnostics 匹配,不带就一条都没有
// (实测见 internal/lsp 的 TestGoplsCodeActionMissingImportQuickfix)。
//
// 只按行比、不细到列:gopls 会自己再按列筛一遍,卡得太死反而可能漏;带不相干
// **行**的诊断才会真的污染结果,所以按行过滤正好。
func diagsIn(diags []lsp.Diagnostic, r lsp.Range) []lsp.Diagnostic {
var out []lsp.Diagnostic
for _, d := range diags {
if d.Range.Start.Line <= r.End.Line && r.Start.Line <= d.Range.End.Line {
out = append(out, d)
}
}
return out
}
// noiseCommands 是 gopls 那些「只打开浏览器或面板、不改一个字节」的命令。
//
// 实测一次 Alt+Enter 能返回 6–9 项,其中 5 项是这类东西——打开 pkg.go.dev、
// 看汇编、看编译器优化细节、列未归类符号、直接开个 URL。它们把真正的
// 「Extract variable」挤到第七位。按**命令名**过滤而不是标题:标题是英文且
// 会随 gopls 版本变,命令名是协议标识,改得慢。
//
// 白名单式的反向判断(只留已知会改代码的)更干净,但 gopls 加新能力时会把
// 新动作一起漏掉;所以这里只列已知噪音,其余一律放行。
var noiseCommands = map[string]bool{
"gopls.doc": true, // Browse documentation
"gopls.assembly": true, // Browse assembly
"gopls.free_symbols": true, // Browse free symbols
"gopls.client_open_url": true, // 明文开浏览器的命令
"gopls.gc_details": true, // 编译器优化细节开关
}
// actionNoise 判断这个动作是不是该从面板里拿掉。
func actionNoise(a lsp.CodeAction) bool {
return a.Command != nil && noiseCommands[a.Command.Command]
}
// mergeActions 合并多次请求的结果:过滤噪音,同标题只留第一次出现的。
//
// 「第一次出现的优先」是刻意的:第一个请求是光标/选区算出来的,它的动作
// 与用户眼前的范围一致;第二个是整文件算的,同名项(如 Extract function)
// 的目标范围可能更大,顶掉前者会让用户选中一段却抽出整行。
func mergeActions(parts ...[]lsp.CodeAction) []lsp.CodeAction {
seen := make(map[string]bool)
var out []lsp.CodeAction
for _, part := range parts {
for _, a := range part {
if actionNoise(a) || seen[a.Title] {
continue
}
seen[a.Title] = true
out = append(out, a)
}
}
return out
}
// actionRank 给动作排优先级,数字小的靠前。
//
// gopls 的返回顺序不带意图:实测「Extract variable」排在「Add test」和一堆
// 浏览命令之后。按 kind 重排一次,让「马上能改对代码」的项落在拇指下面。
func actionRank(a lsp.CodeAction) int {
switch {
case a.IsPreferred:
return 0
case strings.HasPrefix(a.Kind, "quickfix"):
return 1
case strings.HasPrefix(a.Kind, "refactor"):
return 2
case strings.HasPrefix(a.Kind, "source"):
return 3
}
return 4
}
// rankActions 按 actionRank 稳定排序:同档内保持 gopls 给的顺序。
func rankActions(acts []lsp.CodeAction) []lsp.CodeAction {
out := make([]lsp.CodeAction, len(acts))
copy(out, acts)
sort.SliceStable(out, func(i, j int) bool {
return actionRank(out[i]) < actionRank(out[j])
})
return out
}
+376
View File
@@ -0,0 +1,376 @@
package app
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/lsp"
)
// newActionDoc 造一个带缓冲区的文档;path 决定语言。
func newActionDoc(t *testing.T, text string) *Doc {
t.Helper()
a := &App{root: t.TempDir()}
return a.newDoc(filepath.Join(a.root, "a.go"), text)
}
// TestCursorRangeNoSelection 没有选区时,范围是光标所在的整行。
//
// 用整行而不是零宽位置,是因为 gopls 靠「请求范围与诊断范围相交」挑快速
// 修复,而诊断通常只盖住标识符那几个列。
func TestCursorRangeNoSelection(t *testing.T) {
d := newActionDoc(t, "package a\n\nfunc main() {}\n")
r := cursorOrSelectionRange(d)
if r.Start.Line != 0 || r.Start.Character != 0 {
t.Fatalf("起点 = %+v", r.Start)
}
if r.End.Line != 0 || r.End.Character != len("package a") {
t.Fatalf("终点 = %+v, 想要第 0 行第 %d 列", r.End, len("package a"))
}
}
// TestCursorRangeAtLine 光标在第二行时范围跟到第二行。
func TestCursorRangeAtLine(t *testing.T) {
d := newActionDoc(t, "package a\n\nvar x = 1\n")
d.st.GoTo(editor.Pos{Line: 2, Col: 4})
r := cursorOrSelectionRange(d)
if r.Start.Line != 2 || r.End.Line != 2 {
t.Fatalf("范围落在 %d..%d 行, 想要 2..2", r.Start.Line, r.End.Line)
}
if r.End.Character != len("var x = 1") {
t.Fatalf("终点列 = %d, 想要 %d", r.End.Character, len("var x = 1"))
}
}
// TestCursorRangeSelection 有选区时用选区——这是 extract/inline 的前提。
func TestCursorRangeSelection(t *testing.T) {
src := "package a\n\nvar s = foo(1)\n"
d := newActionDoc(t, src)
// 选中 "foo(1)"(第 2 行第 8..14 字节)。
start := indexOf(src, "foo(1)")
d.st.SetSelections(editor.Selection{Anchor: start, Head: start + len("foo(1)")})
r := cursorOrSelectionRange(d)
if r.Start.Line != 2 || r.Start.Character != 8 {
t.Fatalf("起点 = %+v, 想要第 2 行第 8 列", r.Start)
}
if r.End.Line != 2 || r.End.Character != 14 {
t.Fatalf("终点 = %+v, 想要第 2 行第 14 列", r.End)
}
}
// TestCursorRangeSelectionCJK UTF-16 列号:中文一个字算一列,不能按字节。
func TestCursorRangeSelectionCJK(t *testing.T) {
// 前置注释里放中文,让后面的字节数不等于列数。
src := "package a\n\n// 中文注释 x\n"
d := newActionDoc(t, src)
start := indexOf(src, "x\n")
d.st.SetSelections(editor.Selection{Anchor: start, Head: start + 1})
r := cursorOrSelectionRange(d)
// "// 中文注释 x" 的 UTF-16 长度:// 加空格 3,中文 4 个字 4,空格 1,x 1 → 9。
if r.Start.Character != 8 || r.End.Character != 9 {
t.Fatalf("列号 = %d..%d, 想要 8..9", r.Start.Character, r.End.Character)
}
}
// TestWholeFileRange 整文件范围从第 0 行第 0 列到文件末尾。
//
// 注意末尾换行会多出一个空行:`"a\nb\n"` 的 LineCount 是 3,第 2 行是空的。
// 所以文件末尾落在「最后一行第 0 列」,这正是 LSP 眼里的 EOF。
func TestWholeFileRange(t *testing.T) {
d := newActionDoc(t, "package a\n\nfunc main() {}\n")
r := wholeFileRange(d)
if r.Start.Line != 0 || r.Start.Character != 0 {
t.Fatalf("起点 = %+v", r.Start)
}
if r.End.Line != 3 || r.End.Character != 0 {
t.Fatalf("终点 = %+v, 想要第 3 行第 0 列(末尾换行后的空行)", r.End)
}
}
// TestWholeFileRangeNoTrailingNewline 没有末尾换行时,末尾是最后一行末列。
func TestWholeFileRangeNoTrailingNewline(t *testing.T) {
d := newActionDoc(t, "package a\n\nfunc main() {}")
r := wholeFileRange(d)
if r.End.Line != 2 || r.End.Character != len("func main() {}") {
t.Fatalf("终点 = %+v", r.End)
}
}
// TestDiagsIn 只带与请求范围同行的诊断。
func TestDiagsIn(t *testing.T) {
diags := []lsp.Diagnostic{
{Range: lsp.Range{Start: lsp.Position{Line: 3}, End: lsp.Position{Line: 3, Character: 5}}, Message: "a"},
{Range: lsp.Range{Start: lsp.Position{Line: 5}, End: lsp.Position{Line: 7}}, Message: "b"},
{Range: lsp.Range{Start: lsp.Position{Line: 9}, End: lsp.Position{Line: 9}}, Message: "c"},
}
// 单行范围:只命中第 3 行那条。
if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 3}, End: lsp.Position{Line: 3}}); len(got) != 1 || got[0].Message != "a" {
t.Fatalf("单行范围取到 %+v", got)
}
// 跨行范围:第 5–7 行的诊断为 b。
if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 4}, End: lsp.Position{Line: 8}}); len(got) != 1 || got[0].Message != "b" {
t.Fatalf("跨行范围取到 %+v", got)
}
// 覆盖全部:三条都要。
if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 0}, End: lsp.Position{Line: 20}}); len(got) != 3 {
t.Fatalf("整文件范围只取到 %d 条", len(got))
}
// 都不沾:空。
if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 1}, End: lsp.Position{Line: 2}}); len(got) != 0 {
t.Fatalf("不相干的范围取到 %+v", got)
}
}
// TestCodeActionRequests 两次请求:一次光标/选区,一次整文件只问 refactor.rewrite。
func TestCodeActionRequests(t *testing.T) {
d := newActionDoc(t, "package a\n\nfunc main() {}\n")
d.diags = []lsp.Diagnostic{
{Range: lsp.Range{Start: lsp.Position{Line: 0}, End: lsp.Position{Line: 0}}},
{Range: lsp.Range{Start: lsp.Position{Line: 9}, End: lsp.Position{Line: 9}}},
}
reqs := codeActionRequests(d)
if len(reqs) != 2 {
t.Fatalf("请求 %d 次, 想要 2 次", len(reqs))
}
// 第一次:第 0 行整行,只带第 0 行的诊断。
if reqs[0].rng.Start.Line != 0 || reqs[0].rng.End.Line != 0 {
t.Fatalf("第一次范围 = %+v", reqs[0].rng)
}
if len(reqs[0].diags) != 1 {
t.Fatalf("第一次带了 %d 条诊断, 想要 1 条", len(reqs[0].diags))
}
if len(reqs[0].only) != 0 {
t.Fatalf("第一次不该限定 only:%v", reqs[0].only)
}
// 第二次:整文件(末尾换行导致最后一行是空的第 3 行),只问
// refactor.rewrite,且不带诊断。
if reqs[1].rng.End.Line != 3 {
t.Fatalf("第二次范围到第 %d 行, 想要文件末尾 3", reqs[1].rng.End.Line)
}
if len(reqs[1].only) != 1 || reqs[1].only[0] != "refactor.rewrite" {
t.Fatalf("第二次 only = %v", reqs[1].only)
}
if len(reqs[1].diags) != 0 {
t.Fatalf("整文件请求不该带诊断:%+v", reqs[1].diags)
}
}
// TestActionNoise 浏览类命令被认出来,真会改代码的放行。
func TestActionNoise(t *testing.T) {
withCmd := func(name string) lsp.CodeAction {
return lsp.CodeAction{Command: &lsp.Command{Command: name}}
}
for _, name := range []string{"gopls.doc", "gopls.assembly", "gopls.free_symbols", "gopls.client_open_url", "gopls.gc_details"} {
if !actionNoise(withCmd(name)) {
t.Fatalf("%q 应判为浏览类", name)
}
}
for _, name := range []string{"gopls.apply_fix", "gopls.add_test", "gopls.modify_tags", "gopls.split_package"} {
if actionNoise(withCmd(name)) {
t.Fatalf("%q 会改代码,不该过滤", name)
}
}
// 没有 command 的(自带 edit)一律保留。
if actionNoise(lsp.CodeAction{}) {
t.Fatal("没有 command 的动作不该被过滤")
}
}
// TestMergeActions 过滤噪音 + 同标题只留第一次出现的那条。
func TestMergeActions(t *testing.T) {
first := []lsp.CodeAction{
{Title: "Extract function", Kind: "refactor.extract.function", Command: &lsp.Command{Command: "gopls.apply_fix"}},
{Title: "Browse documentation", Kind: "source.doc", Command: &lsp.Command{Command: "gopls.doc"}},
}
second := []lsp.CodeAction{
{Title: "Extract function", Kind: "refactor.rewrite.function", Command: &lsp.Command{Command: "gopls.apply_fix"}},
{Title: "Add struct tags", Kind: "refactor.rewrite.addTags", Command: &lsp.Command{Command: "gopls.modify_tags"}},
}
got := mergeActions(first, second)
if len(got) != 2 {
t.Fatalf("合并后有 %d 项: %+v", len(got), titles(got))
}
// 同标题保留第一次的 kind——它的范围与用户眼前一致。
if got[0].Kind != "refactor.extract.function" {
t.Fatalf("同名项保留了 %q, 想要第一次的 refactor.extract.function", got[0].Kind)
}
if got[1].Title != "Add struct tags" {
t.Fatalf("第二项是 %q", got[1].Title)
}
// 顺序:第一次请求的在前。
if got[0].Title != "Extract function" {
t.Fatalf("顺序反了:%+v", titles(got))
}
}
// TestMergeActionsAllNoise 全是浏览命令时结果为空(调用方据此给出「已隐藏」提示)。
func TestMergeActionsAllNoise(t *testing.T) {
acts := []lsp.CodeAction{
{Title: "Browse documentation", Command: &lsp.Command{Command: "gopls.doc"}},
{Title: "Browse assembly", Command: &lsp.Command{Command: "gopls.assembly"}},
}
if got := mergeActions(acts); len(got) != 0 {
t.Fatalf("还剩 %+v", titles(got))
}
}
// TestRankActions 排序:推荐 → 快速修复 → 重构 → 源码,同档保持原序。
func TestRankActions(t *testing.T) {
acts := []lsp.CodeAction{
{Title: "source1", Kind: "source.addTest"},
{Title: "refactor1", Kind: "refactor.rewrite.addTags"},
{Title: "quick1", Kind: "quickfix"},
{Title: "refactor0", Kind: "refactor.extract.variable"},
{Title: "preferred", Kind: "quickfix", IsPreferred: true},
{Title: "other", Kind: ""},
}
got := titles(rankActions(acts))
want := []string{"preferred", "quick1", "refactor1", "refactor0", "source1", "other"}
if len(got) != len(want) {
t.Fatalf("got %v", got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("第 %d 位是 %q, 想要 %q(全部:%v)", i, got[i], want[i], got)
}
}
}
// TestRankActionsStable 同档内不重排:gopls 给的相对顺序是有意义的。
func TestRankActionsStable(t *testing.T) {
acts := []lsp.CodeAction{
{Title: "a", Kind: "refactor.a"},
{Title: "b", Kind: "refactor.b"},
{Title: "c", Kind: "refactor.c"},
}
if got := titles(rankActions(acts)); len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "c" {
t.Fatalf("同档顺序被改动:%v", got)
}
}
// TestActionKindLabel 分类文案,重点是 source 里那几个真会改代码的。
func TestActionKindLabel(t *testing.T) {
cases := map[string]string{
"quickfix": "快速修复",
"refactor.extract.variable": "提取",
"refactor.inline.call": "内联",
"refactor.rewrite.addTags": "重写",
"refactor.other": "重构",
"source.addTest": "生成测试",
"source.organizeImports": "整理 import",
"source.fixAll": "全部修复",
"source.splitPackage": "源码",
"": "",
"gopls.doc.features": "",
}
for kind, want := range cases {
if got := actionKindLabel(kind); got != want {
t.Fatalf("actionKindLabel(%q) = %q, 想要 %q", kind, got, want)
}
}
}
// titles 提取标题,便于断言。
func titles(acts []lsp.CodeAction) []string {
out := make([]string, len(acts))
for i, a := range acts {
out[i] = a.Title
}
return out
}
// indexOf 返回子串的字节偏移,找不到返回 -1。
func indexOf(s, sub string) int {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return i
}
}
return -1
}
// TestQueryCodeActionsAgainstGopls 用真 gopls 跑完 app 层整条管线:
// 算范围 → 发两次请求 → 过滤噪音 → 合并去重 → 排序。
//
// 单测覆盖不到的是「我们算出来的范围,gopls 认不认」。这条盯着两件事:
// - 选中表达式时,结果里有 refactor.extract.variable(只有选区才有);
// - 结果里没有任何 gopls 的浏览类命令(说明噪音过滤生效)。
func TestQueryCodeActionsAgainstGopls(t *testing.T) {
if testing.Short() {
t.Skip("集成测试需要 gopls")
}
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil {
t.Fatal(err)
}
src := "package demo\n\nimport \"strings\"\n\nfunc caller() string {\n\treturn strings.ToUpper(\"b\")\n}\n"
path := filepath.Join(dir, "demo.go")
if err := os.WriteFile(path, []byte(src), 0o644); err != nil {
t.Fatal(err)
}
c, err := lsp.Start(context.Background(), lsp.Options{Root: dir, Logf: t.Logf})
if err != nil {
t.Skipf("gopls 不可用: %v", err)
}
t.Cleanup(func() { _ = c.Close() })
uri := lsp.PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
a := &App{root: dir}
d := a.newDoc(path, src)
off := indexOf(src, `strings.ToUpper("b")`)
if off < 0 {
t.Fatal("测试源码里找不到目标表达式")
}
d.st.SetSelections(editor.Selection{Anchor: off, Head: off + len(`strings.ToUpper("b")`)})
reqs := codeActionRequests(d)
if len(reqs) != 2 {
t.Fatalf("请求 %d 次", len(reqs))
}
var acts []lsp.CodeAction
for i := 0; i < 40; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
acts, _, err = queryCodeActions(ctx, c, uri, reqs)
cancel()
if err != nil {
t.Logf("第 %d 次请求出错:%v", i, err)
}
if len(acts) > 0 {
break
}
time.Sleep(500 * time.Millisecond)
}
if len(acts) == 0 {
t.Fatal("一条动作都没拿到")
}
var kinds []string
for _, act := range acts {
kinds = append(kinds, act.Kind)
if actionNoise(act) {
t.Fatalf("结果里混进了浏览类命令 %q", act.Title)
}
}
t.Logf("过滤排序后 %d 项:%v → %v", len(acts), titles(acts), kinds)
found := false
for _, k := range kinds {
if k == "refactor.extract.variable" {
found = true
}
}
if !found {
t.Fatalf("选中表达式后没有 extract.variable,实际:%v", kinds)
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ func (a *App) renderCompletions(c *ui.Context, panel ui.Element, m *editor.Compl
if s := m.Selected(); s < len(items) && items[s].Documentation != "" { if s := m.Selected(); s < len(items) && items[s].Documentation != "" {
ui.Box(c).Height(1).Background(t.Border).Margin(t.Space(1), 0) ui.Box(c).Height(1).Background(t.Border).Margin(t.Space(1), 0)
text := a.docTranslation(items[s].Documentation) text := a.docTranslation(items[s].Documentation)
ui.Text(c, text).FontSize(t.FontSize - 1).TextColor(t.TextMuted).MaxWidth(t.Space(140)).Padding(t.Space(0.5), t.Space(1.5)) ui.Text(c, text).FontSize(t.FontSize-1).TextColor(t.TextMuted).MaxWidth(t.Space(140)).Padding(t.Space(0.5), t.Space(1.5))
} }
}) })
} }
+120
View File
@@ -0,0 +1,120 @@
package app
import (
"strings"
"sync"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/lsp"
)
// snippetCache 缓存 LSP 补全模板的解析结果(含失败,值为 nil)。
//
// 同一个模板(如 Print(${1:}))在每次补全里都会出现,解析虽然便宜但
// 没必要每帧重做。key 是原始 snippet 文本,缓存随会话增长但条目有限,
// 因为服务端能给出的模板种类是收敛的。
var snippetCache sync.Map // map[string]*editor.Snippet
func parseCompletionSnippet(src string) *editor.Snippet {
if v, ok := snippetCache.Load(src); ok {
return v.(*editor.Snippet)
}
s, err := editor.ParseSnippet(src)
if err != nil {
s = nil
}
snippetCache.Store(src, s)
return s
}
// plainSnippetText 把服务端返回的 snippet 剥成能直接插入的纯文本。
//
// 只在 ParseSnippet 拒绝模板时走这里(例如服务端用了 choices 或 transform)。
// 不剥的话用户会看到 "Print(${1:})" 这种字面量,比没有补全还糟。
// 支持 ${1:name} → name(含嵌套占位递归剥离)、${1|a,b|} → a、
// $1/$0 → 空、\$ 转义。这是解析失败后的降级路径,只求不把 ${...}
// 原样插进代码,不追求完整还原 TextMate 语义。
func plainSnippetText(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
if s[i] == '\\' && i+1 < len(s) {
b.WriteByte(s[i+1])
i += 2
continue
}
if s[i] != '$' {
b.WriteByte(s[i])
i++
continue
}
i++
if i < len(s) && s[i] == '{' {
// 花括号要配平:${2:${3:nested}} 里第一个 } 属于内层。
depth, j := 1, i+1
for j < len(s) && depth > 0 {
switch {
case s[j] == '\\' && j+1 < len(s):
j += 2
case s[j] == '$' && j+1 < len(s) && s[j+1] == '{':
depth++
j += 2
case s[j] == '}':
depth--
j++
default:
j++
}
}
if depth > 0 {
b.WriteString(s[i-1:])
break
}
body := s[i+1 : j-1]
switch {
case strings.Contains(body, ":"):
c := strings.IndexByte(body, ':')
b.WriteString(plainSnippetText(body[c+1:])) // 内层继续剥
case strings.Contains(body, "|"):
// choices 语法 ${1|a,b|}:降级取第一个选项。
opts := body[strings.IndexByte(body, '|')+1:]
if e := strings.LastIndexByte(opts, '|'); e >= 0 {
opts = opts[:e]
}
if comma := strings.IndexByte(opts, ','); comma >= 0 {
opts = opts[:comma]
}
b.WriteString(opts)
}
i = j
continue
}
j := i
for j < len(s) && s[j] >= '0' && s[j] <= '9' {
j++
}
if j == i {
b.WriteByte('$')
}
i = j
}
return b.String()
}
// applyCompletionSnippet 把 LSP 的 snippet 补全接到框架的模板能力上。
//
// insertTextFormat==2 才是 snippet(实测 gopls v0.23 给函数补全返回
// Print(${1:}) 这类模板)。解析成功就交给 Completion.Snippet,由框架
// 负责 Tab/Shift+Tab 跳转;解析失败降级成纯文本,绝不整条丢掉。
// Kind 保持不变——它只决定图标,函数补全不该因为能跳占位就变成模板图标。
func applyCompletionSnippet(c *editor.Completion, it lsp.CompletionItem, insert string) {
if it.InsertTextFormat != 2 {
return
}
if s := parseCompletionSnippet(insert); s != nil {
c.Snippet = s
return
}
c.Insert = plainSnippetText(insert)
}
+130
View File
@@ -0,0 +1,130 @@
package app
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/lsp"
)
// TestParseGoplsSnippet 固化实测前提:gopls 给的 ${1:} 空默认值模板,
// mygo v0.9.0 的 ParseSnippet 能解析,插入文本是 Print()。
func TestParseGoplsSnippet(t *testing.T) {
s := parseCompletionSnippet("Print(${1:})")
if s == nil {
t.Fatal("mygo 应该能解析 gopls 的 ${1:} 模板")
}
if got := s.Text(); got != "Print()" {
t.Fatalf("插入文本 = %q,想要 Print()", got)
}
// 同一模板走缓存,结果必须是同一个对象。
if s2 := parseCompletionSnippet("Print(${1:})"); s2 != s {
t.Fatal("缓存没生效")
}
}
func TestPlainSnippetText(t *testing.T) {
cases := []struct{ in, want string }{
{"Print(${1:})", "Print()"},
{"Add(${1:a}, ${2:b})$0", "Add(a, b)"},
{"cost is \\$5$0", "cost is $5"},
{"plain text", "plain text"},
}
for _, c := range cases {
if got := plainSnippetText(c.in); got != c.want {
t.Errorf("plainSnippetText(%q) = %q, want %q", c.in, got, c.want)
}
}
if got := plainSnippetText("Print(${1:})"); strings.Contains(got, "${") {
t.Fatalf("降级文本不该残留占位语法:%q", got)
}
}
// TestApplyCompletionSnippet 只有 insertTextFormat==2 才接模板;
// 解析不了的要降级成纯文本,不能把 ${...} 原样插进代码。
func TestApplyCompletionSnippet(t *testing.T) {
// 纯文本补全不碰 Snippet。
plain := editor.Completion{Label: "Print", Insert: "Print"}
applyCompletionSnippet(&plain, lsp.CompletionItem{InsertTextFormat: 1}, "Print")
if plain.Snippet != nil || plain.Insert != "Print" {
t.Fatalf("纯文本补全被改了:%+v", plain)
}
// snippet 补全:模板交给框架。
snip := editor.Completion{Label: "Print", Insert: "Print(${1:})", Kind: editor.CompletionFunction}
applyCompletionSnippet(&snip, lsp.CompletionItem{InsertTextFormat: 2}, "Print(${1:})")
if snip.Snippet == nil {
t.Fatal("应把模板交给 Completion.Snippet")
}
if snip.Kind != editor.CompletionFunction {
t.Fatal("Kind 只决定图标,不该被 snippet 改掉")
}
// 解析失败:降级成纯文本,且缓存住失败结果。
bad := "${1|one,two|} + ${2:${3:nested}}"
fallback := editor.Completion{Label: "x", Insert: bad}
applyCompletionSnippet(&fallback, lsp.CompletionItem{InsertTextFormat: 2}, bad)
if fallback.Snippet != nil {
t.Fatal("不支持的模板不该当成 snippet")
}
if strings.Contains(fallback.Insert, "${") {
t.Fatalf("降级文本不该残留占位语法:%q", fallback.Insert)
}
}
// TestToEditorCompletionGopls 按 gopls 的真实返回走完整映射:
// insertText 为空、内容在 textEdit.newText、format=2。
func TestToEditorCompletionGopls(t *testing.T) {
it := lsp.CompletionItem{
Label: "Print",
Kind: 3,
TextEdit: &lsp.TextEdit{NewText: "Print(${1:})"},
InsertTextFormat: 2,
}
got := toEditorCompletion(it)
if got.Snippet == nil {
t.Fatalf("gopls 的模板补全没接上:%+v", got)
}
if got.Kind != completionKind(3) {
t.Fatal("映射把补全类型改了")
}
if got.Label != "Print" {
t.Fatalf("label 不对:%q", got.Label)
}
}
// TestSnippetCompletionEndToEnd 走完「LSP 项 → 编辑器补全 → 接受 → 光标」。
// 框架自己的 snippet_test.go 覆盖模板状态机,这里只负责证明我们填的
// Completion.Snippet 确实被框架应用了,而不是设了个没人读的字段。
func TestSnippetCompletionEndToEnd(t *testing.T) {
src := "package main\n\nfunc main() {\n\tfmt.Pr\n}\n"
d := newActionDoc(t, src)
at := strings.Index(src, "Pr")
end := at + len("Pr")
d.st.Select(end, end)
d.st.ShowCompletions(at, []editor.Completion{
toEditorCompletion(lsp.CompletionItem{
Label: "Print",
TextEdit: &lsp.TextEdit{NewText: "Print(${1:})"},
InsertTextFormat: 2,
}),
})
tt := ui.NewTester(func(c *ui.Context) {
editor.View(c, d.st).Fill().AutoFocus()
}, 640, 400)
tt.Frame()
tt.Key(0, ui.KeyTab) // 接受第一项补全
tt.Frame()
got := d.buf.String()
if !strings.Contains(got, "fmt.Print()") {
t.Fatalf("接受补全后文本不对:%q", got)
}
// 光标应停在括号里(第一个占位符),而不是行尾。
if cur := d.st.Cursor(); cur != strings.Index(got, "Print()")+len("Print(") {
t.Fatalf("光标 = %d,应停在括号内;文本 %q", cur, got)
}
}
+100 -2
View File
@@ -49,6 +49,9 @@ type coverState struct {
files map[string]coverFile // 键是小写规范化的绝对路径 files map[string]coverFile // 键是小写规范化的绝对路径
all float64 all float64
total string // 整体一行摘要,显示在状态栏 total string // 整体一行摘要,显示在状态栏
// failMsg 非空表示这一轮 go test 有失败,覆盖率数字不可信;
// 详情已写进输出面板,界面上只放这一行摘要。
failMsg string
} }
// parseCoverProfile 解析 coverprofile 文本。 // parseCoverProfile 解析 coverprofile 文本。
@@ -133,7 +136,8 @@ func (a *App) RunCoverage() {
out.Close() out.Close()
defer os.Remove(path) defer os.Remove(path)
t, err := task.Start(a.root, "go", "test", "-coverprofile="+path, "./...") args := a.withTestFlags([]string{"test", "-coverprofile=" + path, "./..."})
t, err := task.Start(a.root, "go", args...)
if err != nil { if err != nil {
a.alert("覆盖率", err.Error()) a.alert("覆盖率", err.Error())
return return
@@ -153,20 +157,101 @@ func (a *App) RunCoverage() {
lines = append(lines, line) lines = append(lines, line)
} }
t.Wait() t.Wait()
// Task.Wait 没有返回值,退出状态只能从 ExitCode 取(未结束是 -1)。
code := t.ExitCode()
data, readErr := os.ReadFile(path) data, readErr := os.ReadFile(path)
a.win.Update(func() { a.win.Update(func() {
a.cover.running = false a.cover.running = false
if code != 0 {
// 测试没全过时 coverprofile 可能只是一部分包的,数字会骗人:
// 摘要放本页,明细进输出面板(本页只显示覆盖率,看不到日志)。
a.cover.failMsg = coverageFailSummary(code, lines)
a.appendOut("$ go test -coverprofile=… ./...")
for _, ln := range coverageFailLines(lines) {
a.appendOut(ln)
}
a.appendOut("覆盖率:测试未全部通过,以上数字仅供参考")
} else {
a.cover.failMsg = ""
}
if readErr != nil { if readErr != nil {
if code != 0 {
a.appendOut("覆盖率失败:测试未通过,没有生成 coverprofile")
} else {
a.appendOut("覆盖率失败:没拿到 coverprofile") a.appendOut("覆盖率失败:没拿到 coverprofile")
}
a.refresh() a.refresh()
return return
} }
a.applyCoverage(string(data)) a.applyCoverage(string(data))
}) })
_ = lines
}() }()
} }
// coverFailCap 是回放到输出面板的失败行上限:全量回放会刷屏。
const coverFailCap = 200
// coverageFailLines 从 go test 输出里挑出能说明失败原因的行。
//
// 只挑这几类:FAIL 汇总、--- FAIL 用例、panic、以及带 file.go:12: 的
// 断言消息(parseOutLine 认得出位置,点一下能跳源码)。其余(ok 行、
// 进度行)丢掉,避免把输出面板灌满。
func coverageFailLines(lines []string) []string {
out := make([]string, 0, 16)
for _, ln := range lines {
s := strings.TrimSpace(ln)
if s == "" {
continue
}
keep := strings.HasPrefix(s, "FAIL") ||
strings.HasPrefix(s, "--- FAIL") ||
strings.HasPrefix(s, "panic:") ||
strings.HasPrefix(s, "# ")
if !keep {
if _, ok := splitLoc(s); ok {
keep = true
}
}
if !keep {
continue
}
out = append(out, ln)
if len(out) >= coverFailCap {
out = append(out, fmt.Sprintf("…(失败输出超过 %d 行,已截断)", coverFailCap))
break
}
}
return out
}
// coverageFailSummary 生成一行失败摘要,例如:
// 「2 个包失败 · 3 个用例失败(go test 退出码 1)」。
func coverageFailSummary(code int, lines []string) string {
var pkgs, cases int
for _, ln := range lines {
s := strings.TrimSpace(ln)
switch {
case strings.HasPrefix(s, "--- FAIL"):
cases++
case strings.HasPrefix(s, "FAIL\t"), strings.HasPrefix(s, "FAIL "):
if !strings.HasPrefix(s, "FAIL\t ") {
pkgs++
}
}
}
parts := make([]string, 0, 3)
if pkgs > 0 {
parts = append(parts, fmt.Sprintf("%d 个包失败", pkgs))
}
if cases > 0 {
parts = append(parts, fmt.Sprintf("%d 个用例失败", cases))
}
if len(parts) == 0 {
parts = append(parts, "go test 未通过")
}
return fmt.Sprintf("%s(退出码 %d),覆盖率数字仅供参考", strings.Join(parts, " · "), code)
}
// applyCoverage 把 coverprofile 套到打开的文件上。 // applyCoverage 把 coverprofile 套到打开的文件上。
func (a *App) applyCoverage(text string) { func (a *App) applyCoverage(text string) {
files := parseCoverProfile(text) files := parseCoverProfile(text)
@@ -308,6 +393,19 @@ func (a *App) coverageView(c *ui.Context) {
} }
}) })
// 上一轮测试没全过:数字不可信,先把话说明白,再给个去看日志的入口。
if a.cover.failMsg != "" {
ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center).
Background(t.Danger.Alpha(0.12)).Children(func() {
ui.Text(c, "⚠ "+a.cover.failMsg).FontSize(11).
TextColor(t.Danger).SingleLine()
ui.Box(c).Grow(1)
if ui.Button(c, "查看测试输出").Clicked() {
a.panelTab = 0
}
})
}
if len(a.cover.files) == 0 { if len(a.cover.files) == 0 {
ui.Column(c).Grow(1).FillHeight().Center().Children(func() { ui.Column(c).Grow(1).FillHeight().Center().Children(func() {
ui.Text(c, "点「统计覆盖率」跑一遍 go test -coverprofile").FontSize(12). ui.Text(c, "点「统计覆盖率」跑一遍 go test -coverprofile").FontSize(12).
+88
View File
@@ -1,6 +1,7 @@
package app package app
import ( import (
"strings"
"testing" "testing"
"github.com/egoist/mygo/ui" "github.com/egoist/mygo/ui"
@@ -91,3 +92,90 @@ func TestCoverStatText(t *testing.T) {
t.Fatalf("没有数据的文件不该显示: %q", got) t.Fatalf("没有数据的文件不该显示: %q", got)
} }
} }
// sampleFailOut 是一段真实的 `go test ./...` 失败输出(混合了成功包)。
const sampleFailOut = `ok testdemo/util 0.004s
--- FAIL: TestAdd (0.00s)
calc_test.go:12: 2+2 = 5, want 4
--- FAIL: TestSub/deep (0.00s)
calc_test.go:20: 1-1 = 1, want 0
FAIL
FAIL testdemo 0.006s
FAIL
`
// TestCoverageFailLines 失败行筛选:只留能说明问题的,丢掉 ok 与空行。
func TestCoverageFailLines(t *testing.T) {
lines := strings.Split(sampleFailOut, "\n")
got := coverageFailLines(lines)
var hasCase, hasLoc, hasOk bool
for _, s := range got {
if strings.HasPrefix(s, "--- FAIL: TestAdd") {
hasCase = true
}
if strings.Contains(s, "calc_test.go:12:") {
hasLoc = true
}
if strings.HasPrefix(s, "ok ") {
hasOk = true
}
}
if !hasCase || !hasLoc {
t.Fatalf("应保留用例行与断言行:%v", got)
}
if hasOk {
t.Fatalf("不该回放 ok 行:%v", got)
}
}
// TestCoverageFailLinesBuildError 编译失败也要能带出来(# 包头 + 位置行)。
func TestCoverageFailLinesBuildError(t *testing.T) {
out := "# testdemo\n./main.go:6:2: undefined: fmtx\nFAIL\ttestdemo [build failed]\n"
got := coverageFailLines(strings.Split(out, "\n"))
joined := strings.Join(got, "\n")
if !strings.Contains(joined, "undefined: fmtx") {
t.Fatalf("编译错误被丢掉:%v", got)
}
if !strings.Contains(joined, "# testdemo") {
t.Fatalf("包名行被丢掉:%v", got)
}
}
// TestCoverageFailLinesCap 超量时截断,并追加提示。
func TestCoverageFailLinesCap(t *testing.T) {
var lines []string
for i := 0; i <= coverFailCap+10; i++ {
lines = append(lines, "--- FAIL: TestX")
}
got := coverageFailLines(lines)
if len(got) > coverFailCap+1 {
t.Fatalf("未按上限截断,%d 行", len(got))
}
last := got[len(got)-1]
if !strings.Contains(last, "已截断") {
t.Fatalf("最后一行应为截断提示,得到 %q", last)
}
}
// TestCoverageFailSummary 摘要:数包、数用例、带退出码。
func TestCoverageFailSummary(t *testing.T) {
got := coverageFailSummary(1, strings.Split(sampleFailOut, "\n"))
if !strings.Contains(got, "1 个包失败") {
t.Fatalf("包计数不对:%q", got)
}
if !strings.Contains(got, "2 个用例失败") {
t.Fatalf("用例计数不对:%q", got)
}
if !strings.Contains(got, "退出码 1") {
t.Fatalf("缺退出码:%q", got)
}
}
// TestCoverageFailSummaryNoDetail 输出里什么都没有时也要给一句可读的话。
func TestCoverageFailSummaryNoDetail(t *testing.T) {
got := coverageFailSummary(2, nil)
if !strings.Contains(got, "go test 未通过") || !strings.Contains(got, "退出码 2") {
t.Fatalf("兜底文案不对:%q", got)
}
}
+15 -4
View File
@@ -123,12 +123,16 @@ func (a *App) StartDebug() {
if prog == "" { if prog == "" {
prog = "." prog = "."
} }
args := strings.Fields(cfg.Args) // 与「运行」同一套解析:支持双引号包住的参数。
args := parseArgs(cfg.Args)
stopOnEntry := cfg.StopOnEntry stopOnEntry := cfg.StopOnEntry
root := a.root // dlv 自己的 cwd 与 launch 的 cwd 都跟着配置走:
// 前者决定相对 program 怎么解析,后者决定被调试进程的工作目录。
dir := a.cfgWorkDir(cfg)
env := envFromLines(cfg.Env)
go func() { go func() {
c, err := dap.Start(root, func(ev string, body json.RawMessage) { c, err := dap.Start(dir, func(ev string, body json.RawMessage) {
a.win.Update(func() { a.onDebugEvent(ev, body) }) a.win.Update(func() { a.onDebugEvent(ev, body) })
}, logf) }, logf)
if err != nil { if err != nil {
@@ -142,7 +146,14 @@ func (a *App) StartDebug() {
return return
} }
a.win.Update(func() { s.state = "构建中…" }) a.win.Update(func() { s.state = "构建中…" })
if err := c.Launch(prog, args, stopOnEntry, 180*time.Second); err != nil { // env / cwd 是 dlv 的扩展字段,作用于被调试进程而不是 dlv 自己。
if err := c.LaunchWith(dap.LaunchOptions{
Program: prog,
Args: args,
StopOnEntry: stopOnEntry,
Env: env,
WorkDir: dir,
}, 180*time.Second); err != nil {
a.failDebug(s, err) a.failDebug(s, err)
return return
} }
+248
View File
@@ -0,0 +1,248 @@
package app
import (
"path/filepath"
"strings"
"github.com/egoist/mygo"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/lsp"
)
// 编辑器右键菜单里应用层动作的 ID。
//
// 为什么用字符串 ID 而不是直接塞闭包:菜单项要在单测里断言(哪几项该灰、
// 哪个 ID 对应哪个快捷键),闭包里装着 *App 就没法比对了。
const (
emCodeActions = "codeActions" // 代码动作(gopls 的 quick fix)
emFindRefs = "findRefs" // 查找引用
emRename = "rename" // 重命名符号
emFormat = "format" // 格式化文档
emFind = "find" // 在文件中查找
emRunTest = "runTest" // 运行光标处的测试
emTestPkg = "testPkg" // 运行当前包的测试
emRevealTree = "revealTree" // 在项目树中定位
emRevealOS = "revealOS" // 在资源管理器中显示
emHistory = "history" // 本地历史
emCopyRel = "copyRel" // 复制相对路径
emCopyAbs = "copyAbs" // 复制绝对路径
)
// editorMenuItem 是菜单里的一项。sep 为真时是分隔线,其余字段无意义。
//
// 用自己的一份结构而不是直接造 ui.MenuItem,是为了让「该有哪些项、哪几项
// 可用」变成纯函数,能在没有窗口、没有渲染帧的测试里跑。
type editorMenuItem struct {
id string
label string
sep bool
enabled bool
}
// editorMenuCap 是决定菜单项可用与否的事实集合,由 editorMenuCap 从文档现状
// 取出来。单独一个结构体,是为了单测能任选组合,不必真造 App 与 LSP 客户端。
type editorMenuCap struct {
goFile bool // Go 文件:代码动作 / 引用 / 重命名 / 格式化
testFile bool // _test.go:才显示「运行测试」
lspReady bool // 语言服务器在线
inRoot bool // 在工作区内:相对路径与「在项目树中定位」才有意义
onDisk bool // 有绝对路径:资源管理器与本地历史才可用
readOnly bool // 只读(超大文件):会改文本的项一律灰掉
}
// attachEditorMenu 把应用层菜单项挂到文档编辑器上。
//
// 这个钩子加在框架自带菜单的**后面**:框架的 build.go 里先放跳转定义、
// 剪切/复制/粘贴、全选、切换注释,以及选区/转换/折叠三个子菜单,末尾
// `m.Separator()` 之后才调 State.ContextMenu(见 editor/build.go:278)。
// 所以这里只管补框架没有的、应用层才知道的东西——gopls 的几个请求、
// 跑测试、路径复制、定位文件。
func (a *App) attachEditorMenu(d *Doc) {
d.st.ContextMenu = func(m *ui.Menu) { a.buildEditorMenu(m, d) }
}
// buildEditorMenu 按当前文档的现状把菜单画出来。
func (a *App) buildEditorMenu(m *ui.Menu, d *Doc) {
if d == nil {
return
}
for _, it := range editorMenuItems(a.editorMenuCap(d)) {
if it.sep {
m.Separator()
continue
}
item := m.Item(it.label).Disabled(!it.enabled)
if mods, key, ok := editorMenuShortcut(it.id); ok {
item.Shortcut(mods, key)
}
// Chosen 只在「用户点完之后重跑 build」那一遍返回 true,
// 收集菜单项那一遍是 false,所以这里不会误触发。
if item.Chosen() {
a.editorMenuAction(d, it.id)
}
}
}
// editorMenuCap 读出当前文档决定菜单可用性的事实。
func (a *App) editorMenuCap(d *Doc) editorMenuCap {
return editorMenuCap{
goFile: lsp.IsGoFile(d.path),
testFile: strings.HasSuffix(d.path, "_test.go"),
lspReady: a.lsp != nil,
inRoot: a.root != "" && within(a.root, d.path),
onDisk: filepath.IsAbs(d.path),
readOnly: d.st.ReadOnly,
}
}
// editorMenuItems 产出菜单项列表。纯函数,便于单测。
//
// 测试那两项只在 _test.go 里出现——普通文件里挂着一个永远点不动的
// 「运行光标处的测试」纯属噪音,而它一旦可点又会在光标不在测试函数里时
// 偷偷退化成「跑全部测试」,那是更糟的意外。
func editorMenuItems(c editorMenuCap) []editorMenuItem {
item := func(id, label string, on bool) editorMenuItem {
return editorMenuItem{id: id, label: label, enabled: on}
}
sep := editorMenuItem{sep: true}
canGo := c.goFile && c.lspReady // gopls 在,且是 Go 文件
canEdit := canGo && !c.readOnly // 再加上「这份缓冲区可以改」
canRun := c.testFile && c.inRoot // 跑测试要有包路径,得在工作区内
items := []editorMenuItem{
item(emCodeActions, "代码动作(Alt+Enter)", canEdit),
item(emFindRefs, "查找引用(Shift+F2)", canGo),
item(emRename, "重命名符号(F2)", canEdit),
sep,
item(emFormat, "格式化文档", canEdit),
item(emFind, "在文件中查找(Ctrl+F)", true),
}
if canRun {
items = append(items,
sep,
item(emRunTest, "运行光标处的测试", true),
item(emTestPkg, "运行当前包的测试", true),
)
}
items = append(items,
sep,
item(emRevealTree, "在项目树中定位", c.inRoot),
item(emRevealOS, "在资源管理器中显示", c.onDisk),
item(emHistory, "本地历史…", c.onDisk),
sep,
item(emCopyRel, "复制相对路径", c.inRoot),
item(emCopyAbs, "复制绝对路径", c.onDisk),
)
return compactEditorMenu(items)
}
// compactEditorMenu 去掉开头、结尾和连续的分隔线。
//
// 条件插入(测试项、以及将来别的可选组)很容易留下「分隔线接分隔线」
// 或者末尾挂一条线,菜单上看就是一道多出来的横杠。统一在这里收口,
// 免得每加一个条件组都要自己数前后有没有线。
func compactEditorMenu(items []editorMenuItem) []editorMenuItem {
out := make([]editorMenuItem, 0, len(items))
for _, it := range items {
if it.sep && (len(out) == 0 || out[len(out)-1].sep) {
continue
}
out = append(out, it)
}
for len(out) > 0 && out[len(out)-1].sep {
out = out[:len(out)-1]
}
return out
}
// editorMenuShortcut 返回菜单项右侧该显示的快捷键。
//
// 只列**应用里真的绑了**的组合:这里只是画个字样,按下去由 OnInput 或
// 菜单 Accelerator 负责,写错等于骗人。
func editorMenuShortcut(id string) (ui.Modifiers, ui.Key, bool) {
switch id {
case emCodeActions:
return ui.Alt, ui.KeyEnter, true
case emFindRefs:
return ui.Shift, ui.KeyF2, true
case emRename:
return 0, ui.KeyF2, true
case emFormat:
return ui.Ctrl | ui.Alt, ui.KeyL, true
case emFind:
return ui.Cmd, ui.KeyF, true
}
return 0, 0, false
}
// editorMenuAction 执行菜单里选中(或被键盘触发)的那一项。
func (a *App) editorMenuAction(d *Doc, id string) {
if d == nil {
return
}
switch id {
case emCodeActions:
a.CodeActions()
case emFindRefs:
a.FindReferences()
case emRename:
a.RenameSymbol()
case emFormat:
a.FormatCurrent()
case emFind:
// 走 pendingCmd:菜单回调里直接 Run 会被编辑器按「正在用」拒掉,
// 和快捷键那条路一样推到下一帧再跑(见 editcmd.go)。
a.RunEditorCmd(editor.Find)
case emRunTest:
a.runTestAtCursor()
case emTestPkg:
a.runCurrentPackageTests()
case emRevealTree:
a.revealDir(filepath.Dir(d.path))
case emRevealOS:
mygo.Shell.ShowItemInFolder(d.path)
case emHistory:
a.OpenHistoryView(d.path, false, histLocal)
case emCopyRel:
a.copyToClipboard(menuRelPath(a.root, d.path))
case emCopyAbs:
a.copyToClipboard(d.path)
}
}
// menuRelPath 返回相对工作区的路径(统一成正斜杠),不在工作区内时退回绝对路径。
func menuRelPath(root, path string) string {
if root == "" || path == "" || !within(root, path) {
return path
}
rel, err := filepath.Rel(root, path)
if err != nil || rel == "" {
return path
}
return filepath.ToSlash(rel)
}
// clipWrite 是「写系统剪贴板」那一步。
//
// 抽成变量只为测试:单测里换成记录用的函数,免得跑一次测试就把用户剪贴板
// 上的东西覆盖掉。
var clipWrite = func(s string) error {
return mygo.Clipboard.Write(transfer.TextData(s))
}
// copyToClipboard 写系统剪贴板。
//
// 剪贴板是主线程资源,但这里来自菜单选择,已经站在 UI 线程上,直接写即可;
// 失败只记日志——复制个路径而已,弹窗打断反而烦。
func (a *App) copyToClipboard(s string) {
if s == "" {
return
}
if err := clipWrite(s); err != nil {
logf("写剪贴板失败:%v", err)
}
}
+330
View File
@@ -0,0 +1,330 @@
package app
import (
"path/filepath"
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
)
// menuByID 在菜单项里按 ID 找,找不到返回 false。
func menuByID(items []editorMenuItem, id string) (editorMenuItem, bool) {
for _, it := range items {
if !it.sep && it.id == id {
return it, true
}
}
return editorMenuItem{}, false
}
// mustMenu 断言某项存在并返回它。
func mustMenu(t *testing.T, items []editorMenuItem, id string) editorMenuItem {
t.Helper()
it, ok := menuByID(items, id)
if !ok {
t.Fatalf("菜单里没有 %q", id)
}
return it
}
// goReady 是这个项目里最常见的组合:工作区内的 Go 文件 + 语言服务器在线。
func goReady() editorMenuCap {
return editorMenuCap{goFile: true, lspReady: true, inRoot: true, onDisk: true}
}
// TestEditorMenuGoFile 普通 Go 文件:gopls 那几项可用,测试项不出现。
func TestEditorMenuGoFile(t *testing.T) {
items := editorMenuItems(goReady())
for _, id := range []string{emCodeActions, emFindRefs, emRename, emFormat, emFind} {
if it := mustMenu(t, items, id); !it.enabled {
t.Fatalf("%q 应该是可用的", id)
}
}
// 不是 _test.go,跑测试的两项不该露头。
for _, id := range []string{emRunTest, emTestPkg} {
if _, ok := menuByID(items, id); ok {
t.Fatalf("非测试文件不该有 %q", id)
}
}
}
// TestEditorMenuTestFile 测试文件多出跑测试的两项。
func TestEditorMenuTestFile(t *testing.T) {
c := goReady()
c.testFile = true
items := editorMenuItems(c)
for _, id := range []string{emRunTest, emTestPkg} {
if it := mustMenu(t, items, id); !it.enabled {
t.Fatalf("%q 应该可用", id)
}
}
}
// TestEditorMenuTestFileOutsideRoot 工作区外打开的测试文件跑不了:没有包路径。
func TestEditorMenuTestFileOutsideRoot(t *testing.T) {
c := goReady()
c.testFile, c.inRoot = true, false
items := editorMenuItems(c)
if _, ok := menuByID(items, emRunTest); ok {
t.Fatal("不在工作区内不该出现跑测试")
}
}
// TestEditorMenuNonGo 非 Go 文件:gopls 相关的都灰掉,只用通用项。
func TestEditorMenuNonGo(t *testing.T) {
c := editorMenuCap{inRoot: true, onDisk: true} // goFile 与 lspReady 都是 false
items := editorMenuItems(c)
for _, id := range []string{emCodeActions, emFindRefs, emRename, emFormat} {
if it := mustMenu(t, items, id); it.enabled {
t.Fatalf("非 Go 文件的 %q 应该灰掉", id)
}
}
if it := mustMenu(t, items, emFind); !it.enabled {
t.Fatal("「在文件中查找」与语言无关,应该可用")
}
if it := mustMenu(t, items, emRevealOS); !it.enabled {
t.Fatal("「在资源管理器中显示」应该可用")
}
}
// TestEditorMenuNoLSP 语言服务器挂了:代码动作类全灰,但复制路径照旧。
func TestEditorMenuNoLSP(t *testing.T) {
c := goReady()
c.lspReady = false
items := editorMenuItems(c)
if it := mustMenu(t, items, emFindRefs); it.enabled {
t.Fatal("gopls 不在时「查找引用」应该灰掉")
}
if it := mustMenu(t, items, emCopyAbs); !it.enabled {
t.Fatal("复制绝对路径不该受 gopls 影响")
}
}
// TestEditorMenuReadOnly 只读缓冲区:改文本的项灰掉,只读的项留着。
func TestEditorMenuReadOnly(t *testing.T) {
c := goReady()
c.readOnly = true
items := editorMenuItems(c)
for _, id := range []string{emCodeActions, emRename, emFormat} {
if it := mustMenu(t, items, id); it.enabled {
t.Fatalf("只读文件的 %q 应该灰掉", id)
}
}
if it := mustMenu(t, items, emFindRefs); !it.enabled {
t.Fatal("只读文件的「查找引用」仍然可用")
}
}
// TestEditorMenuOutsideRoot 工作区外:相对路径与树内定位都没有意义。
func TestEditorMenuOutsideRoot(t *testing.T) {
c := goReady()
c.inRoot = false
items := editorMenuItems(c)
for _, id := range []string{emCopyRel, emRevealTree} {
if it := mustMenu(t, items, id); it.enabled {
t.Fatalf("工作区外的 %q 应该灰掉", id)
}
}
if it := mustMenu(t, items, emCopyAbs); !it.enabled {
t.Fatal("绝对路径在哪儿都能复制")
}
}
// TestCompactEditorMenu 分隔线不留头尾、也不连着两条。
func TestCompactEditorMenu(t *testing.T) {
sep := editorMenuItem{sep: true}
item := func(id string) editorMenuItem { return editorMenuItem{id: id, label: id, enabled: true} }
cases := []struct {
name string
in []editorMenuItem
want []string // "" 表示分隔线
}{
{"连续分隔线合并", []editorMenuItem{item("a"), sep, sep, item("b")}, []string{"a", "", "b"}},
{"去掉开头", []editorMenuItem{sep, sep, item("a")}, []string{"a"}},
{"去掉结尾", []editorMenuItem{item("a"), sep, sep}, []string{"a"}},
{"全是分隔线", []editorMenuItem{sep, sep}, nil},
{"空输入", nil, nil},
{"原样保留", []editorMenuItem{item("a"), sep, item("b")}, []string{"a", "", "b"}},
}
for _, c := range cases {
got := compactEditorMenu(c.in)
if len(got) != len(c.want) {
t.Fatalf("%s:长度 %d, 想要 %d", c.name, len(got), len(c.want))
}
for i, want := range c.want {
isSep := got[i].sep
if (want == "") != isSep {
t.Fatalf("%s:第 %d 项分隔线状态不对", c.name, i)
}
if !isSep && got[i].id != want {
t.Fatalf("%s:第 %d 项是 %q, 想要 %q", c.name, i, got[i].id, want)
}
}
}
}
// TestEditorMenuNormalized 真实产出的菜单本身就已经规整过。
func TestEditorMenuNormalized(t *testing.T) {
// 非测试文件 + 工作区外,是条件组缺席最多的组合。
items := editorMenuItems(editorMenuCap{goFile: true, lspReady: true})
if len(items) == 0 {
t.Fatal("菜单不该是空的")
}
if items[0].sep || items[len(items)-1].sep {
t.Fatal("菜单首尾不该是分隔线")
}
for i := 1; i < len(items); i++ {
if items[i].sep && items[i-1].sep {
t.Fatalf("第 %d、%d 项是连着两条分隔线", i-1, i)
}
}
}
// TestEditorMenuLabels 每一项都得有文案,且不重名——重名会让用户分不清点的是哪个。
func TestEditorMenuLabels(t *testing.T) {
seen := map[string]string{}
for _, it := range editorMenuItems(goReady()) {
if it.sep {
continue
}
if strings.TrimSpace(it.label) == "" {
t.Fatalf("%q 没有文案", it.id)
}
if prev, dup := seen[it.label]; dup {
t.Fatalf("%q 与 %q 文案重复:%s", prev, it.id, it.label)
}
seen[it.label] = it.id
}
}
// TestEditorMenuShortcut 只给真绑了快捷键的项挂字样。
func TestEditorMenuShortcut(t *testing.T) {
cases := []struct {
id string
mods ui.Modifiers
key ui.Key
}{
{emCodeActions, ui.Alt, ui.KeyEnter},
{emFindRefs, ui.Shift, ui.KeyF2},
{emRename, 0, ui.KeyF2},
{emFormat, ui.Ctrl | ui.Alt, ui.KeyL},
{emFind, ui.Cmd, ui.KeyF},
}
for _, c := range cases {
mods, key, ok := editorMenuShortcut(c.id)
if !ok {
t.Fatalf("%q 应该有快捷键", c.id)
}
if mods != c.mods || key != c.key {
t.Fatalf("%q 的快捷键不对", c.id)
}
}
// 没有绑定快捷键的项不能瞎标。
for _, id := range []string{emRunTest, emTestPkg, emCopyAbs, emCopyRel, emRevealOS, emRevealTree, emHistory} {
if _, _, ok := editorMenuShortcut(id); ok {
t.Fatalf("%q 没有快捷键却标了", id)
}
}
}
// TestMenuRelPath 相对路径统一用正斜杠,出圈时退回绝对路径。
func TestMenuRelPath(t *testing.T) {
root := `/w/proj`
cases := []struct{ path, want string }{
{`/w/proj/main.go`, "main.go"},
{`/w/proj/internal/app/x.go`, "internal/app/x.go"},
{`/w/other/x.go`, `/w/other/x.go`}, // 不在工作区内
{``, ``},
}
for _, c := range cases {
if got := menuRelPath(root, c.path); got != c.want {
t.Fatalf("menuRelPath(%q) = %q, 想要 %q", c.path, got, c.want)
}
}
if got := menuRelPath("", `/w/proj/main.go`); got != `/w/proj/main.go` {
t.Fatalf("没有工作区时应返回原路径,got %q", got)
}
}
// TestEditorMenuOnDoc 从真实文档读出能力:这条链路把 path/只读/工作区串起来。
func TestEditorMenuOnDoc(t *testing.T) {
dir := t.TempDir()
a := &App{root: dir}
goOn := a.newDoc(dir+`/main_test.go`, "package main\n")
items := editorMenuItems(a.editorMenuCap(goOn))
// 没有 LSP,代码动作该灰。
if it := mustMenu(t, items, emCodeActions); it.enabled {
t.Fatal("没有语言服务器时代码动作应灰")
}
// 但它在工作区内且是 _test.go,跑测试的项该在(且可用)。
if it := mustMenu(t, items, emRunTest); !it.enabled {
t.Fatal("工作区内的测试文件应能跑光标处的测试")
}
// 换成只读 + 非 Go 的文档,代码动作、格式化都灰,且没有测试项。
ro := a.newDoc(dir+`/notes.txt`, "hello\n")
ro.st.ReadOnly = true
items = editorMenuItems(a.editorMenuCap(ro))
if it := mustMenu(t, items, emFormat); it.enabled {
t.Fatal("只读文件的格式化应灰")
}
if _, ok := menuByID(items, emRunTest); ok {
t.Fatal("txt 文件不该有跑测试")
}
}
// TestEditorMenuShowsInEditor 真把菜单弹出来:右键编辑器,读菜单文案。
//
// 这一步是纯函数测试覆盖不到的那一半——钩子有没有真挂在 editor.State 上、
// 框架有没有在它自己那批项后面接上应用层的项、灰掉的项是不是真点不动。
func TestEditorMenuShowsInEditor(t *testing.T) {
dir := t.TempDir()
a := &App{root: dir}
d := a.newDoc(filepath.Join(dir, "main.go"), "package main\n")
tt := ui.NewTester(func(c *ui.Context) {
editor.View(c, d.st).Fill().AutoFocus()
}, 600, 400)
tt.Frame()
tt.RightClickAt(300, 200)
labels := tt.Menu()
if len(labels) == 0 {
t.Fatal("右键编辑器没有弹出菜单")
}
for _, want := range []string{"代码动作(Alt+Enter)", "复制相对路径", "复制绝对路径", "在资源管理器中显示"} {
if !strings.Contains(strings.Join(labels, "\n"), want) {
t.Fatalf("菜单里没有 %q,实际:%q", want, labels)
}
}
// 没有语言服务器,「代码动作」是灰的:点它应当被拒。
if err := tt.ChooseMenuItem("代码动作(Alt+Enter)"); err == nil {
t.Fatal("灰掉的菜单项居然能选")
}
// 换一项能用的:复制绝对路径,走完整条 「菜单 → 动作 → 剪贴板」 链路。
var copied string
old := clipWrite
clipWrite = func(s string) error { copied = s; return nil }
defer func() { clipWrite = old }()
if err := tt.ChooseMenuItem("复制绝对路径"); err != nil {
t.Fatalf("选「复制绝对路径」失败:%v", err)
}
tt.Frame()
if copied != d.path {
t.Fatalf("复制了 %q, 想要 %q", copied, d.path)
}
// 相对路径那项复制的是相对工作区的写法。
copied = ""
tt.RightClickAt(300, 200)
if err := tt.ChooseMenuItem("复制相对路径"); err != nil {
t.Fatalf("选「复制相对路径」失败:%v", err)
}
if copied != "main.go" {
t.Fatalf("复制了 %q, 想要 main.go", copied)
}
}
+47 -8
View File
@@ -150,40 +150,79 @@ func (a *App) treeEntries(path string, isDir bool) []menuEntry {
return out return out
} }
// deletePaths 删除文件或目录。删目录用 RemoveAll,会连内容一起删掉, // deletePaths 删除文件或目录。
// 所以先明确问一次,并列出数量。 //
// 默认走回收站(可撤销),另给「永久删除」。默认必须是可逆的那个:
// 删目录是递归的,误点一下整包源码就没了,而回收站只是多一步清空。
func (a *App) deletePaths(paths []string) { func (a *App) deletePaths(paths []string) {
if len(paths) == 0 || a.win == nil { if len(paths) == 0 || a.win == nil {
return return
} }
hasDir := false
for _, p := range paths {
if st, err := os.Stat(p); err == nil && st.IsDir() {
hasDir = true
break
}
}
what := "项目" what := "项目"
if len(paths) == 1 { if len(paths) == 1 {
what = filepath.Base(paths[0]) what = filepath.Base(paths[0])
} }
msg := fmt.Sprintf("确定删除 %s?\n此操作不可撤销。", what) var msg string
if len(paths) > 1 { switch {
msg = fmt.Sprintf("确定删除选中的 %d 个项目?\n其中目录会连内容一起删除,此操作不可撤销。", len(paths)) case len(paths) == 1 && hasDir:
msg = fmt.Sprintf("确定删除目录 %s?\n目录会连同里面的内容一起删除。", what)
case len(paths) == 1:
msg = fmt.Sprintf("确定删除 %s?", what)
case hasDir:
msg = fmt.Sprintf("确定删除选中的 %d 项?\n其中目录会连同里面的内容一起删除。", len(paths))
default:
msg = fmt.Sprintf("确定删除选中的 %d 项?", len(paths))
} }
msg += "\n\n移到回收站可以恢复;永久删除不可恢复。"
const (
btnTrash = 0
btnPermanent = 1
btnCancel = 2
)
res, err := mygo.Dialog.Message(mygo.MessageOptions{ res, err := mygo.Dialog.Message(mygo.MessageOptions{
Parent: a.win, Parent: a.win,
Type: mygo.MessageWarning, Type: mygo.MessageWarning,
Title: "删除", Title: "删除",
Message: msg, Message: msg,
Buttons: []string{"删除", "取消"}, Buttons: []string{"移到回收站", "永久删除", "取消"},
CancelButton: 1, DefaultButton: btnTrash,
CancelButton: btnCancel,
// 告诉系统哪个按钮是不可逆的:macOS 11+ 会把它单独摆放,
// 并且不让回车键顺手激活它。Windows 的 task dialog 没有这个概念,
// 传了也不生效——所以在 Windows 上「默认按钮是回收站」才是保险的那道。
DestructiveButtons: []int{btnPermanent},
}) })
if err != nil || res.Button != 0 { if err != nil || res.Button == btnCancel {
return return
} }
switch res.Button {
case btnTrash:
if err := moveToTrash(paths); err != nil {
// 失败就停手,绝不悄悄退化成永久删除。
a.alert("移到回收站失败", err.Error()+"\n\n可以重试,或改用「永久删除」。")
return
}
case btnPermanent:
for _, p := range paths { for _, p := range paths {
if err := os.RemoveAll(p); err != nil { if err := os.RemoveAll(p); err != nil {
a.appendOut(err.Error()) a.appendOut(err.Error())
a.panel = true a.panel = true
} }
} }
default:
return
}
// 被删掉的文件如果开着,标签也要跟着关,否则编辑器指向一个不存在的路径。 // 被删掉的文件如果开着,标签也要跟着关,否则编辑器指向一个不存在的路径。
a.win.Update(func() { a.win.Update(func() {
-9
View File
@@ -1,10 +1 @@
package app package app
// trimTo 把字符串截断到 n 个字符,历史列表里的标题用。
func trimTo(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
+31 -6
View File
@@ -10,38 +10,54 @@ import (
// 文件名索引与模糊匹配,供快速打开使用。 // 文件名索引与模糊匹配,供快速打开使用。
// indexFileCap 是文件索引的规模上限。超过就截断并置 indexState.truncated,
// 界面据此提示——静默截断会让用户以为「搜不到就是没有」。
const indexFileCap = 20000
// indexState 是工作区文件索引。 // indexState 是工作区文件索引。
type indexState struct { type indexState struct {
mu sync.Mutex mu sync.Mutex
root string root string
files []string // 相对路径,正斜杠 files []string // 相对路径,正斜杠
ready bool ready bool
truncated bool // 是否因超过 indexFileCap 被截断
} }
// buildIndex 在后台遍历工作区,收集可打开的文件。 // buildIndex 在后台遍历工作区,收集可打开的文件。
//
// 跳过规则有三层:内置目录(.git/vendor/dist…)、根 .gitignore、
// 生成物后缀(.exe/.test)。vendor 必须跳过——一个 Go 项目的 vendor
// 能塞几千个包,进索引后快速打开与全局搜索全是第三方噪音。
func (a *App) buildIndex(root string) { func (a *App) buildIndex(root string) {
rules := loadIgnoreRules(root)
go func() { go func() {
var files []string var files []string
truncated := false
_ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil { if err != nil {
return nil return nil
} }
name := d.Name() name := d.Name()
rel, relErr := filepath.Rel(root, p)
relSlash := ""
if relErr == nil {
relSlash = filepath.ToSlash(rel)
}
if d.IsDir() { if d.IsDir() {
if p != root && skipDir(name) { if p != root && (isBuiltinSkipDir(name) || rules.match(relSlash, true)) {
return filepath.SkipDir return filepath.SkipDir
} }
return nil return nil
} }
if skipFile(name) { if skipFile(name) || rules.match(relSlash, false) {
return nil return nil
} }
rel, err := filepath.Rel(root, p) if relErr != nil {
if err != nil {
return nil return nil
} }
files = append(files, filepath.ToSlash(rel)) files = append(files, relSlash)
if len(files) > 20000 { if len(files) > indexFileCap {
truncated = true
return filepath.SkipAll return filepath.SkipAll
} }
return nil return nil
@@ -51,6 +67,7 @@ func (a *App) buildIndex(root string) {
if a.index.root == root { if a.index.root == root {
a.index.files = files a.index.files = files
a.index.ready = true a.index.ready = true
a.index.truncated = truncated
} }
a.index.mu.Unlock() a.index.mu.Unlock()
}() }()
@@ -72,6 +89,14 @@ func (a *App) indexSnapshot() ([]string, bool) {
return a.index.files, a.index.ready return a.index.files, a.index.ready
} }
// indexTruncated 报告索引是否因超过 indexFileCap 被截断。
// 只看已建好的索引:没建好时截断与否还没有意义。
func (a *App) indexTruncated() bool {
a.index.mu.Lock()
defer a.index.mu.Unlock()
return a.index.ready && a.index.truncated
}
// fuzzyScore 判断 query 是否为 path 的子序列,并给出一个分数(越大越靠前)。 // fuzzyScore 判断 query 是否为 path 的子序列,并给出一个分数(越大越靠前)。
// //
// 规则很朴素:连续匹配、匹配到文件名部分、匹配位置靠前,都会加分。 // 规则很朴素:连续匹配、匹配到文件名部分、匹配位置靠前,都会加分。
+42 -3
View File
@@ -3,6 +3,7 @@ package app
import ( import (
"crypto/sha1" "crypto/sha1"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@@ -44,6 +45,19 @@ type histIndex struct {
Entries []histEntry `json:"entries"` Entries []histEntry `json:"entries"`
} }
// histSkipped 不是写失败,而是「这次故意没留历史点」,需要让用户知道原因。
// 用独立类型把它和真正的 IO 错误分开:前者进输出面板,后者进日志。
type histSkipped struct{ msg string }
func (e histSkipped) Error() string { return e.msg }
// histSkipMessage 说明为什么这个文件没被纳入本地历史。
// 单列成纯函数是为了能测:措辞里要带文件名、上限,别只说「失败」。
func histSkipMessage(path string, size int) string {
return fmt.Sprintf("本地历史:%s 超过 %d MB 上限(当前 %.1f MB),该文件不会有历史快照",
filepath.Base(path), histMaxSize/(1<<20), float64(size)/(1<<20))
}
// histMu 串行化索引读写:多个文档同时保存会并发进来。 // histMu 串行化索引读写:多个文档同时保存会并发进来。
var histMu sync.Mutex var histMu sync.Mutex
@@ -58,10 +72,17 @@ func historyDir(path string) string {
} }
// saveSnapshot 给文件留一个历史点;内容没变时直接跳过。 // saveSnapshot 给文件留一个历史点;内容没变时直接跳过。
//
// 超过 histMaxSize 时返回 histSkipped(不是 error 日志),调用方要把它
// 转成用户可见的说明——以前这里静默 return nil,大文件改坏后用户根本
// 不知道自己没有快照可回。
func saveSnapshot(path string, data []byte, reason string, dirty bool) error { func saveSnapshot(path string, data []byte, reason string, dirty bool) error {
if len(data) == 0 || len(data) > histMaxSize { if len(data) == 0 {
return nil return nil
} }
if len(data) > histMaxSize {
return histSkipped{histSkipMessage(path, len(data))}
}
dir := historyDir(path) dir := historyDir(path)
if dir == "" { if dir == "" {
return nil return nil
@@ -225,7 +246,15 @@ func loadPending() []pendingSnap {
return items return items
} }
// snapshotAsync 在后台给文档留一个历史点,失败只记日志。 // shouldWarnHistory 判断这个文件的「超限」提示是否还没发过。
// LoadOrStore 保证并发自动快照里也只过一次。
func (a *App) shouldWarnHistory(path string) bool {
_, warned := a.histWarned.LoadOrStore(path, struct{}{})
return !warned
}
// snapshotAsync 在后台给文档留一个历史点,真正的写失败只记日志;
// 「故意跳过」要让用户看见,否则用户会以为自己有快照可回。
func (a *App) snapshotAsync(d *Doc, reason string, dirty bool) { func (a *App) snapshotAsync(d *Doc, reason string, dirty bool) {
if d == nil || d.truncated || !a.set.History { if d == nil || d.truncated || !a.set.History {
return return
@@ -240,7 +269,17 @@ func (a *App) snapshotAsync(d *Doc, reason string, dirty bool) {
if err != nil { if err != nil {
return return
} }
if err := saveSnapshot(path, data, reason, dirty); err != nil { err = saveSnapshot(path, data, reason, dirty)
var skipped histSkipped
if errors.As(err, &skipped) {
if a.win == nil || !a.shouldWarnHistory(path) {
return
}
msg := skipped.Error()
a.win.Update(func() { a.appendOut(msg) })
return
}
if err != nil {
logf("本地历史写入失败:%v", err) logf("本地历史写入失败:%v", err)
} }
}() }()
+36 -3
View File
@@ -1,8 +1,10 @@
package app package app
import ( import (
"errors"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
) )
@@ -80,7 +82,8 @@ func TestSnapshotPrune(t *testing.T) {
} }
} }
// TestSnapshotTooLarge 超大内容不存历史,避免把日志反复复制。 // TestSnapshotTooLarge 超大内容不存历史,但必须把「跳过」这件事报出来,
// 不能像以前那样静默 return nil——用户会误以为有快照可回。
func TestSnapshotTooLarge(t *testing.T) { func TestSnapshotTooLarge(t *testing.T) {
isolateConfig(t) isolateConfig(t)
path := filepath.Join(t.TempDir(), "big.log") path := filepath.Join(t.TempDir(), "big.log")
@@ -88,12 +91,42 @@ func TestSnapshotTooLarge(t *testing.T) {
for i := range big { for i := range big {
big[i] = 'x' big[i] = 'x'
} }
if err := saveSnapshot(path, big, "save", false); err != nil { err := saveSnapshot(path, big, "save", false)
t.Fatal(err) var skipped histSkipped
if !errors.As(err, &skipped) {
t.Fatalf("超大内容应返回 histSkipped,实际 %v", err)
} }
if n := len(listHistory(path)); n != 0 { if n := len(listHistory(path)); n != 0 {
t.Fatalf("超大内容不该留历史,实际 %d 条", n) t.Fatalf("超大内容不该留历史,实际 %d 条", n)
} }
// 空文件是正常跳过,不该报「超限」。
if err := saveSnapshot(path, nil, "save", false); err != nil {
t.Fatalf("空文件不该报错,实际 %v", err)
}
}
// TestHistSkipMessage 提示要说清是哪个文件、上限多少,不能只说「失败」。
func TestHistSkipMessage(t *testing.T) {
msg := histSkipMessage(filepath.Join("a", "b", "huge.log"), histMaxSize+1)
for _, want := range []string{"huge.log", "4 MB", "本地历史"} {
if !strings.Contains(msg, want) {
t.Fatalf("提示缺 %q:%s", want, msg)
}
}
}
// TestShouldWarnHistoryOnce 自动快照每分钟一次,提示不能刷屏。
func TestShouldWarnHistoryOnce(t *testing.T) {
a := &App{}
if !a.shouldWarnHistory("C:/x/big.go") {
t.Fatal("首次应当提示")
}
if a.shouldWarnHistory("C:/x/big.go") {
t.Fatal("同一文件不该提示第二次")
}
if !a.shouldWarnHistory("C:/x/other.go") {
t.Fatal("另一个文件应当独立提示")
}
} }
// TestPendingRoundTrip 未保存标记能写能读能清。 // TestPendingRoundTrip 未保存标记能写能读能清。
+171
View File
@@ -0,0 +1,171 @@
package app
import (
"os"
"path"
"path/filepath"
"strings"
)
// .gitignore 的简化实现。
//
// 为什么自己写而不引库:只需要给「索引」和「搜索」做过滤,不需要
// 完整 git 语义(.git/info/exclude、全局 excludesfile、嵌套 .gitignore、
// `\` 转义、`[]` 字符类都省了)。完整实现要几百行且要处理一堆边界,
// 收益抵不上——漏掉的规则最多是多收录几个文件,不会出错。
//
// 支持的形态(覆盖日常项目里真正会写的那几类):
//
// dir/ 忽略任意层级下叫 dir 的目录
// *.ext 忽略任意层级下的后缀
// /rootonly 只忽略工作区根下的这个路径
// sub/dir/file.go 带路径的匹配,支持 ** 跨层通配
// !keep.go 取反(后出现的规则覆盖先出现的)
// # 注释 / 空行 跳过
// ignoreRule 是 .gitignore 里的一条规则。
type ignoreRule struct {
segs []string // 模式按 / 切开的段
negate bool // ! 开头:命中时反而要保留
dirOnly bool // 以 / 结尾:只对目录生效
hasPath bool // 模式里含 /(含开头的 /):要对整条相对路径匹配
}
// ignoreRules 是一份解析好的忽略规则集合;nil 表示没有 .gitignore。
type ignoreRules struct {
rules []ignoreRule
}
// loadIgnoreRules 读取工作区根的 .gitignore;没有或读不到就返回 nil。
func loadIgnoreRules(root string) *ignoreRules {
if root == "" {
return nil
}
data, err := os.ReadFile(filepath.Join(root, ".gitignore"))
if err != nil {
return nil
}
return parseIgnoreRules(string(data))
}
// parseIgnoreRules 解析 .gitignore 文本。
func parseIgnoreRules(text string) *ignoreRules {
r := &ignoreRules{}
for _, line := range strings.Split(text, "\n") {
line = strings.TrimRight(line, " \t\r")
if line == "" || strings.HasPrefix(line, "#") {
continue
}
rule := ignoreRule{}
if strings.HasPrefix(line, "!") {
rule.negate = true
line = line[1:]
}
if strings.HasPrefix(line, "\\#") || strings.HasPrefix(line, "\\!") {
line = line[1:] // 转义的 # 与 ! 当普通字符
}
if strings.HasSuffix(line, "/") {
rule.dirOnly = true
line = strings.TrimRight(line, "/")
}
if strings.HasPrefix(line, "/") {
rule.hasPath = true
line = strings.TrimPrefix(line, "/")
} else if strings.Contains(line, "/") {
rule.hasPath = true
}
if line == "" {
continue
}
rule.segs = strings.Split(line, "/")
r.rules = append(r.rules, rule)
}
if len(r.rules) == 0 {
return nil
}
return r
}
// match 判断相对路径 rel(正斜杠)是否应被忽略。
//
// 语义与 git 一致的部分:后来的规则覆盖先前的(所以 `!` 取反要放在后面);
// 只对目录生效的规则不会命中文件。
func (r *ignoreRules) match(rel string, isDir bool) bool {
if r == nil || rel == "" || rel == "." {
return false
}
rel = strings.TrimPrefix(filepath.ToSlash(rel), "./")
segs := strings.Split(rel, "/")
ignored := false
for _, rule := range r.rules {
if rule.dirOnly && !isDir {
continue
}
hit := false
if rule.hasPath {
hit = matchSegs(rule.segs, segs)
} else {
// 不含 / 的模式对路径里任意一段生效(相当于 basename 匹配)。
for _, s := range segs {
if ok, _ := path.Match(rule.segs[0], s); ok {
hit = true
break
}
}
}
if hit {
ignored = !rule.negate
}
}
return ignored
}
// matchSegs 按段匹配,支持 ** 跨任意多段。
//
// 模式必须从第一段对齐:日常写法里 `sub/a.go` 就是从工作区根算起的相对路径,
// 与 git「不含开头的 / 也允许后缀对齐」略有出入,这里按更直观的语义实现。
func matchSegs(pat, s []string) bool {
for len(pat) > 0 {
if pat[0] == "**" {
// ** 吃掉 0 到 n 段
rest := pat[1:]
if len(rest) == 0 {
return true
}
for i := 0; i <= len(s); i++ {
if matchSegs(rest, s[i:]) {
return true
}
}
return false
}
if len(s) == 0 {
return false
}
if ok, _ := path.Match(pat[0], s[0]); !ok {
return false
}
pat, s = pat[1:], s[1:]
}
return len(s) == 0
}
// builtinSkipDirs 无论 .gitignore 写没写都要跳过的目录。
//
// 前四个是工具数据目录;后面几个是构建产物,Go 项目里 vendor 尤其要紧
// (一个 vendor 能塞进几千个包,进索引后快速打开和搜索全是噪音)。
var builtinSkipDirs = []string{
".git", ".idea", ".mygoland",
"node_modules", "vendor", "dist", "build", "out", "target", ".next",
}
// isBuiltinSkipDir 判断目录名是否在内置跳过清单里。
func isBuiltinSkipDir(name string) bool {
for _, d := range builtinSkipDirs {
if name == d {
return true
}
}
return false
}
+198
View File
@@ -0,0 +1,198 @@
package app
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// TestIgnoreDirRule `dir/` 忽略任意层级下的同名目录,但不动同名文件。
func TestIgnoreDirRule(t *testing.T) {
r := parseIgnoreRules("dist/\n")
if r == nil {
t.Fatal("规则解析为空")
}
if !r.match("dist", true) {
t.Fatal("根下的 dist 目录应被忽略")
}
if !r.match("web/dist", true) {
t.Fatal("任意层级的 dist 目录都应被忽略")
}
if r.match("dist", false) {
t.Fatal("dirOnly 规则不该命中同名文件")
}
if r.match("dist2", true) {
t.Fatal("不该命中前缀相同的目录")
}
}
// TestIgnoreSuffixRule `*.log` 任意层级。
func TestIgnoreSuffixRule(t *testing.T) {
r := parseIgnoreRules("*.log\n")
for _, p := range []string{"a.log", "logs/b.log", "x/y/z.log"} {
if !r.match(p, false) {
t.Fatalf("%s 应被忽略", p)
}
}
if r.match("a.logx", false) {
t.Fatal("不该命中 a.logx")
}
// git 的通配不区分文件与目录:叫 a.log 的目录同样被忽略。
if !r.match("a.log", true) {
t.Fatal("*.log 也应命中同名目录(与 git 一致)")
}
}
// TestIgnoreRootOnly `/build` 只匹配根。
func TestIgnoreRootOnly(t *testing.T) {
r := parseIgnoreRules("/build\n")
if !r.match("build", true) {
t.Fatal("根下的 build 应被忽略")
}
if r.match("sub/build", true) {
t.Fatal("/build 不该命中子目录里的 build")
}
}
// TestIgnorePathRule 带路径的模式按段对齐。
func TestIgnorePathRule(t *testing.T) {
r := parseIgnoreRules("internal/gen/x.go\n")
if !r.match("internal/gen/x.go", false) {
t.Fatal("精确路径应命中")
}
if r.match("other/internal/gen/x.go", false) {
t.Fatal("不该后缀对齐到别处")
}
}
// TestIgnoreDoubleStar `**` 跨层通配。
func TestIgnoreDoubleStar(t *testing.T) {
r := parseIgnoreRules("**/*.pb.go\n")
for _, p := range []string{"a.pb.go", "api/a.pb.go", "api/v1/a.pb.go"} {
if !r.match(p, false) {
t.Fatalf("%s 应被 ** 命中", p)
}
}
r2 := parseIgnoreRules("testdata/**/golden.txt\n")
if !r2.match("testdata/a/golden.txt", false) {
t.Fatal("testdata/**/golden.txt 应命中深层文件")
}
}
// TestIgnoreNegate `!` 取反:后出现的规则覆盖先前的。
func TestIgnoreNegate(t *testing.T) {
r := parseIgnoreRules("*.log\n!keep.log\n")
if !r.match("a.log", false) {
t.Fatal("a.log 应被忽略")
}
if r.match("keep.log", false) {
t.Fatal("keep.log 被 ! 取反,应保留")
}
}
// TestIgnoreComments 注释与空行跳过;全是注释时返回 nil。
func TestIgnoreComments(t *testing.T) {
if r := parseIgnoreRules("# 只有注释\n\n \n"); r != nil {
t.Fatalf("全是注释应返回 nil,得到 %+v", r.rules)
}
r := parseIgnoreRules("# 注释\n*.tmp\n")
if !r.match("x.tmp", false) {
t.Fatal("注释行之后的规则应生效")
}
}
// TestIgnoreNilSafe 没有 .gitignore 时调用不能 panic。
func TestIgnoreNilSafe(t *testing.T) {
var r *ignoreRules
if r.match("a.go", false) {
t.Fatal("nil 规则应一律不忽略")
}
if loadIgnoreRules("") != nil {
t.Fatal("空 root 应返回 nil")
}
if loadIgnoreRules(filepath.Join(t.TempDir(), "nope")) != nil {
t.Fatal("目录不存在应返回 nil")
}
}
// TestLoadIgnoreRulesReal 从磁盘读 .gitignore。
func TestLoadIgnoreRulesReal(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".gitignore"),
[]byte("bin/\n*.exe\n"), 0o644); err != nil {
t.Fatal(err)
}
r := loadIgnoreRules(dir)
if r == nil {
t.Fatal("应读到规则")
}
if !r.match("bin", true) || !r.match("tool.exe", false) {
t.Fatal("规则未生效")
}
}
// TestBuiltinSkipDirs 内置清单:vendor 必须在里面。
func TestBuiltinSkipDirs(t *testing.T) {
for _, d := range []string{".git", "node_modules", "vendor", "dist", "build"} {
if !isBuiltinSkipDir(d) {
t.Fatalf("%s 应在内置跳过清单里", d)
}
}
if isBuiltinSkipDir("internal") || isBuiltinSkipDir("cmd") {
t.Fatal("普通源码目录不该被跳过")
}
}
// TestBuildIndexRespectsIgnores 真实遍历:vendor 与 .gitignore 里的目录都该消失。
func TestBuildIndexRespectsIgnores(t *testing.T) {
dir := t.TempDir()
mk := func(rel, content string) {
p := filepath.Join(dir, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
mk("keep.go", "package x")
mk("internal/a.go", "package internal")
mk("vendor/github.com/x/y.go", "package y")
mk("dist/bundle.js", "// built")
mk("logs/run.txt", "log")
mk(".gitignore", "dist/\nlogs/\n")
a := &App{index: indexState{root: dir}}
a.buildIndex(dir)
// buildIndex 是异步的,等它 ready(最多 2 秒)。
deadline := time.Now().Add(2 * time.Second)
var files []string
for time.Now().Before(deadline) {
var ready bool
files, ready = a.indexSnapshot()
if ready {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(files) == 0 {
t.Fatal("索引没建起来")
}
got := strings.Join(files, ",")
if strings.Contains(got, "vendor/") {
t.Fatalf("vendor 不该进索引:%v", files)
}
if strings.Contains(got, "dist/") {
t.Fatalf("dist 被 .gitignore 忽略,不该进索引:%v", files)
}
if strings.Contains(got, "logs/") {
t.Fatalf("logs 被 .gitignore 忽略,不该进索引:%v", files)
}
if !strings.Contains(got, "keep.go") || !strings.Contains(got, "internal/a.go") {
t.Fatalf("正常源码文件被误杀:%v", files)
}
}
+20 -4
View File
@@ -7,7 +7,7 @@ import (
"path/filepath" "path/filepath"
) )
// logMaxSize 是日志文件的上限,超过则在启动时清空重来。 // logMaxSize 是单个日志文件的上限,超过则轮转成 .1 后重开。
const logMaxSize = 4 << 20 const logMaxSize = 4 << 20
// logPath 是当前日志文件路径,为空表示没启用文件日志。 // logPath 是当前日志文件路径,为空表示没启用文件日志。
@@ -27,9 +27,7 @@ func SetupLog() string {
return "" return ""
} }
p := filepath.Join(dir, "mygoland.log") p := filepath.Join(dir, "mygoland.log")
if st, err := os.Stat(p); err == nil && st.Size() > logMaxSize { rotateLog(p, logMaxSize)
_ = os.Remove(p)
}
f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
return "" return ""
@@ -40,5 +38,23 @@ func SetupLog() string {
return p return p
} }
// rotateLog 在日志超过 max 时把它改名成 <path>.1。
//
// 为什么不直接删:崩溃排查往往发生在「刚出问题、马上想看日志」的时候,
// 那时日志恰好跨过上限就把证据删干净了,是最坏的结果。
// 只保留一份历史(.1)够用——两份 4MB 已经能覆盖一次完整会话。
func rotateLog(path string, max int64) {
st, err := os.Stat(path)
if err != nil || st.Size() <= max {
return
}
old := path + ".1"
_ = os.Remove(old) // 覆盖上一份历史
if err := os.Rename(path, old); err != nil {
// 改名失败(可能被别的进程占着):继续追加比丢日志强,不删。
logf("日志轮转失败,继续追加:%v", err)
}
}
// LogPath 返回日志文件路径。 // LogPath 返回日志文件路径。
func LogPath() string { return logPath } func LogPath() string { return logPath }
+91
View File
@@ -0,0 +1,91 @@
package app
import (
"os"
"path/filepath"
"testing"
)
// writeSized 造一个指定大小的文件。
func writeSized(t *testing.T, p string, n int64) {
t.Helper()
f, err := os.Create(p)
if err != nil {
t.Fatal(err)
}
if n > 0 {
if _, err := f.Write(make([]byte, n)); err != nil {
t.Fatal(err)
}
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
// TestRotateLogOverLimit 超过上限时改名成 .1,原文件消失。
func TestRotateLogOverLimit(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "mygoland.log")
writeSized(t, p, 1024)
rotateLog(p, 512)
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatalf("原日志应已被改名,stat err = %v", err)
}
st, err := os.Stat(p + ".1")
if err != nil {
t.Fatalf(".1 应存在:%v", err)
}
if st.Size() != 1024 {
t.Fatalf(".1 大小 = %d, 想要 1024", st.Size())
}
}
// TestRotateLogUnderLimit 没超上限什么都不做。
func TestRotateLogUnderLimit(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "mygoland.log")
writeSized(t, p, 100)
rotateLog(p, 512)
if _, err := os.Stat(p + ".1"); !os.IsNotExist(err) {
t.Fatal("未超上限不该轮转")
}
st, err := os.Stat(p)
if err != nil || st.Size() != 100 {
t.Fatalf("原日志应原样保留:%v", err)
}
}
// TestRotateLogOverwritesOld 已有 .1 时覆盖它,不无限堆积。
func TestRotateLogOverwritesOld(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "mygoland.log")
writeSized(t, p+".1", 10)
writeSized(t, p, 2048)
rotateLog(p, 512)
st, err := os.Stat(p + ".1")
if err != nil {
t.Fatal(err)
}
if st.Size() != 2048 {
t.Fatalf(".1 应被新日志覆盖(2048),实际 %d", st.Size())
}
if _, err := os.Stat(p + ".2"); !os.IsNotExist(err) {
t.Fatal("只保留一份历史,不该出现 .2")
}
}
// TestRotateLogMissing 文件不存在时不 panic、不建文件。
func TestRotateLogMissing(t *testing.T) {
p := filepath.Join(t.TempDir(), "nope.log")
rotateLog(p, 512)
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatal("不该凭空建出日志文件")
}
}
+4 -2
View File
@@ -75,7 +75,7 @@ func (a *App) onLSPExit(root string, gen int) {
} }
// resetDocsForLSP 清掉文档的已同步标记:重连后所有 Go 文件要重新 didOpen // resetDocsForLSP 清掉文档的已同步标记:重连后所有 Go 文件要重新 didOpen
//(prev 快照由 lspOpen 重新设)。须在主线程调用。 // (prev 快照由 lspOpen 重新设)。须在主线程调用。
func (a *App) resetDocsForLSP() { func (a *App) resetDocsForLSP() {
for _, d := range a.docs { for _, d := range a.docs {
if lsp.IsGoFile(d.path) { if lsp.IsGoFile(d.path) {
@@ -303,7 +303,7 @@ func toEditorCompletion(it lsp.CompletionItem) editor.Completion {
if insert == "" { if insert == "" {
insert = it.Label insert = it.Label
} }
return editor.Completion{ out := editor.Completion{
Label: it.Label, Label: it.Label,
Detail: it.Detail, Detail: it.Detail,
Kind: completionKind(it.Kind), Kind: completionKind(it.Kind),
@@ -311,6 +311,8 @@ func toEditorCompletion(it lsp.CompletionItem) editor.Completion {
Documentation: it.DocumentationText(), Documentation: it.DocumentationText(),
FilterText: it.FilterText, FilterText: it.FilterText,
} }
applyCompletionSnippet(&out, it, insert)
return out
} }
// completionKind 映射 LSP 补全类型。 // completionKind 映射 LSP 补全类型。
+343
View File
@@ -0,0 +1,343 @@
package app
import (
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"unicode"
)
// 移动 Go 包时同步 import 路径。
//
// 为什么不用 gopls:实测 v0.23 的 server capabilities 里
// workspace.fileOperations 只声明 didCreate,没有 willRename/didRename,
// 它不会响应 workspace/willRenameFiles;textDocument/rename 改的是符号
// 引用,改不了包路径。所以这一层自己用 go/parser 精确改字符串字面量。
//
// 为什么用 AST 而不是字符串替换:中文注释里出现同名路径很常见,
// 全局替换会误伤。只动 *ast.ImportSpec.Path 这一个 token 才安全。
// modulePath 从 go.mod 内容里取 module 行。
func modulePath(gomod []byte) string {
for _, line := range strings.Split(string(gomod), "\n") {
line = strings.TrimSpace(line)
rest, ok := strings.CutPrefix(line, "module")
if !ok {
continue
}
// module 后面必须跟空白或引号,否则是 "modulefoo" 这类别的指令。
if rest != "" && rest[0] != ' ' && rest[0] != '\t' && rest[0] != '"' && rest[0] != '`' {
continue
}
return strings.TrimSpace(strings.Trim(strings.TrimSpace(rest), "\"`"))
}
return ""
}
// importPathFor 把目录转成 import 路径。返回空串表示不在模块里。
func importPathFor(root, module, dir string) string {
if module == "" || root == "" {
return ""
}
rel, err := filepath.Rel(root, dir)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return ""
}
rel = filepath.ToSlash(rel)
if rel == "." {
return module
}
return module + "/" + rel
}
type spanEdit struct {
start, end int
text string
}
// planImportEdits 找出 src 里所有指向 oldPath 的 import 字面量。
//
// 只认精确匹配和「oldPath/子包」前缀,避免把 idetest/greeter2
// 误当成 idetest/greeter。
func planImportEdits(src []byte, oldPath, newPath string) ([]spanEdit, error) {
if oldPath == "" || newPath == "" || oldPath == newPath {
return nil, nil
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
if err != nil {
return nil, err
}
var out []spanEdit
for _, spec := range f.Imports {
lit, err := strconv.Unquote(spec.Path.Value)
if err != nil {
continue
}
var next string
switch {
case lit == oldPath:
next = newPath
case strings.HasPrefix(lit, oldPath+"/"):
next = newPath + strings.TrimPrefix(lit, oldPath)
default:
continue
}
start := fset.Position(spec.Path.Pos()).Offset
end := fset.Position(spec.Path.End()).Offset
if start < 0 || end > len(src) || start >= end {
continue
}
out = append(out, spanEdit{start: start, end: end, text: strconv.Quote(next)})
}
return out, nil
}
// applySpans 从后往前套用替换,前面的偏移量才不会漂移。
func applySpans(src []byte, edits []spanEdit) []byte {
if len(edits) == 0 {
return src
}
// parser 按 import 出现顺序产出,本来就是升序;保险起见排一次。
for i := 1; i < len(edits); i++ {
for j := i; j > 0 && edits[j].start < edits[j-1].start; j-- {
edits[j], edits[j-1] = edits[j-1], edits[j]
}
}
out := append([]byte(nil), src...)
for i := len(edits) - 1; i >= 0; i-- {
e := edits[i]
tail := append([]byte(nil), out[e.end:]...)
out = append(out[:e.start], []byte(e.text)...)
out = append(out, tail...)
}
return out
}
// rewriteGoImports 把 src 里指向 oldPath 的 import 改成 newPath。
// 返回新内容、改动处数;语法有问题时返回错误,由调用方决定降级。
func rewriteGoImports(src []byte, oldPath, newPath string) ([]byte, int, error) {
edits, err := planImportEdits(src, oldPath, newPath)
if err != nil {
return nil, 0, err
}
if len(edits) == 0 {
return src, 0, nil
}
return applySpans(src, edits), len(edits), nil
}
// validIdent 判断 s 能不能当 Go 包名:字母/下划线开头,且不能是关键字。
func validIdent(s string) bool {
if s == "" || token.Lookup(s).IsKeyword() {
return false
}
for i, r := range s {
if r == '_' || unicode.IsLetter(r) || (i > 0 && unicode.IsDigit(r)) {
continue
}
return false
}
return true
}
// packageName 读 .go 文件里的 package 名。
func readPackageDecl(src []byte) (string, error) {
f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.PackageClauseOnly)
if err != nil {
return "", err
}
return f.Name.Name, nil
}
// rewritePackageDecl 把 package 声明换成 name(只动那一个标识符)。
// 名字不合法或本来就一样时不改。
func rewritePackageDecl(src []byte, name string) ([]byte, bool, error) {
if !validIdent(name) {
return src, false, nil
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, parser.PackageClauseOnly)
if err != nil {
return nil, false, err
}
if f.Name.Name == name {
return src, false, nil
}
start := fset.Position(f.Name.Pos()).Offset
end := fset.Position(f.Name.End()).Offset
if start < 0 || end > len(src) || start >= end {
return src, false, nil
}
return applySpans(src, []spanEdit{{start: start, end: end, text: name}}), true, nil
}
// goSourceFiles 列出工作区里所有 .go 文件(含 _test.go,测试文件一样 import 包)。
// 不用 workspaceFiles():那份索引会被 20000 文件上限截断,漏改一个引用就编译失败。
func goSourceFiles(root string) []string {
var out []string
_ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
if p != root && (strings.HasPrefix(d.Name(), ".") || d.Name() == "vendor" || d.Name() == "node_modules") {
return filepath.SkipDir
}
return nil
}
if strings.HasSuffix(d.Name(), ".go") {
out = append(out, p)
}
return nil
})
return out
}
// targetPackageName 是单文件移进 dir 后该用的包名:优先跟目录里已有的
// .go 文件一致(外部测试包 xxx_test 不算),否则用目录名规范化出来的名字。
func targetPackageName(dir string) string {
entries, err := os.ReadDir(dir)
if err != nil {
return ""
}
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") || strings.HasSuffix(e.Name(), "_test.go") {
continue
}
src, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
if n, err := readPackageDecl(src); err == nil && validIdent(n) {
return n
}
}
n := packageName(filepath.Base(dir))
if validIdent(n) {
return n
}
return ""
}
// planGoMoveEdits 在 os.Rename 之前算出所有要改写的文件。
//
// 返回的 key 是**移动之后**的路径:目录里的文件也会跟着搬到新位置,
// 所以落盘必须等 rename 完成再做。读不全或语法有问题的文件直接跳过,
// 宁可少改一处让用户自己补,也不能因为一个坏文件把整个移动搞砸。
func (a *App) planGoMoveEdits(old, target string) map[string][]byte {
edits := map[string][]byte{}
if a.root == "" {
return edits
}
gomod, err := os.ReadFile(filepath.Join(a.root, "go.mod"))
if err != nil {
return edits // 不是 Go 模块,没得同步
}
mod := modulePath(gomod)
if mod == "" {
return edits
}
info, err := os.Stat(old)
if err != nil {
return edits
}
if info.IsDir() {
oldImp := importPathFor(a.root, mod, old)
newImp := importPathFor(a.root, mod, target)
if oldImp == "" || newImp == "" || oldImp == newImp {
return edits
}
for _, p := range goSourceFiles(a.root) {
src, err := os.ReadFile(p)
if err != nil {
continue
}
out, n, err := rewriteGoImports(src, oldImp, newImp)
if err != nil || n == 0 {
continue
}
np, _ := remapPath(p, old, target)
edits[np] = out
}
return edits
}
// 单文件跨目录移动:文件进了别的包,package 声明要跟着改,
// 但调用方的 import 路径没变(Go import 的是包,不是文件)。
if !strings.HasSuffix(old, ".go") || filepath.Dir(old) == filepath.Dir(target) {
return edits
}
name := targetPackageName(filepath.Dir(target))
if name == "" {
return edits
}
src, err := os.ReadFile(old)
if err != nil {
return edits
}
out, changed, err := rewritePackageDecl(src, name)
if err == nil && changed {
edits[target] = out
}
return edits
}
// applyGoMoveEdits 落盘改写。任一文件写失败就整体恢复,让调用方回滚 rename。
// 缓冲区同步单独放在 syncGoMoveBuffers:只有全部落盘成功之后才碰编辑器状态。
func (a *App) applyGoMoveEdits(edits map[string][]byte) error {
if len(edits) == 0 {
return nil
}
type backup struct {
path string
data []byte
}
var backs []backup
rollback := func() {
for _, b := range backs {
_ = os.WriteFile(b.path, b.data, 0o644)
}
}
// 排序让写盘顺序稳定,出错时的提示也好复现。
paths := make([]string, 0, len(edits))
for p := range edits {
paths = append(paths, p)
}
sort.Strings(paths)
for _, p := range paths {
orig, err := os.ReadFile(p)
if err != nil {
rollback()
return err
}
backs = append(backs, backup{p, orig})
if err := os.WriteFile(p, edits[p], 0o644); err != nil {
rollback()
return err
}
}
return nil
}
// syncGoMoveBuffers 把改写同步到已打开、且用户没动过的文档。
// 有未保存改动的文档跳过:宁可让用户手动重载,也不能覆盖他的东西。
func (a *App) syncGoMoveBuffers(edits map[string][]byte) {
for p, content := range edits {
for _, d := range a.docs {
if d.path != p || d.buf.Modified() {
continue
}
// Reset 把新文本当成「已保存」,不制造假的未保存标记。
d.buf.Reset(string(content))
d.notifySaved()
a.lspSync(d)
}
}
}
+136
View File
@@ -0,0 +1,136 @@
package app
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// writeGoModule 造一个只依赖自己和标准库的小模块,不联网就能 build。
func writeGoModule(t *testing.T, files map[string]string) string {
t.Helper()
root := t.TempDir()
if _, ok := files["go.mod"]; !ok {
files["go.mod"] = "module example.com/p\n\ngo 1.21\n"
}
for rel, text := range files {
p := filepath.Join(root, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(text), 0o644); err != nil {
t.Fatal(err)
}
}
return root
}
// TestMovePackageRewritesImportsAndBuilds 是 T1 的完成标准:
// 移动一个被多处引用的包之后,不改一行代码,go build 直接过。
func TestMovePackageRewritesImportsAndBuilds(t *testing.T) {
root := writeGoModule(t, map[string]string{
"greeter/greeter.go": "package greeter\n\nfunc Hello() string { return \"hi\" }\n",
"greeter/sub/sub.go": "package sub\n\nconst N = 1\n",
"main.go": "package main\n\nimport (\n" +
"\t\"example.com/p/greeter\"\n" +
"\t\"example.com/p/greeter/sub\"\n" +
"\t\"fmt\"\n" +
")\n\n" +
"// 注释里也写了 \"example.com/p/greeter\",别动\n" +
"func main() { fmt.Println(greeter.Hello(), sub.N) }\n",
})
old := filepath.Join(root, "greeter")
target := filepath.Join(root, "internal", "greeter")
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
t.Fatal(err)
}
a := &App{root: root}
edits := a.planGoMoveEdits(old, target)
// 只有 main.go 引用了这个包;包内两个文件没有 import 自己。
if len(edits) != 1 {
t.Fatalf("应有 1 个文件需要改,实际 %d:%v", len(edits), edits)
}
mainPath := filepath.Join(root, "main.go")
got, ok := edits[mainPath]
if !ok {
t.Fatalf("改动没落在 main.go 上:%v", edits)
}
for _, want := range []string{`"example.com/p/internal/greeter"`, `"example.com/p/internal/greeter/sub"`} {
if !strings.Contains(string(got), want) {
t.Fatalf("改写后缺 %s:\n%s", want, got)
}
}
if !strings.Contains(string(got), `注释里也写了 "example.com/p/greeter"`) {
t.Fatal("中文注释里的同名路径被误改")
}
if err := os.Rename(old, target); err != nil {
t.Fatal(err)
}
if err := a.applyGoMoveEdits(edits); err != nil {
t.Fatal(err)
}
cmd := exec.Command("go", "build", "./...")
cmd.Dir = root
cmd.Env = append(os.Environ(), "GOPROXY=off", "GOFLAGS=-mod=mod")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("移动后 go build 失败:%v\n%s", err, out)
}
}
// TestPlanGoMoveEditsSingleFile 单文件跨目录移动要跟目标目录的包名一致。
func TestPlanGoMoveEditsSingleFile(t *testing.T) {
root := writeGoModule(t, map[string]string{
"util/a.go": "package util\n\nfunc A() {}\n",
"other/b.go": "package other\n\nfunc B() {}\n",
})
old := filepath.Join(root, "util", "a.go")
target := filepath.Join(root, "other", "a.go")
a := &App{root: root}
edits := a.planGoMoveEdits(old, target)
out, ok := edits[target]
if !ok {
t.Fatalf("应改写移动到新位置的文件:%v", edits)
}
name, err := readPackageDecl(out)
if err != nil || name != "other" {
t.Fatalf("包名没跟目标目录对齐:%q, err=%v\n%s", name, err, out)
}
// 同目录内改名不该动 package 声明。
edits = a.planGoMoveEdits(old, filepath.Join(root, "util", "c.go"))
if len(edits) != 0 {
t.Fatalf("同目录改名不该改内容:%v", edits)
}
}
// TestApplyGoMoveEditsRollback 中途写失败时,已经写过的文件要恢复原样。
func TestApplyGoMoveEditsRollback(t *testing.T) {
root := t.TempDir()
good := filepath.Join(root, "good.go")
missing := filepath.Join(root, "nope", "missing.go")
orig := []byte("package main\n")
if err := os.WriteFile(good, orig, 0o644); err != nil {
t.Fatal(err)
}
a := &App{root: root}
edits := map[string][]byte{
good: []byte("package changed\n"),
missing: []byte("package x\n"),
}
if err := a.applyGoMoveEdits(edits); err == nil {
t.Fatal("目标文件不存在时应该报错")
}
got, err := os.ReadFile(good)
if err != nil {
t.Fatal(err)
}
if string(got) != string(orig) {
t.Fatalf("回滚后内容不对:%q", got)
}
}
+145
View File
@@ -0,0 +1,145 @@
package app
import (
"go/parser"
"go/token"
"strconv"
"strings"
"testing"
)
func importsOf(t *testing.T, src []byte) []string {
t.Helper()
f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.ImportsOnly)
if err != nil {
t.Fatalf("改写后源码解析失败:%v\n%s", err, src)
}
var out []string
for _, s := range f.Imports {
v, err := strconv.Unquote(s.Path.Value)
if err != nil {
t.Fatal(err)
}
out = append(out, v)
}
return out
}
func TestModulePath(t *testing.T) {
cases := []struct {
in, want string
}{
{"module example.com/proj\n\ngo 1.21\n", "example.com/proj"},
{"// 注释\nmodule `example.com/p`\ngo 1.21\n", "example.com/p"},
{"module \"example.com/q\"\n", "example.com/q"},
{"modulefoo bar\n", ""},
{"go 1.21\n", ""},
}
for _, c := range cases {
if got := modulePath([]byte(c.in)); got != c.want {
t.Errorf("modulePath(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestImportPathFor(t *testing.T) {
root := "D:/proj"
mod := "example.com/p"
if got := importPathFor(root, mod, "D:/proj/greeter"); got != "example.com/p/greeter" {
t.Fatalf("子目录: %q", got)
}
if got := importPathFor(root, mod, "D:/proj"); got != "example.com/p" {
t.Fatalf("根目录: %q", got)
}
if got := importPathFor(root, mod, "D:/elsewhere"); got != "" {
t.Fatalf("模块外应为空: %q", got)
}
if got := importPathFor(root, "", "D:/proj/g"); got != "" {
t.Fatalf("无 module 应为空: %q", got)
}
}
// TestRewriteGoImports 精确匹配、子包前缀、不误伤邻居与中文注释里的同名路径。
func TestRewriteGoImports(t *testing.T) {
src := []byte("package main\n\nimport (\n" +
"\t\"example.com/p/greeter\"\n" +
"\t\"example.com/p/greeter/sub\"\n" +
"\t\"example.com/p/greeter2\"\n" +
"\t`example.com/p/greeter`\n" +
"\t\"fmt\"\n" +
")\n\n// 中文注释里也提到 \"example.com/p/greeter\",这里不该动\n" +
"var _ = fmt.Println\n")
out, n, err := rewriteGoImports(src, "example.com/p/greeter", "example.com/p/internal/greeter")
if err != nil {
t.Fatal(err)
}
if n != 3 {
t.Fatalf("应改 3 处 import,实际 %d", n)
}
want := []string{
"example.com/p/internal/greeter",
"example.com/p/internal/greeter/sub",
"example.com/p/greeter2",
"example.com/p/internal/greeter",
"fmt",
}
got := importsOf(t, out)
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Fatalf("import 不对\n got: %v\nwant: %v", got, want)
}
if !strings.Contains(string(out), `中文注释里也提到 "example.com/p/greeter"`) {
t.Fatal("中文注释里的同名路径被误改了")
}
// 原串不能被就地修改。
if !strings.Contains(string(src), "\t\"example.com/p/greeter\"\n") {
t.Fatal("原内容被就地改写了")
}
}
func TestRewriteGoImportsNoopAndError(t *testing.T) {
src := []byte("package main\n\nimport \"example.com/p/other\"\n")
out, n, err := rewriteGoImports(src, "example.com/p/greeter", "example.com/p/g")
if err != nil || n != 0 || string(out) != string(src) {
t.Fatalf("无关文件不该改:n=%d err=%v", n, err)
}
if _, _, err := rewriteGoImports(src, "a", "b"); err != nil {
t.Fatal(err)
}
if _, _, err := rewriteGoImports([]byte("这不是 Go 源码"), "a", "b"); err == nil {
t.Fatal("语法错误应该报错,交给调用方降级")
}
}
func TestValidIdent(t *testing.T) {
for _, s := range []string{"greeter", "_x", "包", "a1"} {
if !validIdent(s) {
t.Errorf("%q 该是合法包名", s)
}
}
for _, s := range []string{"", "1a", "go-utils", "func", "a b"} {
if validIdent(s) {
t.Errorf("%q 不该是合法包名", s)
}
}
}
func TestRewritePackageDecl(t *testing.T) {
src := []byte("// 头注释\npackage old\n\nfunc F() {}\n")
out, changed, err := rewritePackageDecl(src, "hello")
if err != nil || !changed {
t.Fatalf("应该改:changed=%v err=%v", changed, err)
}
if !strings.Contains(string(out), "\npackage hello\n") {
t.Fatalf("包名没换:%s", out)
}
if n, err := readPackageDecl(out); err != nil || n != "hello" {
t.Fatalf("读回包名 = %q, err=%v", n, err)
}
// 非法名字、名字本来就一样:都不动。
if _, ch, _ := rewritePackageDecl(src, "go-utils"); ch {
t.Fatal("非法包名不该改")
}
if _, ch, _ := rewritePackageDecl(src, "old"); ch {
t.Fatal("同名不该改")
}
}
+47 -9
View File
@@ -69,6 +69,7 @@ func (a *App) RunProgram() {
a.writeDoc(d) a.writeDoc(d)
} }
cfg := a.activeCfg()
pkg, label := ".", "go run ." pkg, label := ".", "go run ."
if d := a.doc(); d != nil { if d := a.doc(); d != nil {
if dir, ok := mainPkgDir(d); ok { if dir, ok := mainPkgDir(d); ok {
@@ -83,7 +84,27 @@ func (a *App) RunProgram() {
} }
} }
} }
a.startTask(label, "go", "run", pkg) // 程序参数必须排在包名之后:`go run ./pkg a b` 里 a b 才是传给程序的,
// 写在 pkg 前面会被 go 当成自己的参数。
progArgs := parseArgs(cfg.Args)
args := append([]string{"run", pkg}, progArgs...)
if len(progArgs) > 0 {
label += " " + strings.Join(progArgs, " ")
}
a.startTaskAt(label, a.cfgWorkDir(cfg), envFromLines(cfg.Env), "go", args...)
}
// cfgWorkDir 解析运行配置里的工作目录:空表示工作区根,
// 相对路径按工作区根算(与 Program 的语义一致)。
func (a *App) cfgWorkDir(cfg runConfig) string {
w := strings.TrimSpace(cfg.WorkDir)
if w == "" {
return a.root
}
if filepath.IsAbs(w) {
return w
}
return filepath.Join(a.root, w)
} }
// mainPkgDir 判断文档是不是 main 包里能直接跑的文件,返回它所在的目录。 // mainPkgDir 判断文档是不是 main 包里能直接跑的文件,返回它所在的目录。
@@ -112,7 +133,8 @@ func mainPkgDir(d *Doc) (string, bool) {
// RunTests 运行工作区的所有测试。 // RunTests 运行工作区的所有测试。
func (a *App) RunTests() { func (a *App) RunTests() {
a.startTask("go test ./...", "go", "test", "./...") args := a.withTestFlags([]string{"test", "./..."})
a.startTask(a.testCommandLabel("go test ./..."), "go", args...)
} }
// StopTask 结束正在运行的命令。 // StopTask 结束正在运行的命令。
@@ -144,9 +166,20 @@ func (a *App) TogglePanel() {
// startTask 在后台启动命令,输出进入面板。 // startTask 在后台启动命令,输出进入面板。
func (a *App) startTask(label, name string, args ...string) { func (a *App) startTask(label, name string, args ...string) {
a.startTaskAt(label, a.root, nil, name, args...)
}
// startTaskAt 在指定目录与环境变量下启动命令。
//
// dir 为空时回落到工作区根;env 为增量(不整体替换),
// 否则 PATH 之类被清掉,go 命令直接找不到。
func (a *App) startTaskAt(label, dir string, env map[string]string, name string, args ...string) {
if a.root == "" { if a.root == "" {
return return
} }
if dir == "" {
dir = a.root
}
if a.running { if a.running {
a.StopTask() a.StopTask()
} }
@@ -157,7 +190,11 @@ func (a *App) startTask(label, name string, args ...string) {
} }
a.appendOut("$ " + label) a.appendOut("$ " + label)
t, err := task.Start(a.root, name, args...) envList := make([]string, 0, len(env))
for k, v := range env {
envList = append(envList, k+"="+v)
}
t, err := task.StartWith(task.Options{Dir: dir, Env: envList}, name, args...)
if err != nil { if err != nil {
a.appendOut(err.Error()) a.appendOut(err.Error())
a.running = false a.running = false
@@ -431,6 +468,9 @@ func (a *App) runView(c *ui.Context) {
a.jumpTo(loc) a.jumpTo(loc)
} }
} }
if list.RightClicked() {
a.openListPop(list, a.outputMenuEntries())
}
} }
// problemView 是「问题」页签的内容。 // problemView 是「问题」页签的内容。
@@ -469,6 +509,9 @@ func (a *App) problemView(c *ui.Context) {
p := ps[a.probSel] p := ps[a.probSel]
a.jumpTo(&SourceLoc{Path: p.Path, Line: p.Line, Col: p.Col}) a.jumpTo(&SourceLoc{Path: p.Path, Line: p.Line, Col: p.Col})
} }
if list.RightClicked() {
a.openListPop(list, a.problemMenuEntries(ps))
}
} }
// allProblems 汇总所有已打开文件的诊断。 // allProblems 汇总所有已打开文件的诊断。
@@ -511,12 +554,7 @@ func (a *App) problemRow(c *ui.Context, i int, ps []Problem) {
case editor.SeverityInfo, editor.SeverityHint: case editor.SeverityInfo, editor.SeverityHint:
color = t.TextMuted color = t.TextMuted
} }
tag := "" ui.Text(c, problemLineText(p)).FontSize(12).TextColor(color).SingleLine()
if p.Source != "" {
tag = "[" + p.Source + "] "
}
text := fmt.Sprintf("%s%s:%d %s", tag, filepath.Base(p.Path), p.Line, p.Text)
ui.Text(c, text).FontSize(12).TextColor(color).SingleLine()
} }
// outRow 画出一行输出。 // outRow 画出一行输出。
+123 -23
View File
@@ -4,7 +4,10 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"sync"
"sync/atomic"
"time" "time"
"unicode/utf8" "unicode/utf8"
@@ -55,6 +58,8 @@ type paletteState struct {
items []paletteItem items []paletteItem
gen int gen int
waiting bool waiting bool
// searchHint 是这轮全局搜索跳过了哪些文件,底部一行小字提示。
searchHint string
// 全局搜索的替换:replaceTo 是「替换为」,replacing 表示正在显示 // 全局搜索的替换:replaceTo 是「替换为」,replacing 表示正在显示
// 预览(此时候选列表被替换成文件清单 + 确认按钮),planning 表示 // 预览(此时候选列表被替换成文件清单 + 确认按钮),planning 表示
@@ -157,22 +162,25 @@ func (a *App) refreshPalette() {
if strings.TrimSpace(a.pal.query) == "" { if strings.TrimSpace(a.pal.query) == "" {
a.pal.items = nil a.pal.items = nil
a.pal.waiting = false a.pal.waiting = false
a.pal.searchHint = ""
return return
} }
a.pal.gen++ a.pal.gen++
gen := a.pal.gen gen := a.pal.gen
a.pal.waiting = true a.pal.waiting = true
a.pal.searchHint = "" // 新查询开始,别挂着上一轮的跳过提示
q := a.pal.query q := a.pal.query
opt := searchOpts{useRegex: a.pal.useRegex, matchCase: a.pal.matchCase, wholeWord: a.pal.wholeWord} opt := searchOpts{useRegex: a.pal.useRegex, matchCase: a.pal.matchCase, wholeWord: a.pal.wholeWord}
go func() { go func() {
// 轻微去抖:连续输入时只跑最后一次。 // 轻微去抖:连续输入时只跑最后一次。
time.Sleep(220 * time.Millisecond) time.Sleep(220 * time.Millisecond)
items := a.searchInWorkspace(q, paletteLimit, opt) items, stats := a.searchInWorkspace(q, paletteLimit, opt)
a.win.Update(func() { a.win.Update(func() {
if !a.pal.open || gen != a.pal.gen { if !a.pal.open || gen != a.pal.gen {
return return
} }
a.pal.items = items a.pal.items = items
a.pal.searchHint = stats.hint()
a.pal.waiting = false a.pal.waiting = false
}) })
}() }()
@@ -209,24 +217,30 @@ func (a *App) workspaceFiles() []string {
if files, ready := a.indexSnapshot(); ready { if files, ready := a.indexSnapshot(); ready {
return files return files
} }
rules := loadIgnoreRules(root)
var files []string var files []string
_ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil { if err != nil {
return nil return nil
} }
rel, relErr := filepath.Rel(root, p)
relSlash := ""
if relErr == nil {
relSlash = filepath.ToSlash(rel)
}
if d.IsDir() { if d.IsDir() {
if p != root && skipDir(d.Name()) { if p != root && (isBuiltinSkipDir(d.Name()) || rules.match(relSlash, true)) {
return filepath.SkipDir return filepath.SkipDir
} }
return nil return nil
} }
if skipFile(d.Name()) { if skipFile(d.Name()) || rules.match(relSlash, false) {
return nil return nil
} }
if rel, err := filepath.Rel(root, p); err == nil { if relErr == nil {
files = append(files, filepath.ToSlash(rel)) files = append(files, relSlash)
} }
if len(files) > 20000 { if len(files) > indexFileCap {
return filepath.SkipAll return filepath.SkipAll
} }
return nil return nil
@@ -234,51 +248,128 @@ func (a *App) workspaceFiles() []string {
return files return files
} }
// searchInWorkspace 在工作区里按行搜索,返回命中的行。 // searchStats 是这一轮搜索里被静默跳过的文件数。
func (a *App) searchInWorkspace(query string, limit int, o searchOpts) []paletteItem { // 以前超过 512KB 或读不出来的文件直接 continue,用户根本不知道自己
// 漏搜了东西;现在交给调用方显示成面板里的一行提示。
type searchStats struct {
tooLarge int
unreadable int
}
func (s searchStats) hint() string {
var parts []string
if s.tooLarge > 0 {
parts = append(parts, fmt.Sprintf("%d 个文件超过 512 KB", s.tooLarge))
}
if s.unreadable > 0 {
parts = append(parts, fmt.Sprintf("%d 个文件读不出或非 UTF-8", s.unreadable))
}
if len(parts) == 0 {
return ""
}
return "全局搜索已跳过:" + strings.Join(parts, "、")
}
// searchInWorkspace 在工作区里按行搜索,返回命中的行与跳过统计。
//
// 读盘是 I/O 密集,按 runtime.NumCPU() 并发(上限 8);每个 worker 只写
// 自己那份结果槽,最后按文件顺序合并,所以结果顺序和串行版完全一致。
// 命中上限后停止派发新文件,避免为了 200 条结果把上万个文件全读一遍。
func (a *App) searchInWorkspace(query string, limit int, o searchOpts) ([]paletteItem, searchStats) {
root := a.root root := a.root
if root == "" || query == "" { if root == "" || query == "" {
return nil return nil, searchStats{}
} }
files := a.workspaceFiles() files := a.workspaceFiles()
match, err := buildMatcher(query, o) match, err := buildMatcher(query, o)
if err != nil { if err != nil {
return nil return nil, searchStats{}
} }
var out []paletteItem if len(files) == 0 {
for _, rel := range files { return nil, searchStats{}
}
type fileHits struct {
items []paletteItem
tooLarge, unreadable int
}
per := make([]fileHits, len(files))
workers := runtime.NumCPU()
if workers > 8 {
workers = 8
}
if workers > len(files) {
workers = len(files)
}
var total atomic.Int64
var stop atomic.Bool
jobs := make(chan int, workers)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
if stop.Load() {
continue
}
rel := files[i]
abs := filepath.Join(root, filepath.FromSlash(rel)) abs := filepath.Join(root, filepath.FromSlash(rel))
info, err := os.Stat(abs) info, err := os.Stat(abs)
if err != nil || info.Size() > 512*1024 { if err != nil || info.Size() > 512*1024 {
per[i].tooLarge = 1
continue continue
} }
data, err := os.ReadFile(abs) data, err := os.ReadFile(abs)
if err != nil || !utf8.Valid(data) { if err != nil || !utf8.Valid(data) {
per[i].unreadable = 1
continue continue
} }
for i, line := range strings.Split(string(data), "\n") { var hits []paletteItem
for ln, line := range strings.Split(string(data), "\n") {
if !match(line) { if !match(line) {
continue continue
} }
trimmed := strings.TrimSpace(line) // 按字符截断,别切坏中文(见 strutil.go 的注释)。
if len(trimmed) > 160 { hits = append(hits, paletteItem{
trimmed = trimmed[:160] + "…"
}
out = append(out, paletteItem{
Kind: itemLine, Kind: itemLine,
Path: abs, Path: abs,
Line: i + 1, Line: ln + 1,
Label: rel, Label: rel,
Hint: "", Text: trimTo(strings.TrimSpace(line), 160),
Text: trimmed,
}) })
}
per[i].items = hits
if len(hits) > 0 && total.Add(int64(len(hits))) >= int64(limit) {
stop.Store(true)
}
}
}()
}
for i := range files {
if stop.Load() {
break
}
jobs <- i
}
close(jobs)
wg.Wait()
var out []paletteItem
var stats searchStats
for i := range per {
stats.tooLarge += per[i].tooLarge
stats.unreadable += per[i].unreadable
for _, it := range per[i].items {
out = append(out, it)
if len(out) >= limit { if len(out) >= limit {
return out return out, stats
} }
} }
} }
return out return out, stats
} }
// moveSel 上下移动选中项。 // moveSel 上下移动选中项。
@@ -419,6 +510,15 @@ func (a *App) paletteView(c *ui.Context) {
ui.Text(c, "Enter 打开").FontSize(10).TextColor(t.TextMuted) ui.Text(c, "Enter 打开").FontSize(10).TextColor(t.TextMuted)
ui.Text(c, "Esc 关闭").FontSize(10).TextColor(t.TextMuted) ui.Text(c, "Esc 关闭").FontSize(10).TextColor(t.TextMuted)
ui.Box(c).Grow(1) ui.Box(c).Grow(1)
// 索引被上限截断时说一声:否则「搜不到」会被当成「不存在」。
if !a.pal.search && a.indexTruncated() {
ui.Textf(c, "索引已截断至 %d 个文件", indexFileCap).
FontSize(10).TextColor(t.Warning)
}
// 被静默跳过的文件要让用户知道,否则「搜不到」会被当成「不存在」。
if a.pal.search && a.pal.searchHint != "" {
ui.Text(c, a.pal.searchHint).FontSize(10).TextColor(t.Warning)
}
if n := len(a.pal.items); n > 0 { if n := len(a.pal.items); n > 0 {
ui.Textf(c, "%d 项", n).FontSize(10).TextColor(t.TextMuted) ui.Textf(c, "%d 项", n).FontSize(10).TextColor(t.TextMuted)
} }
+6 -2
View File
@@ -71,10 +71,13 @@ func TestSearchInWorkspace(t *testing.T) {
} }
a := &App{root: root} a := &App{root: root}
got := a.searchInWorkspace("needle", 10, searchOpts{}) got, stats := a.searchInWorkspace("needle", 10, searchOpts{})
if len(got) != 2 { if len(got) != 2 {
t.Fatalf("应命中 2 行,实际 %d: %+v", len(got), got) t.Fatalf("应命中 2 行,实际 %d: %+v", len(got), got)
} }
if stats.hint() != "" {
t.Fatalf("没有跳过文件时不该有提示:%q", stats.hint())
}
seen := map[string]int{} seen := map[string]int{}
for _, it := range got { for _, it := range got {
seen[it.Label] = it.Line seen[it.Label] = it.Line
@@ -96,7 +99,8 @@ func TestSearchSkipsSkippedDirs(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
a := &App{root: root} a := &App{root: root}
if got := a.searchInWorkspace("needle", 10, searchOpts{}); len(got) != 0 { got, _ := a.searchInWorkspace("needle", 10, searchOpts{})
if len(got) != 0 {
t.Fatalf("应当跳过 node_modules,实际命中 %d", len(got)) t.Fatalf("应当跳过 node_modules,实际命中 %d", len(got))
} }
} }
+91
View File
@@ -0,0 +1,91 @@
package app
import (
"fmt"
"path/filepath"
"strings"
"github.com/egoist/mygo/ui"
)
// 输出面板与问题面板的右键菜单。
//
// 终端不用管:plugins/terminal 的 View 自带 ContextMenu(默认
// RightClickContextMenu),从 mygo v0.7.4 起就有,只是原生菜单在
// automation 插座里看不到——别再把「openPop 没有入口」当成「没有菜单」。
// 这两个面板是我们自己用 ui.List 画的,框架不会给菜单。
// outLinesText 把输出行拼成可复制的纯文本。
func outLinesText(lines []OutLine) string {
if len(lines) == 0 {
return ""
}
out := make([]string, 0, len(lines))
for _, l := range lines {
out = append(out, l.Text)
}
return strings.Join(out, "\n")
}
// problemLineText 是一条问题的纯文本,和 problemRow 的显示保持一致。
// 抽出来是为了复制和渲染不各写一份、不会慢慢漂移。
func problemLineText(p Problem) string {
tag := ""
if p.Source != "" {
tag = "[" + p.Source + "] "
}
return fmt.Sprintf("%s%s:%d %s", tag, filepath.Base(p.Path), p.Line, p.Text)
}
func problemLinesText(ps []Problem) string {
if len(ps) == 0 {
return ""
}
out := make([]string, 0, len(ps))
for _, p := range ps {
out = append(out, problemLineText(p))
}
return strings.Join(out, "\n")
}
// outputMenuEntries 是「运行」面板的右键项。
func (a *App) outputMenuEntries() []menuEntry {
sel, all := "", outLinesText(a.out)
if a.outSel >= 0 && a.outSel < len(a.out) {
sel = a.out[a.outSel].Text
}
return []menuEntry{
{label: "复制选中行", disabled: sel == "", action: func() { a.copyToClipboard(sel) }},
{label: "复制全部输出", disabled: all == "", action: func() { a.copyToClipboard(all) }},
{divider: true},
{label: "清空输出", disabled: len(a.out) == 0, action: a.ClearOutput},
}
}
// problemMenuEntries 是「问题」面板的右键项。
// 问题来自诊断,没有「清空」这回事,所以只给复制。
func (a *App) problemMenuEntries(ps []Problem) []menuEntry {
sel, all := "", problemLinesText(ps)
if a.probSel >= 0 && a.probSel < len(ps) {
sel = problemLineText(ps[a.probSel])
}
return []menuEntry{
{label: "复制选中行", disabled: sel == "", action: func() { a.copyToClipboard(sel) }},
{label: "复制全部问题", disabled: all == "", action: func() { a.copyToClipboard(all) }},
}
}
// openListPop 在列表的右键位置弹出菜单。
//
// List 的 Bounds 是一整块,直接当锚点会把菜单顶到窗口外再折回来,位置
// 离指针很远。这里用指针在列表内的坐标构造一个零宽矩形,让菜单贴着鼠标。
func (a *App) openListPop(list ui.Element, entries []menuEntry) {
b := list.Bounds()
x, y, over := list.PointerPosition()
if over {
b.X += x
b.Y += y
b.W, b.H = 0, 0
}
a.openPopAt(b, entries)
}
+99
View File
@@ -0,0 +1,99 @@
package app
import (
"strings"
"testing"
)
// TestOutLinesText 复制全部输出要保持原顺序、一行一条。
func TestOutLinesText(t *testing.T) {
if got := outLinesText(nil); got != "" {
t.Fatalf("空列表应得到空串,实际 %q", got)
}
got := outLinesText([]OutLine{
{Text: "go build ./..."},
{Text: ""},
{Text: "FAIL internal/app"},
})
want := "go build ./...\n\nFAIL internal/app"
if got != want {
t.Fatalf("拼接不对\n got: %q\nwant: %q", got, want)
}
}
// TestProblemLinesText 复制出来的文字要和 problemRow 显示的完全一致,
// 包括 [来源] 前缀与只显示文件名。
func TestProblemLinesText(t *testing.T) {
ps := []Problem{
{Path: "D:/proj/internal/app/a.go", Line: 12, Text: "undefined: x"},
{Path: "D:/proj/b.go", Line: 3, Text: "unused import", Source: "go vet"},
}
got := problemLinesText(ps)
want := "a.go:12 undefined: x\n[go vet] b.go:3 unused import"
if got != want {
t.Fatalf("拼接不对\n got: %q\nwant: %q", got, want)
}
if problemLinesText(nil) != "" {
t.Fatal("空列表应得到空串")
}
}
// TestOutputMenuEntries 空输出时三项都该灰掉;有内容时复制动作要真的写剪贴板。
func TestOutputMenuEntries(t *testing.T) {
empty := (&App{outSel: -1}).outputMenuEntries()
for _, e := range empty {
if e.divider {
continue
}
if !e.disabled {
t.Fatalf("空输出时 %q 不该可用", e.label)
}
}
a := &App{
out: []OutLine{{Text: "first"}, {Text: "second"}},
outSel: 1,
}
entries := a.outputMenuEntries()
if entries[0].disabled || entries[1].disabled || entries[3].disabled {
t.Fatal("有输出时复制与清空都该可用")
}
var copied string
old := clipWrite
clipWrite = func(s string) error { copied = s; return nil }
defer func() { clipWrite = old }()
entries[0].action()
if copied != "second" {
t.Fatalf("复制选中行得到 %q,想要 second", copied)
}
entries[1].action()
if !strings.Contains(copied, "first") || !strings.Contains(copied, "second") {
t.Fatalf("复制全部输出缺内容:%q", copied)
}
}
// TestProblemMenuEntries 越界的选中下标不能让菜单项变成「可用但复制到空」。
func TestProblemMenuEntries(t *testing.T) {
ps := []Problem{{Path: "/p/a.go", Line: 7, Text: "oops"}}
empty := (&App{probSel: 9}).problemMenuEntries(ps)
if !empty[0].disabled {
t.Fatal("选中下标越界时「复制选中行」不该可用")
}
if empty[1].disabled {
t.Fatal("有问题时「复制全部问题」该可用")
}
a := &App{probSel: 0}
var copied string
old := clipWrite
clipWrite = func(s string) error { copied = s; return nil }
defer func() { clipWrite = old }()
entries := a.problemMenuEntries(ps)
entries[0].action()
if copied != "a.go:7 oops" {
t.Fatalf("复制选中行得到 %q", copied)
}
}
+12 -1
View File
@@ -70,7 +70,18 @@ func (a *App) openPop(anchor ui.Element, entries []menuEntry) {
if len(entries) == 0 || a.win == nil { if len(entries) == 0 || a.win == nil {
return return
} }
a.popRect = anchor.Bounds() a.openPopAt(anchor.Bounds(), entries)
}
// openPopAt 在给定矩形下沿弹出菜单。
//
// 用在整块列表上:列表的 Bounds 是一大片,直接拿它当锚点会把菜单顶到
// 屏幕外面。右键时传一个零宽的小矩形(指针位置)就能贴着鼠标弹。
func (a *App) openPopAt(r ui.Rect, entries []menuEntry) {
if len(entries) == 0 || a.win == nil {
return
}
a.popRect = r
a.popEntries = entries a.popEntries = entries
a.popOpen = true a.popOpen = true
a.popJustOpened = true a.popJustOpened = true
+1 -4
View File
@@ -82,10 +82,7 @@ func linePreview(path string, line int) string {
return "" return ""
} }
s := strings.TrimSpace(lines[line-1]) s := strings.TrimSpace(lines[line-1])
if len(s) > 140 { return trimTo(s, 140)
s = s[:140] + "…"
}
return s
} }
// RenameSymbol 打开重命名弹窗,光标处的词作为默认值。 // RenameSymbol 打开重命名弹窗,光标处的词作为默认值。
+21 -5
View File
@@ -101,24 +101,40 @@ func (a *App) confirmRenameEntry() {
a.win.Update(func() {}) a.win.Update(func() {})
return return
} }
// Go 包的同步要读旧路径上的文件,必须在 rename 之前算好。
edits := a.planGoMoveEdits(old, target)
var renameErr error
if strings.EqualFold(target, old) { if strings.EqualFold(target, old) {
// 只改大小写:Windows 上需要先改名到临时名字再改回来。 // 只改大小写:Windows 上需要先改名到临时名字再改回来。
tmp := old + ".renaming" tmp := old + ".renaming"
if err := os.Rename(old, tmp); err == nil { if err := os.Rename(old, tmp); err != nil {
_ = os.Rename(tmp, target) renameErr = err
} else if err := os.Rename(tmp, target); err != nil {
renameErr = err
_ = os.Rename(tmp, old)
} }
} else { } else {
if _, err := os.Stat(target); err == nil { if _, err := os.Stat(target); err == nil {
a.alert("重命名失败", "目标已存在:"+filepath.Base(target)) a.alert("重命名失败", "目标已存在:"+filepath.Base(target))
return return
} }
if err := os.Rename(old, target); err != nil { renameErr = os.Rename(old, target)
a.alert("重命名失败", err.Error()) }
if renameErr != nil {
a.alert("重命名失败", renameErr.Error())
return return
} }
if err := a.applyGoMoveEdits(edits); err != nil {
// 内容同步失败就把移动也退回去,别留下一个编译不过的仓库。
_ = os.Rename(target, old)
a.alert("移动失败", "已回滚文件移动;同步 import 时出错:"+err.Error())
return
} }
a.afterRename(old, target) a.afterRename(old, target) // 先把内存里的路径搬到新位置
a.syncGoMoveBuffers(edits)
a.win.Update(func() {}) a.win.Update(func() {})
} }
+15
View File
@@ -15,6 +15,12 @@ type runConfig struct {
Program string `json:"program"` Program string `json:"program"`
Args string `json:"args"` Args string `json:"args"`
StopOnEntry bool `json:"stopOnEntry"` StopOnEntry bool `json:"stopOnEntry"`
// WorkDir 是被运行/被调试程序的工作目录,空表示工作区根。
// 相对路径按工作区根解析(与 Program 的语义一致)。
WorkDir string `json:"workDir,omitempty"`
// Env 是「每行一个 KEY=VALUE」的额外环境变量;空行与 # 注释会被跳过。
// 存在字符串里而不是 map:配置文件要能保留用户写的注释与顺序。
Env string `json:"env,omitempty"`
} }
// configsFile 是一个工作区里的全部运行配置。 // configsFile 是一个工作区里的全部运行配置。
@@ -162,10 +168,19 @@ func (a *App) runConfigDialog(c *ui.Context) {
ui.Text(c, "参数").FontSize(11).TextColor(t.TextMuted).Width(48) ui.Text(c, "参数").FontSize(11).TextColor(t.TextMuted).Width(48)
ui.TextInput(c, &a.cfgDlg.draft.Args).FillWidth().FontSize(13) ui.TextInput(c, &a.cfgDlg.draft.Args).FillWidth().FontSize(13)
}) })
ui.Text(c, "参数支持双引号:-tags \"integration e2e\" 算一个参数").
FontSize(10).TextColor(t.TextMuted)
ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() {
ui.Text(c, "工作目录").FontSize(11).TextColor(t.TextMuted).Width(48)
ui.TextInput(c, &a.cfgDlg.draft.WorkDir).FillWidth().FontSize(13)
})
ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() {
ui.Switch(c, &a.cfgDlg.draft.StopOnEntry) ui.Switch(c, &a.cfgDlg.draft.StopOnEntry)
ui.Text(c, "启动即停(调试时停在第一行)").FontSize(11).TextColor(t.TextMuted) ui.Text(c, "启动即停(调试时停在第一行)").FontSize(11).TextColor(t.TextMuted)
}) })
ui.Text(c, "环境变量(每行一个 KEY=VALUE,可用 # 注释)").
FontSize(11).TextColor(t.TextMuted)
ui.TextArea(c, &a.cfgDlg.draft.Env).FillWidth().Height(84).FontSize(12)
ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() {
if ui.Button(c, "新建").Clicked() { if ui.Button(c, "新建").Clicked() {
+74
View File
@@ -0,0 +1,74 @@
package app
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// TestSearchConcurrentOrderStable 并发读盘后结果仍按文件序排列,
// 不能因为哪个 worker 先跑完就打乱顺序。
func TestSearchConcurrentOrderStable(t *testing.T) {
root := t.TempDir()
const n = 24
for i := 0; i < n; i++ {
name := fmt.Sprintf("f%02d.txt", i)
body := fmt.Sprintf("line one\nneedle in %s\nlast line\n", name)
if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
a := &App{root: root}
got, stats := a.searchInWorkspace("needle", 200, searchOpts{})
if len(got) != n {
t.Fatalf("应命中 %d 行,实际 %d", n, len(got))
}
if stats.hint() != "" {
t.Fatalf("没有跳过文件时不该有提示:%q", stats.hint())
}
for i, it := range got {
want := fmt.Sprintf("f%02d.txt", i)
if it.Label != want {
t.Fatalf("第 %d 项是 %q,想要 %q(顺序乱了)", i, it.Label, want)
}
if it.Line != 2 {
t.Fatalf("%s 命中行 = %d,想要 2", it.Label, it.Line)
}
}
}
// TestSearchStatsTooLarge 超过 512KB 的文件要被数出来,并且提示可见。
func TestSearchStatsTooLarge(t *testing.T) {
root := t.TempDir()
big := strings.Repeat("x", 512*1024+1) + "\nneedle\n"
if err := os.WriteFile(filepath.Join(root, "big.txt"), []byte(big), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "small.txt"), []byte("needle\n"), 0o644); err != nil {
t.Fatal(err)
}
a := &App{root: root}
got, stats := a.searchInWorkspace("needle", 200, searchOpts{})
if len(got) != 1 || got[0].Label != "small.txt" {
t.Fatalf("只该命中 small.txt:%+v", got)
}
if stats.tooLarge != 1 {
t.Fatalf("tooLarge = %d,想要 1", stats.tooLarge)
}
hint := stats.hint()
if !strings.Contains(hint, "512 KB") || !strings.Contains(hint, "1 个文件") {
t.Fatalf("提示没说清跳过了什么:%q", hint)
}
}
func TestSearchStatsHint(t *testing.T) {
if (searchStats{}).hint() != "" {
t.Fatal("没有跳过时不该有提示")
}
h := (searchStats{tooLarge: 2, unreadable: 3}).hint()
if !strings.Contains(h, "2 个文件超过 512 KB") || !strings.Contains(h, "3 个文件读不出") {
t.Fatalf("提示缺内容:%q", h)
}
}
+17
View File
@@ -0,0 +1,17 @@
package app
// trimTo 把字符串截断到 n 个**字符**再加省略号。
//
// 必须按 rune 数而不是字节数:中文一个字 3 字节、emoji 4 字节,
// 按字节切会把多字节字符切断,渲染端只能显示成替换字符(�)。
// 曾经 palette/rename 两处用 s[:n] 直接切,中文搜索命中行会出乱码。
func trimTo(s string, n int) string {
if n <= 0 {
return ""
}
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
+88
View File
@@ -0,0 +1,88 @@
package app
import (
"os"
"path/filepath"
"strings"
"testing"
"unicode/utf8"
)
// TestTrimToASCII 纯 ASCII 按字符数截断。
func TestTrimToASCII(t *testing.T) {
if got := trimTo("abcdef", 3); got != "abc…" {
t.Fatalf("trimTo(abcdef,3) = %q", got)
}
if got := trimTo("abc", 3); got != "abc" {
t.Fatalf("恰好等长不该加省略号:%q", got)
}
if got := trimTo("ab", 3); got != "ab" {
t.Fatalf("短于上限原样返回:%q", got)
}
}
// TestTrimToChinese 中文按字数算,且不得切出半个字符。
//
// 这是本函数存在的理由:旧实现 trimmed[:160] 按字节切,160 除以 3
// 落在一个汉字的中间,结果就是乱码。
func TestTrimToChinese(t *testing.T) {
s := strings.Repeat("中", 200)
got := trimTo(s, 160)
if !utf8.ValidString(got) {
t.Fatalf("截断结果不是合法 UTF-8:%q", got)
}
if n := utf8.RuneCountInString(strings.TrimSuffix(got, "…")); n != 160 {
t.Fatalf("字符数 %d, 想要 160", n)
}
if !strings.HasSuffix(got, "…") {
t.Fatalf("长于上限应加省略号:%q", got)
}
}
// TestTrimToEmoji emoji 是 4 字节,同样不能被切开。
func TestTrimToEmoji(t *testing.T) {
s := strings.Repeat("🙂", 10)
got := trimTo(s, 5)
if !utf8.ValidString(got) {
t.Fatalf("emoji 截断结果非法:%q", got)
}
if got != strings.Repeat("🙂", 5)+"…" {
t.Fatalf("got %q", got)
}
}
// TestTrimToMixed 中英混排按字符数,不按显示宽度。
func TestTrimToMixed(t *testing.T) {
s := "abc中文def"
if got := trimTo(s, 5); got != "abc中文…" {
t.Fatalf("got %q", got)
}
}
// TestTrimToNonPositive n<=0 时返回空串(调用方不必先判长度)。
func TestTrimToNonPositive(t *testing.T) {
if got := trimTo("abc", 0); got != "" {
t.Fatalf("n=0 应为空串,得到 %q", got)
}
if got := trimTo("abc", -1); got != "" {
t.Fatalf("n<0 应为空串,得到 %q", got)
}
}
// TestLinePreviewChinese 覆盖真实调用路径:查找引用列表的行预览。
//
// 旧实现在这里按字节切 140,一个 200 字的中文行必然被切坏。
func TestLinePreviewChinese(t *testing.T) {
p := filepath.Join(t.TempDir(), "x.go")
line := strings.Repeat("中文", 100) // 200 字符 / 600 字节
if err := os.WriteFile(p, []byte(line+"\n"), 0o644); err != nil {
t.Fatal(err)
}
got := linePreview(p, 1)
if !utf8.ValidString(got) {
t.Fatalf("预览不是合法 UTF-8:%q", got)
}
if n := utf8.RuneCountInString(strings.TrimSuffix(got, "…")); n != 140 {
t.Fatalf("字符数 %d, 想要 140", n)
}
}
+61
View File
@@ -0,0 +1,61 @@
package app
import (
"path/filepath"
"strings"
)
// tabLabel 返回标签上显示的名字。
//
// 没有重名就只显示文件名;有重名时显示「能区分它的最短后缀」:
// a/main.go 与 b/main.go 显示成 a/main.go / b/main.go,
// 若还撞(internal/x/main.go 与 cmd/x/main.go)就再多带一层。
//
// 为什么不统一显示相对工作区的全路径:标签栏只有一行,全路径会把
// 后面的标签挤到看不见。只在冲突时加长,是 VS Code 的做法。
func (a *App) tabLabel(d *Doc) string {
base := filepath.Base(d.path)
same := 0
for _, o := range a.docs {
if strings.EqualFold(filepath.Base(o.path), base) {
same++
}
}
if same <= 1 {
return base
}
return a.shortestUniqueSuffix(d.path)
}
// shortestUniqueSuffix 从路径尾部往上取段,直到与其它同名文件不再冲突。
func (a *App) shortestUniqueSuffix(path string) string {
self := strings.Split(filepath.ToSlash(path), "/")
base := filepath.Base(path)
// 只和「同名」的那些比,别的标签无关。
var others [][]string
for _, o := range a.docs {
if strings.EqualFold(filepath.Base(o.path), base) && o.path != path {
others = append(others, strings.Split(filepath.ToSlash(o.path), "/"))
}
}
for depth := 2; depth <= len(self); depth++ {
cand := strings.Join(self[len(self)-depth:], "/")
uniq := true
for _, op := range others {
if len(op) < depth {
continue
}
if strings.EqualFold(strings.Join(op[len(op)-depth:], "/"), cand) {
uniq = false
break
}
}
if uniq {
return cand
}
}
// 全路径都一样(理论上不会有),原样返回。
return strings.Join(self, "/")
}
+63
View File
@@ -0,0 +1,63 @@
package app
import (
"testing"
"github.com/egoist/mygo/ui/editor"
)
func docAt(p string) *Doc { return &Doc{path: p, buf: editor.NewBuffer("")} }
// TestTabLabelUnique 没有重名就只显示文件名。
func TestTabLabelUnique(t *testing.T) {
a := &App{docs: []*Doc{docAt("/w/main.go"), docAt("/w/util.go")}}
if got := a.tabLabel(a.docs[0]); got != "main.go" {
t.Fatalf("got %q", got)
}
}
// TestTabLabelSameName 同名时带上能区分的那一层目录。
func TestTabLabelSameName(t *testing.T) {
a := &App{docs: []*Doc{docAt("/w/a/main.go"), docAt("/w/b/main.go")}}
if got := a.tabLabel(a.docs[0]); got != "a/main.go" {
t.Fatalf("第一个标签 = %q, 想要 a/main.go", got)
}
if got := a.tabLabel(a.docs[1]); got != "b/main.go" {
t.Fatalf("第二个标签 = %q, 想要 b/main.go", got)
}
}
// TestTabLabelDeeper 一层不够时继续往上取。
func TestTabLabelDeeper(t *testing.T) {
a := &App{docs: []*Doc{
docAt("/w/internal/x/main.go"),
docAt("/w/cmd/x/main.go"),
}}
got0 := a.tabLabel(a.docs[0])
got1 := a.tabLabel(a.docs[1])
if got0 == got1 {
t.Fatalf("两个标签仍重名:%q", got0)
}
if got0 != "internal/x/main.go" {
t.Fatalf("got %q", got0)
}
}
// TestTabLabelWindowsPath Windows 反斜杠路径也要正确切段。
func TestTabLabelWindowsPath(t *testing.T) {
a := &App{docs: []*Doc{
docAt(`D:\w\a\main.go`),
docAt(`D:\w\b\main.go`),
}}
if got := a.tabLabel(a.docs[0]); got != "a/main.go" {
t.Fatalf("got %q", got)
}
}
// TestTabLabelCaseInsensitive 大小写不同的同名文件也算重名(Windows 语义)。
func TestTabLabelCaseInsensitive(t *testing.T) {
a := &App{docs: []*Doc{docAt("/w/a/Main.go"), docAt("/w/b/main.go")}}
if got := a.tabLabel(a.docs[0]); got == "Main.go" {
t.Fatalf("大小写同名应加目录区分,got %q", got)
}
}
+159
View File
@@ -0,0 +1,159 @@
package app
import (
"path/filepath"
"strings"
"testing"
"github.com/egoist/mygo/ui/editor"
)
// newTabDoc 造一个只带路径与缓冲区的文档,够 tabmenu 用了。
func newTabDoc(p, content string) *Doc {
return &Doc{path: p, buf: editor.NewBuffer(content)}
}
// labels 把菜单条目压成标签列表,便于断言(分隔条记为 "---")。
func labels(es []menuEntry) []string {
out := make([]string, 0, len(es))
for _, e := range es {
if e.divider {
out = append(out, "---")
continue
}
out = append(out, e.label)
}
return out
}
// TestDocIndex 标签位置查找。
func TestDocIndex(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc("/x/a.go", "a"),
newTabDoc("/x/b.go", "b"),
newTabDoc("/x/c.go", "c"),
}}
if got := a.docIndex("/x/b.go"); got != 1 {
t.Fatalf("docIndex(b) = %d, 想要 1", got)
}
if got := a.docIndex("/x/none.go"); got != -1 {
t.Fatalf("docIndex(none) = %d, 想要 -1", got)
}
}
// TestSavedPaths 只收没有未保存改动的。
func TestSavedPaths(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc("/x/a.go", "a"),
newTabDoc("/x/b.go", "b"),
}}
a.docs[1].buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// dirty\n"})
got := a.savedPaths()
if len(got) != 1 || got[0] != "/x/a.go" {
t.Fatalf("savedPaths() = %v, 只该有 /x/a.go", got)
}
}
// TestTabEntriesMiddle 中间那个标签:左右都能关,且能关其他。
func TestTabEntriesMiddle(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc("/x/a.go", "a"),
newTabDoc("/x/b.go", "b"),
newTabDoc("/x/c.go", "c"),
}}
got := labels(a.tabEntries("/x/b.go"))
want := []string{
"关闭",
"关闭左边(1)",
"关闭右边(1)",
"---",
"关闭其他(2)",
"关闭全部(3)",
"---",
"关闭已保存的(3)",
}
if len(got) != len(want) {
t.Fatalf("条目数 %d, 想要 %d:%v", len(got), len(want), got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("第 %d 条 = %q, 想要 %q(全部:%v)", i, got[i], want[i], got)
}
}
}
// TestTabEntriesFirstLast 首尾标签的「关闭左边/右边」应当消失。
func TestTabEntriesFirstLast(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc("/x/a.go", "a"),
newTabDoc("/x/b.go", "b"),
}}
first := labels(a.tabEntries("/x/a.go"))
if len(first) == 0 || first[0] != "关闭" {
t.Fatalf("首标签菜单异常:%v", first)
}
for _, s := range first {
if strings.HasPrefix(s, "关闭左边") {
t.Fatalf("首标签不该有「关闭左边」:%v", first)
}
}
last := labels(a.tabEntries("/x/b.go"))
for _, s := range last {
if strings.HasPrefix(s, "关闭右边") {
t.Fatalf("末标签不该有「关闭右边」:%v", last)
}
}
}
// TestTabEntriesSingle 只剩一个标签时,没有「关闭其他」「关闭已保存的」。
func TestTabEntriesSingle(t *testing.T) {
a := &App{docs: []*Doc{newTabDoc("/x/a.go", "a")}}
got := labels(a.tabEntries("/x/a.go"))
want := []string{"关闭", "---", "关闭全部(1)", "---", "关闭已保存的(1)"}
if len(got) != len(want) {
t.Fatalf("条目数 %d, 想要 %d:%v", len(got), len(want), got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("第 %d 条 = %q, 想要 %q(全部:%v)", i, got[i], want[i], got)
}
}
}
// TestTabEntriesSavedDisabled 全部未保存时,「关闭已保存的」置灰且不可点。
func TestTabEntriesSavedDisabled(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc("/x/a.go", "a"),
newTabDoc("/x/b.go", "b"),
}}
a.docs[0].buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// dirty\n"})
a.docs[1].buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// dirty\n"})
es := a.tabEntries("/x/a.go")
last := es[len(es)-1]
if !last.disabled {
t.Fatalf("全脏时「关闭已保存的」应当 disabled:%+v", last)
}
if last.action != nil {
t.Fatalf("disabled 项不该带 action")
}
}
// TestTabEntriesMissingDoc 路径不在标签里时返回 nil(openPop 会因此不弹)。
func TestTabEntriesMissingDoc(t *testing.T) {
a := &App{docs: []*Doc{newTabDoc("/x/a.go", "a")}}
if es := a.tabEntries("/x/none.go"); es != nil {
t.Fatalf("不存在的路径应返回 nil,得到 %v", labels(es))
}
}
// TestClosePathsRange 区间裁剪:越界不该 panic。
func TestClosePathsRange(t *testing.T) {
a := &App{docs: []*Doc{
newTabDoc(filepath.Join("tmp", "a.go"), "a"),
}}
// a.win 为 nil,closePathsOf 会直接返回;这里只验证区间计算不越界。
a.closePaths(-5, 99)
a.closePaths(3, 1)
}
+65
View File
@@ -0,0 +1,65 @@
package app
import "strings"
// 测试开关:-race / -bench。
//
// 三个 go test 入口(结果树、输出面板、覆盖率)都走 withTestFlags 注入,
// 免得某个入口漏了、开关只在一半地方生效。
// testFlags 是纯函数,组合出要插到 "go test" 后面的参数。
//
// -bench 配 -run=^$ 是 Go 的惯例:跑基准时不重复跑普通测试。但如果调用方
// 已经给了 -run(例如「运行光标处这一个测试」),就不能覆盖掉它。
func testFlags(race, bench, hasRun bool) []string {
var out []string
if race {
out = append(out, "-race")
}
if bench {
out = append(out, "-bench=.")
if !hasRun {
out = append(out, "-run=^$")
}
}
return out
}
// hasRunFlag 判断参数里是否已经指定了 -run / -run=xxx。
func hasRunFlag(args []string) bool {
for _, a := range args {
if a == "-run" || strings.HasPrefix(a, "-run=") {
return true
}
}
return false
}
// withTestFlags 把开关插到 "go test" 之后、其余参数之前。
// 参数是 go 的完整命令行,args[0] 应为 "test"。
func (a *App) withTestFlags(args []string) []string {
extra := testFlags(a.testRace, a.testBench, hasRunFlag(args))
if len(extra) == 0 || len(args) == 0 {
return args
}
out := make([]string, 0, len(args)+len(extra))
out = append(out, args[0])
out = append(out, extra...)
out = append(out, args[1:]...)
return out
}
// testCommandLabel 是输出面板里显示的命令行。
func (a *App) testCommandLabel(base string) string {
var parts []string
if a.testRace {
parts = append(parts, "-race")
}
if a.testBench {
parts = append(parts, "-bench=.")
}
if len(parts) == 0 {
return base
}
return base + " [" + strings.Join(parts, " ") + "]"
}
+79
View File
@@ -0,0 +1,79 @@
package app
import (
"reflect"
"testing"
)
func TestTestFlags(t *testing.T) {
cases := []struct {
race, bench, hasRun bool
want []string
}{
{false, false, false, nil},
{true, false, false, []string{"-race"}},
{false, true, false, []string{"-bench=.", "-run=^$"}},
{true, true, false, []string{"-race", "-bench=.", "-run=^$"}},
// 「运行光标处测试」已给 -run,不能被 -run=^$ 覆盖掉。
{false, true, true, []string{"-bench=."}},
{true, true, true, []string{"-race", "-bench=."}},
}
for _, c := range cases {
got := testFlags(c.race, c.bench, c.hasRun)
if !reflect.DeepEqual(got, c.want) {
t.Errorf("testFlags(%v,%v,%v) = %v, want %v", c.race, c.bench, c.hasRun, got, c.want)
}
}
}
func TestHasRunFlag(t *testing.T) {
for _, args := range [][]string{
{"test", "-json", "-run", "TestFoo", "./pkg"},
{"test", "-run=^TestFoo$", "./..."},
} {
if !hasRunFlag(args) {
t.Errorf("该识别出 -run:%v", args)
}
}
if hasRunFlag([]string{"test", "-json", "./..."}) {
t.Fatal("没有 -run 却识别成了有")
}
}
func TestWithTestFlags(t *testing.T) {
// 关闭时原样返回,不制造多余分配。
a := &App{}
in := []string{"test", "-json", "./..."}
got := a.withTestFlags(in)
if !reflect.DeepEqual(got, in) {
t.Fatalf("开关全关时不该改参数:%v", got)
}
a.testRace, a.testBench = true, true
got = a.withTestFlags([]string{"test", "-json", "./..."})
want := []string{"test", "-race", "-bench=.", "-run=^$", "-json", "./..."}
if !reflect.DeepEqual(got, want) {
t.Fatalf("注入位置不对\n got: %v\nwant: %v", got, want)
}
// 已有 -run 时不加 -run=^$。
got = a.withTestFlags([]string{"test", "-json", "-run", "TestFoo", "./pkg"})
if !reflect.DeepEqual(got[:4], []string{"test", "-race", "-bench=.", "-json"}) {
t.Fatalf("不该覆盖已有的 -run:%v", got)
}
for _, x := range got {
if x == "-run=^$" {
t.Fatalf("已有 -run 时不该再加 -run=^$:%v", got)
}
}
}
func TestTestCommandLabel(t *testing.T) {
a := &App{}
if got := a.testCommandLabel("go test ./..."); got != "go test ./..." {
t.Fatalf("没开关时标签不该变:%q", got)
}
a.testRace, a.testBench = true, true
if got := a.testCommandLabel("go test ./..."); got != "go test ./... [-race -bench=.]" {
t.Fatalf("标签没显示开关:%q", got)
}
}
+13 -1
View File
@@ -93,6 +93,7 @@ func (a *App) runOneTest(pkg, name string) {
// startTest 拉起一次 go test 并把结果树清空重填;args 是 go 的完整参数。 // startTest 拉起一次 go test 并把结果树清空重填;args 是 go 的完整参数。
func (a *App) startTest(args ...string) { func (a *App) startTest(args ...string) {
args = a.withTestFlags(args)
if a.test.running { if a.test.running {
a.StopTask() a.StopTask()
} }
@@ -281,7 +282,12 @@ func (a *App) testView(c *ui.Context) {
ui.Column(c).FillHeight().Children(func() { ui.Column(c).FillHeight().Children(func() {
ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center). ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center).
BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() {
ui.Textf(c, "%s", a.test.pattern).FontSize(11).TextColor(t.TextMuted).SingleLine() ui.Textf(c, "%s", a.testCommandLabel(a.test.pattern)).FontSize(11).
TextColor(t.TextMuted).SingleLine()
// 会话级开关:不写进设置文件,重开 IDE 自动回到关闭状态。
// -race 会明显拖慢测试,不该变成「不知何时被打开」的持久状态。
ui.Checkbox(c, &a.testRace, "-race")
ui.Checkbox(c, &a.testBench, "-bench")
ui.Box(c).Grow(1) ui.Box(c).Grow(1)
if pass+fail+skip > 0 { if pass+fail+skip > 0 {
ui.Textf(c, "✓ %d ✗ %d ○ %d", pass, fail, skip).FontSize(11).TextColor(t.TextMuted) ui.Textf(c, "✓ %d ✗ %d ○ %d", pass, fail, skip).FontSize(11).TextColor(t.TextMuted)
@@ -290,8 +296,14 @@ func (a *App) testView(c *ui.Context) {
ui.Text(c, "运行中…").FontSize(11).TextColor(t.Accent) ui.Text(c, "运行中…").FontSize(11).TextColor(t.Accent)
} }
if ui.Button(c, "全部测试").Clicked() { if ui.Button(c, "全部测试").Clicked() {
// -json 会把 benchmark 的 ns/op 埋在 output 行里,结果树看不清;
// 勾了 -bench 就直接走输出面板,数字原样可见。
if a.testBench {
a.RunTests()
} else {
a.RunTestTree("") a.RunTestTree("")
} }
}
if ui.Button(c, "当前包").Clicked() { if ui.Button(c, "当前包").Clicked() {
a.runCurrentPackageTests() a.runCurrentPackageTests()
} }
+21
View File
@@ -0,0 +1,21 @@
//go:build !windows
package app
import (
"errors"
"os"
)
// moveToTrash 在非 Windows 平台没有统一的可逆删除方式:
// Linux 的 gio/KDE 各有各的规范,macOS 要走 Finder/NSFileManager。
// 这些平台不是本项目的主要目标(Win7 工控机 / Win10 开发机),
// 这里直接返回「不支持」,由调用方引导用户改用永久删除。
func moveToTrash(paths []string) error {
for _, p := range paths {
if _, err := os.Stat(p); err != nil {
return err
}
}
return errors.New("当前平台不支持移到回收站,请改用「永久删除」")
}
+115
View File
@@ -0,0 +1,115 @@
//go:build windows
package app
import (
"fmt"
"runtime"
"syscall"
"unsafe"
)
// 删除到回收站。
//
// 用 shell32 的 SHFileOperationW 而不是自己搬文件:只有经过 shell 才进得了
// 回收站($Recycle.Bin 里每个盘一个、还要写 $I/$R 元数据),自己拼目录是错的。
//
// 为什么不用 IFileOperation(Vista+ 的 COM 接口):要写一堆 COM 样板
// (vtable、引用计数、CoInitialize),换来的好处只有「能拿进度回调」,
// 这里删的是用户手选的几项,用不上。
//
// 已知取舍:SHFileOperationW 对超长路径(>MAX_PATH)支持不好,
// 超过 260 字符的路径会失败——此时用户会看到明确的错误,可以改用「永久删除」。
const (
foDelete = 0x0003 // FO_DELETE
// FOF_ALLOWUNDO 是关键:没有它 SHFileOperation 就是真删。
fofAllowUndo = 0x0040
fofNoConfirmation = 0x0010
fofSilent = 0x0004
fofNoErrorUI = 0x0400
)
// shFileOpStruct 对应 Windows 的 SHFILEOPSTRUCTW。
//
// 字段顺序与宽度必须与 SDK 一致(64 位下 hwnd 与两个指针是 8 字节,
// wFunc/fFlags/BOOL 是 4/2/4)。Go 会按字段对齐自动补 padding,不用手写。
type shFileOpStruct struct {
hwnd syscall.Handle
wFunc uint32
pFrom *uint16
pTo *uint16
fFlags uint16
fAnyOperationsAborted int32
hNameMappings uintptr
lpszProgressTitle *uint16
}
var procSHFileOperationW = syscall.NewLazyDLL("shell32.dll").NewProc("SHFileOperationW")
// shQueryRBInfo 对应 SHQUERYRBINFO,给 SHQueryRecycleBinW 用。
type shQueryRBInfo struct {
cbSize uint32
i64Size int64 // 回收站占用字节数
i64NumItems int64 // 项目数
}
var procSHQueryRecycleBinW = syscall.NewLazyDLL("shell32.dll").NewProc("SHQueryRecycleBinW")
// recycleBinItems 返回回收站的项目数;drive 为空表示统计所有盘。
//
// 只给测试用:验证 moveToTrash 是真把文件放进了回收站,
// 而不是「文件消失了」就算数——后者在 FOF_ALLOWUNDO 漏写时同样成立。
//
// 查单个盘("C:")比查全盘快一个量级:全盘要遍历每个 $Recycle.Bin,
// 回收站里东西多的时候能卡十几秒。
func recycleBinItems(drive string) (int64, error) {
info := shQueryRBInfo{}
info.cbSize = uint32(unsafe.Sizeof(info))
var root *uint16
var keep []uint16
if drive != "" {
keep = syscall.StringToUTF16(drive + `\`)
root = &keep[0]
}
ret, _, _ := procSHQueryRecycleBinW.Call(
uintptr(unsafe.Pointer(root)), uintptr(unsafe.Pointer(&info)))
runtime.KeepAlive(keep)
if ret != 0 {
return 0, fmt.Errorf("SHQueryRecycleBinW 失败(0x%X)", ret)
}
return info.i64NumItems, nil
}
// moveToTrash 把一批路径移进回收站;磁盘路径必须存在。
func moveToTrash(paths []string) error {
if len(paths) == 0 {
return nil
}
// pFrom 的格式是「每个路径以 \0 结尾,整个列表再补一个 \0」,
// 也就是双 null 收尾。StringToUTF16 自带一个 \0,所以这里再补一个。
var buf []uint16
for _, p := range paths {
buf = append(buf, syscall.StringToUTF16(p)...)
}
buf = append(buf, 0)
op := shFileOpStruct{
wFunc: foDelete,
pFrom: &buf[0],
// NOERRORUI:失败由我们提示,不让系统弹一个英文框。
// SILENT + NOCONFIRMATION:确认已经在自己的弹窗里问过了。
fFlags: fofAllowUndo | fofNoConfirmation | fofSilent | fofNoErrorUI,
}
ret, _, _ := procSHFileOperationW.Call(uintptr(unsafe.Pointer(&op)))
runtime.KeepAlive(buf) // buf 必须活到调用返回
if ret != 0 {
return fmt.Errorf("移到回收站失败(错误码 0x%X)", ret)
}
if op.fAnyOperationsAborted != 0 {
return fmt.Errorf("已被取消")
}
return nil
}
+89
View File
@@ -0,0 +1,89 @@
//go:build windows
package app
import (
"os"
"path/filepath"
"testing"
)
// TestMoveToTrash 真调 shell32:文件离开原路径,且回收站项目数确实增加了。
//
// 为什么两条都要断言:SHFILEOPSTRUCTW 的字段宽度、pFrom 的双 null 收尾、
// FOF_ALLOWUNDO 这几个点只要错一个,要么静默不删、要么变成永久删除。
// 只查「原路径没了」看不出后者——那正是回收站与真删的唯一区别。
func TestMoveToTrash(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "trash-me.txt")
drive := filepath.VolumeName(p) // "C:" —— 只查这个盘,全盘要慢十几秒
before, err := recycleBinItems(drive)
if err != nil {
t.Skipf("查不到回收站状态,跳过:%v", err)
}
if err := os.WriteFile(p, []byte("bye"), 0o644); err != nil {
t.Fatal(err)
}
if err := moveToTrash([]string{p}); err != nil {
t.Fatalf("移到回收站失败:%v", err)
}
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatalf("文件应已离开原路径,stat err = %v", err)
}
after, err := recycleBinItems(drive)
if err != nil {
t.Fatalf("查回收站失败:%v", err)
}
if after <= before {
t.Fatalf("回收站项目数没增加(%d → %d),说明文件是被真删而不是移进来的", before, after)
}
}
// TestMoveToTrashDir 目录也要能整棵移走。
func TestMoveToTrashDir(t *testing.T) {
dir := t.TempDir()
sub := filepath.Join(dir, "pkg")
if err := os.MkdirAll(filepath.Join(sub, "deep"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(sub, "deep", "a.go"), []byte("package a"), 0o644); err != nil {
t.Fatal(err)
}
if err := moveToTrash([]string{sub}); err != nil {
t.Fatalf("目录移到回收站失败:%v", err)
}
if _, err := os.Stat(sub); !os.IsNotExist(err) {
t.Fatalf("目录应已被移走,stat err = %v", err)
}
}
// TestMoveToTrashMissing 不存在的路径要报错而不是崩。
func TestMoveToTrashMissing(t *testing.T) {
err := moveToTrash([]string{filepath.Join(t.TempDir(), "nope.txt")})
if err == nil {
t.Fatal("不存在的路径应返回错误")
}
}
// TestMoveToTrashBatch 批量一次调用(pFrom 是双 null 结尾的列表)。
func TestMoveToTrashBatch(t *testing.T) {
dir := t.TempDir()
var paths []string
for _, n := range []string{"a.txt", "b.txt", "c.txt"} {
p := filepath.Join(dir, n)
if err := os.WriteFile(p, []byte(n), 0o644); err != nil {
t.Fatal(err)
}
paths = append(paths, p)
}
if err := moveToTrash(paths); err != nil {
t.Fatalf("批量移入回收站失败:%v", err)
}
for _, p := range paths {
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatalf("%s 应已被移走", p)
}
}
}
+12 -1
View File
@@ -472,6 +472,10 @@ func (a *App) editorArea(c *ui.Context, grow bool) {
// 为真时是 `total - lineHeight`,短文本也大于 0,于是短文件照样画滚动条)。 // 为真时是 `total - lineHeight`,短文本也大于 0,于是短文件照样画滚动条)。
// 关掉后 scrollMax 变成 `total - viewH`,内容不满一页时被 max(0, …) 归零, // 关掉后 scrollMax 变成 `total - viewH`,内容不满一页时被 max(0, …) 归零,
// 滚动条自然消失;长文件不受影响,仍然照常滚动。 // 滚动条自然消失;长文件不受影响,仍然照常滚动。
//
// mygo v0.7.4 起滚动条的滑块改成「指针在编辑器上或拖着它时才画」
// (paintScrollbars 里 `shown := ed.pointerIn || ed.scrollbar.active`),
// 但判据本身没变:不关的话,短文件只要鼠标一移进来,仍会冒出整条滑块。
d.st.NoScrollPastEnd = true d.st.NoScrollPastEnd = true
// 上面是面包屑,下面是编辑器 + 缩略图。 // 上面是面包屑,下面是编辑器 + 缩略图。
@@ -512,13 +516,20 @@ func (a *App) tabBar(c *ui.Context) {
} }
ui.Row(c).Radius(3).Background(bg).AlignItems(ui.Center). ui.Row(c).Radius(3).Background(bg).AlignItems(ui.Center).
Children(func() { Children(func() {
label := filepath.Base(d.path) label := a.tabLabel(d)
if d.buf.Modified() { if d.buf.Modified() {
label = "● " + label label = "● " + label
} }
open := ui.ButtonBase(c).Padding(3, 7).Children(func() { open := ui.ButtonBase(c).Padding(3, 7).Children(func() {
ui.Text(c, label).FontSize(12).TextColor(fg).SingleLine() ui.Text(c, label).FontSize(12).TextColor(fg).SingleLine()
}) })
// 右键:关闭左边/右边/其他/全部/已保存(tabmenu.go)。
// 先把这条设为 active,是因为菜单本身没有标题,用户得靠
// 标签高亮确认「关闭左边」是相对哪一个算的。
if open.RightClicked() {
a.active = d.path
a.openPop(open, a.tabEntries(d.path))
}
if open.Clicked() { if open.Clicked() {
a.active = d.path a.active = d.path
} }
+34 -5
View File
@@ -277,13 +277,42 @@ func (c *Client) Initialize() error {
} }
// Launch 启动被调试程序,args 是传给程序的参数。 // Launch 启动被调试程序,args 是传给程序的参数。
// LaunchOptions 是 dlv launch 请求里我们关心的字段。
//
// env 与 cwd 都是 dlv 的扩展字段(不属于 DAP 规范),dlv 会把它们应用到
// **被调试进程**上,而不是 dlv 自己——这正是不该给 dlv 进程设环境的原因。
type LaunchOptions struct {
Program string
Args []string
StopOnEntry bool
Env map[string]string
WorkDir string
}
// Launch 用默认选项启动调试,保留给不需要 Env/WorkDir 的调用方。
func (c *Client) Launch(program string, args []string, stopOnEntry bool, timeout time.Duration) error { func (c *Client) Launch(program string, args []string, stopOnEntry bool, timeout time.Duration) error {
_, err := c.Do("launch", map[string]any{ return c.LaunchWith(LaunchOptions{
"mode": "debug", Program: program,
"program": program, Args: args,
"args": args, StopOnEntry: stopOnEntry,
"stopOnEntry": stopOnEntry,
}, timeout) }, timeout)
}
// LaunchWith 按给定选项启动调试。
func (c *Client) LaunchWith(o LaunchOptions, timeout time.Duration) error {
req := map[string]any{
"mode": "debug",
"program": o.Program,
"args": o.Args,
"stopOnEntry": o.StopOnEntry,
}
if len(o.Env) > 0 {
req["env"] = o.Env
}
if o.WorkDir != "" {
req["cwd"] = o.WorkDir
}
_, err := c.Do("launch", req, timeout)
return err return err
} }
+1 -1
View File
@@ -94,7 +94,7 @@ func NormKey(s string) string {
} }
// isStandard 判断是否标准库导入路径:首段不含点 // isStandard 判断是否标准库导入路径:首段不含点
//(fmt 是;github.com/x/y 不是)。对 99% 的包够用。 // (fmt 是;github.com/x/y 不是)。对 99% 的包够用。
func isStandard(pkgPath string) bool { func isStandard(pkgPath string) bool {
first := pkgPath first := pkgPath
if i := strings.IndexByte(first, '/'); i >= 0 { if i := strings.IndexByte(first, '/'); i >= 0 {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
) )
// TestDocsFmt 提取 fmt 包:应当包含 Println 的文档,条目量在合理范围 // TestDocsFmt 提取 fmt 包:应当包含 Println 的文档,条目量在合理范围
//(fmt 实测 29 条:23 个函数 + 6 个类型)。 // (fmt 实测 29 条:23 个函数 + 6 个类型)。
func TestDocsFmt(t *testing.T) { func TestDocsFmt(t *testing.T) {
docs, err := Docs("fmt") docs, err := Docs("fmt")
if err != nil { if err != nil {
+18 -1
View File
@@ -367,11 +367,28 @@ func (c *Client) Rename(ctx context.Context, uri string, pos Position, newName s
// CodeActions 请求指定范围上的代码动作(快速修复、整理 import 等)。 // CodeActions 请求指定范围上的代码动作(快速修复、整理 import 等)。
func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error) { func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error) {
return c.CodeActionsOnly(ctx, uri, r, diags, nil)
}
// CodeActionsOnly 同 CodeActions,但可以按 kind 过滤(LSP 的 context.only)。
//
// only 为空表示不过滤。gopls 支持 "quickfix"、"refactor"、"refactor.rewrite"、
// "source" 这些前缀;用它最实际的好处是「只问整文件级的重构」时不会顺带
// 把一堆焦点相关的动作再拉一遍。
func (c *Client) CodeActionsOnly(ctx context.Context, uri string, r Range, diags []Diagnostic, only []string) ([]CodeAction, error) {
if diags == nil {
// JSON 里 null 和 [] 对某些服务端不等价,统一给空数组。
diags = []Diagnostic{}
}
cctx := map[string]any{"diagnostics": diags}
if len(only) > 0 {
cctx["only"] = only
}
var out []CodeAction var out []CodeAction
err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{ err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{
"textDocument": TextDocumentIdentifier{URI: uri}, "textDocument": TextDocumentIdentifier{URI: uri},
"range": r, "range": r,
"context": map[string]any{"diagnostics": diags}, "context": cctx,
}, &out) }, &out)
return out, err return out, err
} }
+218
View File
@@ -0,0 +1,218 @@
package lsp
import (
"context"
"path/filepath"
"strings"
"testing"
"time"
)
// codeActionKinds 请求一次代码动作,返回所有 kind。
func codeActionKinds(t *testing.T, c *Client, uri string, r Range, diags []Diagnostic, only []string) []string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
acts, err := c.CodeActionsOnly(ctx, uri, r, diags, only)
if err != nil {
t.Fatalf("请求代码动作失败: %v", err)
}
kinds := make([]string, 0, len(acts))
for _, a := range acts {
kinds = append(kinds, a.Kind)
}
return kinds
}
// waitKind 轮询到出现指定 kind 为止(gopls 加载包需要时间)。
func waitKind(t *testing.T, c *Client, uri string, r Range, diags []Diagnostic, only []string, want string) []string {
t.Helper()
var kinds []string
for i := 0; i < 40; i++ {
kinds = codeActionKinds(t, c, uri, r, diags, only)
for _, k := range kinds {
if k == want {
return kinds
}
}
time.Sleep(500 * time.Millisecond)
}
t.Fatalf("等了 20 秒也没等到 %q,最后的 kind:%v", want, kinds)
return nil
}
// hasKind 判断 kind 列表里有没有某一项。
func hasKind(kinds []string, want string) bool {
for _, k := range kinds {
if k == want {
return true
}
}
return false
}
const codeActionSrc = `package demo
import "strings"
type Rect struct {
W, H float64
}
func (r Rect) Area() float64 { return r.W * r.H }
func caller() string {
return strings.ToUpper("b")
}
`
// TestGoplsCodeActionSelection 选区决定 gopls 给不给 extract/inline。
//
// 这条测试钉的是一个**实测事实**(gopls v0.23):
// - 范围正好圈住表达式 → 有 refactor.extract.variable、refactor.inline.call
// - 范围是整行 → 只有 refactor.extract.function,没有前两者
//
// 应用层就是靠它把「选中 foo() 再按 Alt+Enter」做成「提取这个表达式」的;
// 一旦有人把选区退回成整行,这里会红。
func TestGoplsCodeActionSelection(t *testing.T) {
c, dir, _ := startTestClient(t)
path := filepath.Join(dir, "demo.go")
writeFile(t, path, codeActionSrc)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, codeActionSrc); err != nil {
t.Fatal(err)
}
off := strings.Index(codeActionSrc, `strings.ToUpper("b")`)
if off < 0 {
t.Fatal("测试源码里找不到目标表达式")
}
sel := Range{
Start: OffsetToPosition(codeActionSrc, off),
End: OffsetToPosition(codeActionSrc, off+len(`strings.ToUpper("b")`)),
}
kinds := waitKind(t, c, uri, sel, nil, nil, "refactor.extract.variable")
for _, want := range []string{"refactor.extract.variable", "refactor.inline.call"} {
if !hasKind(kinds, want) {
t.Fatalf("选区请求里没有 %q:%v", want, kinds)
}
}
// 同一行、但范围是整个行 → 只剩 extract.function。
line := sel.Start.Line
lineText := strings.Split(codeActionSrc, "\n")[line]
lineRange := Range{
Start: Position{Line: line, Character: 0},
End: Position{Line: line, Character: UTF16Len(lineText)},
}
kinds = waitKind(t, c, uri, lineRange, nil, nil, "refactor.extract.function")
if hasKind(kinds, "refactor.extract.variable") {
t.Fatalf("整行范围居然也给了 extract.variable,前提变了:%v", kinds)
}
}
// TestGoplsCodeActionWholeFile 整文件范围 + only=refactor.rewrite 才能拿到
// 「Add struct tags」这类文件级重构。
func TestGoplsCodeActionWholeFile(t *testing.T) {
c, dir, _ := startTestClient(t)
path := filepath.Join(dir, "demo.go")
writeFile(t, path, codeActionSrc)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, codeActionSrc); err != nil {
t.Fatal(err)
}
lines := strings.Split(codeActionSrc, "\n")
whole := Range{
Start: Position{Line: 0},
End: Position{Line: len(lines) - 1, Character: UTF16Len(lines[len(lines)-1])},
}
kinds := waitKind(t, c, uri, whole, nil, []string{"refactor.rewrite"}, "refactor.rewrite.addTags")
// only 得真的起过滤作用:不该混进 quickfix 或 source。
for _, k := range kinds {
if strings.HasPrefix(k, "quickfix") || strings.HasPrefix(k, "source") {
t.Fatalf("only=refactor.rewrite 却返回了 %q", k)
}
}
}
// TestGoplsCodeActionMissingImportQuickfix 快速修复的取法。
//
// 用「缺 import」当例子:gopls v0.23 对 `undefined: fmt` 会给
// 「Add import: "fmt"」这条 quickfix。钉住两点(实测,不是推测):
// - 不带诊断 → 拿不到。quickfix 靠上下文里的诊断匹配,这条是硬前提;
// - 请求范围给整行还是行首的零宽位置 → 都拿得到。gopls 会把位置摊到
// 所属节点上,所以「范围必须盖住诊断」不是必要条件。
//
// 第二条是修正:原先应用层的注释声称「零宽位置会丢快速修复」,实测不成立。
func TestGoplsCodeActionMissingImportQuickfix(t *testing.T) {
c, dir, diags := startTestClient(t)
src := "package demo\n\nfunc f() { fmt.Println(1) }\n"
path := filepath.Join(dir, "demo.go")
writeFile(t, path, src)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
var dg []Diagnostic
select {
case dg = <-diags:
case <-time.After(90 * time.Second):
t.Fatal("等诊断超时")
}
if len(dg) == 0 {
t.Skip("gopls 这次没推诊断,跳过")
}
pos := OffsetToPosition(src, strings.Index(src, "func f()"))
full := Range{
Start: Position{Line: pos.Line, Character: 0},
End: Position{Line: pos.Line, Character: UTF16Len("func f() { fmt.Println(1) }")},
}
// 整行 + 诊断:应当拿到 quickfix,且是那条加 import 的。
var titles []string
for i := 0; i < 40; i++ {
kinds := codeActionKinds(t, c, uri, full, dg, []string{"quickfix"})
titles = titles[:0]
if len(kinds) > 0 {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
acts, err := c.CodeActionsOnly(ctx, uri, full, dg, []string{"quickfix"})
cancel()
if err != nil {
t.Fatalf("请求代码动作失败: %v", err)
}
for _, a := range acts {
titles = append(titles, a.Title)
}
break
}
time.Sleep(500 * time.Millisecond)
}
if len(titles) == 0 {
t.Fatalf("整行范围 + 诊断没拿到快速修复")
}
found := false
for _, s := range titles {
if strings.Contains(s, "import") && strings.Contains(s, "fmt") {
found = true
}
}
if !found {
t.Fatalf("快速修复里没有加 import 的那条:%v", titles)
}
// 对照组一:不带诊断。
if got := codeActionKinds(t, c, uri, full, nil, []string{"quickfix"}); len(got) != 0 {
t.Fatalf("不带诊断也拿到了 %v,前提变了", got)
}
// 对照:带诊断,但请求范围收成行首的零宽位置——照样拿得到。
// 说明「整行」是给按节点展开的动作留范围,不是 quickfix 的必要条件。
zero := Range{Start: full.Start, End: full.Start}
if got := codeActionKinds(t, c, uri, zero, dg, []string{"quickfix"}); len(got) == 0 {
t.Fatal("零宽位置反而丢了快速修复,那注释里的说法要再改一次")
}
}
+65
View File
@@ -0,0 +1,65 @@
package lsp
import (
"context"
"path/filepath"
"strings"
"testing"
"time"
)
// TestGoplsCompletionSnippetFormat 固化 2026-11-12 的实测结论。
//
// 声明 snippetSupport=true 之后,gopls v0.23 对函数补全返回:
//
// insertTextFormat = 2
// insertText = "" (空)
// textEdit.newText = "Print(${1:})"
//
// 也就是说插入内容只在 textEdit 里,且占位符是「空默认值」的 ${1:}。
// 早期把 insertTextFormat 当成可选项、只看 insertText 的实现会漏掉这类补全。
// gopls 换行为时这条会红,正好提醒重新核对接线。
func TestGoplsCompletionSnippetFormat(t *testing.T) {
c, dir, _ := startTestClient(t)
src := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Pr\n}\n"
path := filepath.Join(dir, "main.go")
writeFile(t, path, src)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
pos := OffsetToPosition(src, len(src)-len("\n}\n"))
var items []CompletionItem
for i := 0; i < 10; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
var err error
items, err = c.Completion(ctx, uri, pos)
cancel()
if err == nil && len(items) > 0 {
break
}
time.Sleep(500 * time.Millisecond)
}
if len(items) == 0 {
t.Fatal("没有补全结果")
}
withSnippet := 0
for _, it := range items {
if it.InsertTextFormat != 2 {
continue
}
withSnippet++
newText := ""
if it.TextEdit != nil {
newText = it.TextEdit.NewText
}
if !strings.Contains(newText, "${") {
t.Errorf("format=2 但 textEdit.newText 里没有占位符:%q", newText)
}
}
if withSnippet == 0 {
t.Fatalf("snippetSupport 已开启,却没有任何 format=2 的补全项:%+v", items[:min(3, len(items))])
}
}
+2 -1
View File
@@ -90,6 +90,7 @@ type CompletionItem struct {
Detail string `json:"detail"` Detail string `json:"detail"`
Documentation json.RawMessage `json:"documentation"` Documentation json.RawMessage `json:"documentation"`
InsertText string `json:"insertText"` InsertText string `json:"insertText"`
InsertTextFormat int `json:"insertTextFormat"` // 1=纯文本 2=snippet
TextEdit *TextEdit `json:"textEdit"` TextEdit *TextEdit `json:"textEdit"`
FilterText string `json:"filterText"` FilterText string `json:"filterText"`
SortText string `json:"sortText"` SortText string `json:"sortText"`
@@ -302,7 +303,7 @@ func defaultCapabilities() ClientCapabilities {
Synchronization: SynchronizationCapabilities{DidSave: true}, Synchronization: SynchronizationCapabilities{DidSave: true},
Completion: map[string]any{ Completion: map[string]any{
"completionItem": map[string]any{ "completionItem": map[string]any{
"snippetSupport": false, "snippetSupport": true,
"documentationFormat": []string{"markdown", "plaintext"}, "documentationFormat": []string{"markdown", "plaintext"},
}, },
"contextSupport": true, "contextSupport": true,
+46 -1
View File
@@ -4,7 +4,9 @@ package task
import ( import (
"bufio" "bufio"
"io" "io"
"os"
"os/exec" "os/exec"
"strings"
"sync" "sync"
) )
@@ -21,11 +23,28 @@ type Task struct {
stopped bool stopped bool
} }
// Options 是一次执行的位置与环境。
type Options struct {
// Dir 是工作目录,空表示沿用当前进程的工作目录。
Dir string
// Env 是要追加/覆盖的环境变量(KEY=VALUE 形式由调用方组装)。
// 不整体替换环境:那样会把 PATH 之类清掉,go 命令直接跑不起来。
Env []string
}
// Start 在 dir 下启动命令,标准输出与标准错误合并成有序的行。 // Start 在 dir 下启动命令,标准输出与标准错误合并成有序的行。
func Start(dir, name string, args ...string) (*Task, error) { func Start(dir, name string, args ...string) (*Task, error) {
return StartWith(Options{Dir: dir}, name, args...)
}
// StartWith 与 Start 相同,另可指定环境变量。
func StartWith(o Options, name string, args ...string) (*Task, error) {
cmd := exec.Command(name, args...) cmd := exec.Command(name, args...)
cmd.Dir = dir cmd.Dir = o.Dir
cmd.SysProcAttr = procAttr() cmd.SysProcAttr = procAttr()
if len(o.Env) > 0 {
cmd.Env = mergeEnv(os.Environ(), o.Env)
}
pr, pw := io.Pipe() pr, pw := io.Pipe()
cmd.Stdout = pw cmd.Stdout = pw
@@ -91,3 +110,29 @@ func (t *Task) Stop() {
t.mu.Unlock() t.mu.Unlock()
killTree(t.cmd.Process.Pid) killTree(t.cmd.Process.Pid)
} }
// mergeEnv 把 extra 合并进 base,同一个 KEY 以 extra 为准。
//
// 为什么不直接 append:Windows 的环境块里有同名变量时,子进程读到哪一个
// 取决于顺序,实测会出现「设了没生效」。先把被覆盖的剔掉更稳。
// 变量名在 Windows 上不区分大小写,比较时统一转大写。
func mergeEnv(base, extra []string) []string {
if len(extra) == 0 {
return base
}
overridden := make(map[string]bool, len(extra))
for _, kv := range extra {
if k, _, ok := strings.Cut(kv, "="); ok && k != "" {
overridden[strings.ToUpper(k)] = true
}
}
out := make([]string, 0, len(base)+len(extra))
for _, kv := range base {
k, _, ok := strings.Cut(kv, "=")
if ok && overridden[strings.ToUpper(k)] {
continue
}
out = append(out, kv)
}
return append(out, extra...)
}
+76
View File
@@ -1,6 +1,8 @@
package task package task
import ( import (
"os"
"path/filepath"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -58,3 +60,77 @@ func TestStop(t *testing.T) {
t.Fatal("Stopped 应为 true") t.Fatal("Stopped 应为 true")
} }
} }
// TestMergeEnv 同名变量以 extra 为准,且只留一份。
func TestMergeEnv(t *testing.T) {
base := []string{"PATH=/bin", "FOO=old", "BAR=keep"}
got := mergeEnv(base, []string{"FOO=new", "baz=1"})
count := map[string]int{}
value := map[string]string{}
for _, kv := range got {
k, v, _ := strings.Cut(kv, "=")
count[strings.ToUpper(k)]++
value[strings.ToUpper(k)] = v
}
if count["FOO"] != 1 || value["FOO"] != "new" {
t.Fatalf("FOO 应只剩一份且为新值:%v", got)
}
if value["BAR"] != "keep" || value["PATH"] != "/bin" {
t.Fatalf("未覆盖的变量应保留:%v", got)
}
if value["BAZ"] != "1" {
t.Fatalf("新变量应追加:%v", got)
}
// 大小写不同也算同名(Windows 环境变量不区分大小写)。
got = mergeEnv([]string{"Path=x"}, []string{"PATH=y"})
if len(got) != 1 || !strings.HasPrefix(got[0], "PATH=") {
t.Fatalf("大小写同名应覆盖:%v", got)
}
}
// TestStartWithEnv 真跑一次 go run,确认环境变量与带空格的参数都到了程序里。
func TestStartWithEnv(t *testing.T) {
dir := t.TempDir()
src := `package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("env=" + os.Getenv("MYGOLAND_ENV_TEST"))
for i, a := range os.Args[1:] {
fmt.Printf("arg%d=%s\n", i, a)
}
}
`
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(src), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module envtest\n\ngo 1.21\n"), 0o644); err != nil {
t.Fatal(err)
}
tk, err := StartWith(Options{
Dir: dir,
Env: []string{"MYGOLAND_ENV_TEST=hello world"},
}, "go", "run", ".", "-tags", "a b")
if err != nil {
t.Fatalf("启动失败: %v", err)
}
var out []string
for l := range tk.Lines {
out = append(out, l)
}
tk.Wait()
joined := strings.Join(out, "\n")
if !strings.Contains(joined, "env=hello world") {
t.Fatalf("环境变量没传进去:\n%s", joined)
}
if !strings.Contains(joined, "arg1=a b") {
t.Fatalf("带空格的参数没原样传进去:\n%s", joined)
}
}
+566
View File
@@ -0,0 +1,566 @@
// e2e 冒烟测试:自己起一个带 automation 插座的 MyGoland 实例,
// 通过无障碍元素树和截图像素做断言,不依赖用户当前打开的窗口。
//
// 用法(在仓库根目录):
//
// go run ./tools/e2e
// go run ./tools/e2e -keep # 保留截图到 .tmp/e2e-smoke/
// go run ./tools/e2e -bin e2e.exe # 复用已编译的二进制,跳过编译
//
// 前提:gopls 在 PATH 里(工作区场景需要语言服务器就绪)。
// 右键菜单必须是自绘面板(ui.Overlay),系统原生菜单 automation 看不到,
// 参见框架 docs/plugins/automation.md。
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"image/png"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type node struct {
ID any `json:"id"`
Role string `json:"role"`
Label string `json:"label"`
Value string `json:"value"`
Bounds rect `json:"bounds"`
Actions []string `json:"actions"`
}
type rect struct {
X float32 `json:"x"`
Y float32 `json:"y"`
W float32 `json:"w"`
H float32 `json:"h"`
}
func (n node) text() string {
if n.Label != "" {
return n.Label
}
return n.Value
}
type client struct {
conn net.Conn
enc *json.Encoder
dec *json.Decoder
id int
}
func dial(sock string) (*client, error) {
c, err := net.Dial("unix", sock)
if err != nil {
return nil, err
}
return &client{conn: c, enc: json.NewEncoder(c), dec: json.NewDecoder(bufio.NewReader(c))}, nil
}
func (c *client) call(method string, params map[string]any, out any) error {
c.id++
req := map[string]any{"id": c.id, "method": method}
if params != nil {
req["params"] = params
}
if err := c.enc.Encode(req); err != nil {
return err
}
var resp struct {
Result json.RawMessage `json:"result"`
Error any `json:"error"`
}
if err := c.dec.Decode(&resp); err != nil {
return err
}
if resp.Error != nil {
return fmt.Errorf("%s: %+v", method, resp.Error)
}
if out != nil && len(resp.Result) > 0 {
return json.Unmarshal(resp.Result, out)
}
return nil
}
func (c *client) windows() ([]int, error) {
var r struct {
Windows []struct {
ID int `json:"id"`
} `json:"windows"`
}
if err := c.call("windows", nil, &r); err != nil {
return nil, err
}
out := make([]int, 0, len(r.Windows))
for _, w := range r.Windows {
out = append(out, w.ID)
}
return out, nil
}
func (c *client) tree() ([]node, error) {
var r struct {
Nodes []node `json:"nodes"`
}
if err := c.call("tree", nil, &r); err != nil {
return nil, err
}
return r.Nodes, nil
}
func (c *client) capture(win int) ([]byte, int, int, error) {
var r struct {
PNG []byte `json:"png"`
Width int `json:"width"`
Height int `json:"height"`
}
if err := c.call("capture", map[string]any{"window": win}, &r); err != nil {
return nil, 0, 0, err
}
return r.PNG, r.Width, r.Height, nil
}
func (c *client) input(win int, events ...map[string]any) error {
return c.call("input", map[string]any{"window": win, "events": events}, nil)
}
func (c *client) click(win int, x, y float32, button string) error {
pos := func(t string) map[string]any {
return map[string]any{"type": t, "x": x, "y": y, "button": button}
}
return c.input(win,
map[string]any{"type": "pointerMove", "x": x, "y": y},
pos("pointerDown"), pos("pointerUp"))
}
func (c *client) key(win int, k string) error {
return c.input(win,
map[string]any{"type": "keyDown", "key": k},
map[string]any{"type": "keyUp", "key": k})
}
// waitFor 轮询直到 fn 返回空串或超时。返回错误说明。
func waitFor(timeout time.Duration, fn func() string) error {
deadline := time.Now().Add(timeout)
last := ""
for time.Now().Before(deadline) {
last = fn()
if last == "" {
return nil
}
time.Sleep(300 * time.Millisecond)
}
return fmt.Errorf("超时:%s", last)
}
func findNode(nodes []node, substr string) (node, bool) {
for _, n := range nodes {
if strings.Contains(strings.ToLower(n.text()), strings.ToLower(substr)) {
return n, true
}
}
return node{}, false
}
// findPanelTab 只认底部页签栏里的按钮。
//
// 面板右上角还有一个同名的「运行」图标按钮(真的会跑程序),全局按 label
// 找会误点。页签都在左半边,用精确的 label + X 上限把它俩分开。
func findPanelTab(nodes []node, label string) (node, bool) {
for _, n := range nodes {
if n.Role == "button" && n.Label == label && n.Bounds.X < 700 {
return n, true
}
}
return node{}, false
}
func findButton(nodes []node, label string) (node, bool) {
for _, n := range nodes {
if n.Role == "button" && n.Label == label {
return n, true
}
}
return node{}, false
}
// ensurePanel 保证底部面板是打开的。
//
// 全新会话里 a.panel 默认 false,状态栏只有一个「面板」按钮;
// 之前手工验证时面板是开的,是因为会话存档记住了状态——冒烟脚本不能
// 依赖这个。所有要操作页签的场景都得先过这一步。
func ensurePanel(c *client, win int) error {
nodes, err := c.tree()
if err != nil {
return err
}
if _, ok := findPanelTab(nodes, "运行"); ok {
return nil
}
btn, ok := findButton(nodes, "面板")
if !ok {
return fmt.Errorf("找不到打开面板的入口")
}
if err := c.click(win, btn.Bounds.X, btn.Bounds.Y, "left"); err != nil {
return err
}
return waitFor(6*time.Second, func() string {
ns, err := c.tree()
if err != nil {
return err.Error()
}
if _, ok := findPanelTab(ns, "运行"); !ok {
return "面板还没出现"
}
return ""
})
}
// distinctColors 数 PNG 里的不同颜色,用来排除「窗口全黑 / 全白」这种
// 渲染彻底失败的情况。只采样一部分像素,够用且快。
func distinctColors(data []byte) (int, error) {
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
return 0, err
}
b := img.Bounds()
seen := map[uint32]bool{}
step := 7
for y := b.Min.Y; y < b.Max.Y; y += step {
for x := b.Min.X; x < b.Max.X; x += step {
r, g, bl, _ := img.At(x, y).RGBA()
seen[(r>>8)<<16|(g>>8)<<8|(bl>>8)] = true
}
}
return len(seen), nil
}
type scenario struct {
name string
run func(*client, int, string) error
}
func main() {
keep := flag.Bool("keep", false, "保留截图与临时目录")
bin := flag.String("bin", "", "复用已编译的 -tags e2e 二进制")
flag.Parse()
root, err := repoRoot()
if err != nil {
fail(err.Error())
}
tmp, err := os.MkdirTemp("", "mygoland-e2e-")
if err != nil {
fail(err.Error())
}
if !*keep {
defer os.RemoveAll(tmp)
} else {
fmt.Println("临时目录:", tmp)
}
ws := filepath.Join(tmp, "workspace")
if err := makeWorkspace(ws); err != nil {
fail(err.Error())
}
exe := *bin
if exe == "" {
exe = filepath.Join(tmp, "smoke.exe")
cmd := exec.Command("go", "build", "-tags", "e2e", "-o", exe, ".")
cmd.Dir = root
if out, err := cmd.CombinedOutput(); err != nil {
fail(fmt.Sprintf("编译 e2e 二进制失败:%v\n%s", err, out))
}
}
sock := filepath.Join(tmp, "smoke.sock")
proc := exec.Command(exe, ws)
proc.Dir = root
proc.Env = append(os.Environ(), "MYGO_AUTOMATION="+sock)
// 日志留到文件,免得污染测试结果输出。
logFile, err := os.Create(filepath.Join(tmp, "app.log"))
if err != nil {
fail(err.Error())
}
proc.Stdout, proc.Stderr = logFile, logFile
if err := proc.Start(); err != nil {
fail(err.Error())
}
defer func() {
_ = proc.Process.Kill()
_, _ = proc.Process.Wait()
_ = logFile.Close()
}()
var c *client
if err := waitFor(20*time.Second, func() string {
cc, err := dial(sock)
if err != nil {
return "等待 automation socket"
}
c = cc
return ""
}); err != nil {
fail(err.Error())
}
defer c.conn.Close()
var win int
if err := waitFor(20*time.Second, func() string {
ws, err := c.windows()
if err != nil || len(ws) == 0 {
return "等待窗口出现"
}
win = ws[0]
return ""
}); err != nil {
fail(err.Error())
}
shotDir := filepath.Join(tmp, "shots")
_ = os.MkdirAll(shotDir, 0o755)
scenarios := []scenario{
{"启动渲染", scStartup},
{"工作区与 gopls", scWorkspace},
{"诊断到达", scDiagnostics},
{"输出面板右键菜单", scOutputMenu},
}
fmt.Println("场景 结果 说明")
fmt.Println("------------------------------------------------------------")
failed := 0
for _, s := range scenarios {
start := time.Now()
err := s.run(c, win, shotDir)
status := "PASS"
detail := fmt.Sprintf("%.1fs", time.Since(start).Seconds())
if err != nil {
status, detail = "FAIL", err.Error()
failed++
}
fmt.Printf("%-24s %-6s %s\n", s.name, status, detail)
}
fmt.Println("------------------------------------------------------------")
fmt.Printf("%d/%d 通过\n", len(scenarios)-failed, len(scenarios))
if failed > 0 {
os.Exit(1)
}
}
func fail(msg string) {
fmt.Fprintln(os.Stderr, "e2e: "+msg)
os.Exit(1)
}
func saveShot(c *client, win int, dir, name string) ([]byte, error) {
data, _, _, err := c.capture(win)
if err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(dir, name+".png"), data, 0o644); err != nil {
return nil, err
}
return data, nil
}
func repoRoot() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir, nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", fmt.Errorf("找不到 go.mod,请在仓库里运行")
}
dir = parent
}
}
func makeWorkspace(ws string) error {
files := map[string]string{
"go.mod": "module example.com/smoke\n\ngo 1.21\n",
"main.go": "package main\n\n" +
"// smokeNeedle 是全局搜索冒烟用的关键字\n" +
"func main() { println(\"smokeNeedle\") }\n",
// 故意的编译错误,用来验证诊断能到达问题面板。
"broken.go": "package main\n\nfunc broken() { var n int = \"not an int\"; _ = n }\n",
}
for rel, text := range files {
p := filepath.Join(ws, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, []byte(text), 0o644); err != nil {
return err
}
}
return nil
}
// 场景 1:窗口存在、元素树非空、截图不是纯色。
func scStartup(c *client, win int, dir string) error {
data, err := saveShot(c, win, dir, "1-startup")
if err != nil {
return err
}
n, err := distinctColors(data)
if err != nil {
return fmt.Errorf("截图解不开:%v", err)
}
if n < 12 {
return fmt.Errorf("截图只有 %d 种颜色,像是渲染失败", n)
}
nodes, err := c.tree()
if err != nil {
return err
}
if len(nodes) < 8 {
return fmt.Errorf("无障碍树只有 %d 个节点", len(nodes))
}
return nil
}
// 场景 2:启动参数里的工作区被打开,代码能显示,且 gopls 就绪。
func scWorkspace(c *client, win int, dir string) error {
if err := waitFor(25*time.Second, func() string {
nodes, err := c.tree()
if err != nil {
return err.Error()
}
if _, ok := findNode(nodes, "main.go"); !ok {
return "文件树里没有 main.go"
}
if _, ok := findNode(nodes, "gopls 就绪"); !ok {
return "状态栏还没显示 gopls 就绪"
}
return ""
}); err != nil {
return err
}
// gopls 只对 didOpen 过的文件推诊断,场景 3 指望 broken.go 有诊断,
// 所以这里得真的把它打开,不能只扫文件树。
nodes, err := c.tree()
if err != nil {
return err
}
f, ok := findButton(nodes, "broken.go")
if !ok {
return fmt.Errorf("文件树里没有 broken.go")
}
if err := c.click(win, f.Bounds.X, f.Bounds.Y, "left"); err != nil {
return err
}
return waitFor(15*time.Second, func() string {
ns, err := c.tree()
if err != nil {
return err.Error()
}
if _, ok := findNode(ns, "Code editor"); !ok {
return "编辑器还没显示文件"
}
_, err = saveShot(c, win, dir, "2-workspace")
if err != nil {
return err.Error()
}
return ""
})
}
// 场景 3:gopls 的诊断能进问题面板。
func scDiagnostics(c *client, win int, dir string) error {
if err := ensurePanel(c, win); err != nil {
return err
}
nodes, err := c.tree()
if err != nil {
return err
}
tab, ok := findPanelTab(nodes, "问题")
if !ok {
return fmt.Errorf("找不到「问题」页签")
}
if err := c.click(win, tab.Bounds.X, tab.Bounds.Y, "left"); err != nil {
return err
}
return waitFor(15*time.Second, func() string {
ns, err := c.tree()
if err != nil {
return err.Error()
}
if _, ok := findNode(ns, "broken.go"); ok {
_, _ = saveShot(c, win, dir, "3-diagnostics")
return ""
}
return "问题面板里没有 broken.go 的诊断"
})
}
// 场景 4:输出面板右键弹出自绘菜单,三项都在。
// 这是 T2 的回归保护:自绘菜单能被 automation 的无障碍树看到。
func scOutputMenu(c *client, win int, dir string) error {
if err := ensurePanel(c, win); err != nil {
return err
}
nodes, err := c.tree()
if err != nil {
return err
}
// 切回「运行」页签,那里才有 ui.List。
tab, ok := findPanelTab(nodes, "运行")
if !ok {
return fmt.Errorf("找不到「运行」页签")
}
if err := c.click(win, tab.Bounds.X, tab.Bounds.Y, "left"); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
var list node
if err := waitFor(5*time.Second, func() string {
ns, err := c.tree()
if err != nil {
return err.Error()
}
for _, n := range ns {
if n.Role == "list" {
list = n
return ""
}
}
return "输出面板里没有 list"
}); err != nil {
return err
}
// 落在列表中间一点,避开顶部标签栏。
x, y := list.Bounds.X+200, list.Bounds.Y+60
if err := c.click(win, x, y, "right"); err != nil {
return err
}
return waitFor(5*time.Second, func() string {
ns, err := c.tree()
if err != nil {
return err.Error()
}
for _, want := range []string{"复制选中行", "复制全部输出", "清空输出"} {
if _, ok := findNode(ns, want); !ok {
return "菜单缺「" + want + "」"
}
}
_, _ = saveShot(c, win, dir, "4-output-menu")
return ""
})
}
+1 -1
View File
@@ -1,5 +1,5 @@
// 一次性工具:命令行批量预热标准库文档翻译,直接写入用户缓存文件 // 一次性工具:命令行批量预热标准库文档翻译,直接写入用户缓存文件
//(%APPDATA%/mygoland/translations.json),IDE 启动装载后补全/悬停秒出中文。 // (%APPDATA%/mygoland/translations.json),IDE 启动装载后补全/悬停秒出中文。
// //
// 用法: // 用法:
// //
+39
View File
@@ -0,0 +1,39 @@
@echo off
setlocal
cd /d "%~dp0"
rem Pre-commit check shared by local builds and CI: gofmt, vet, test.
echo [1/3] gofmt ...
set "FMT=%TEMP%\mygoland-gofmt-%RANDOM%.txt"
gofmt -l . > "%FMT%" 2>&1
if errorlevel 1 (
type "%FMT%"
echo gofmt failed to run
del "%FMT%" >nul 2>&1
exit /b 1
)
findstr /r /c:"[^ ]" "%FMT%" >nul
if not errorlevel 1 (
echo Files need gofmt -w:
type "%FMT%"
del "%FMT%" >nul 2>&1
exit /b 1
)
del "%FMT%" >nul 2>&1
echo [2/3] go vet ./... ...
go vet ./...
if errorlevel 1 (
echo go vet failed
exit /b 1
)
echo [3/3] go test ./... -count=1 -timeout 480s ...
go test ./... -count=1 -timeout 480s
if errorlevel 1 (
echo tests failed
exit /b 1
)
echo VERIFY OK: gofmt / vet / test all green
exit /b 0