完成待办清单全部 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 项规划与完成索引。
This commit is contained in:
1 parent
d9db634066
commit
e408300324
21 files changed
+1515
-200
No files matched your search
+46
-137
@@ -1,129 +1,24 @@
|
|||||||
# MyGoland 待办与规划
|
# MyGoland 待办与规划
|
||||||
|
|
||||||
> 生于 2026-11-09,基线提交 `88067cc`(mygo v0.7.4);2026-11-12 升至 mygo v0.9.0。
|
> 生于 2026-11-09,基线提交 `88067cc`(mygo v0.7.4);2026-11-12 升至 mygo v0.9.0 并清空全部待办。
|
||||||
> 配套阅读:`MyGoland-完善度评估-2026-11-05.md`(缺陷证据与实测结论)、`MyGoland-vs-GoLand-差距分析.md`(对比视角)。
|
> 配套阅读:`MyGoland-完善度评估-2026-11-05.md`(缺陷证据与实测结论,已转为存档)、`MyGoland-vs-GoLand-差距分析.md`(对比视角)。
|
||||||
> 本文只记「还没做的」和「打算做的」——做完的项从本文删除,不在这里堆历史。
|
> 本文只记「还没做的」和「打算做的」——做完的项只留一行索引,不在这里堆历史。
|
||||||
|
|
||||||
## 现状
|
## 现状
|
||||||
|
|
||||||
评估报告「立刻做」4 项 + 「本周做」5 项 + 「规划做」第 10 项,共 10 项已全部实施;另加一次依赖升级,合计 11 项。
|
**待办 6 项已全部完成(2026-11-12)**,本文剩下的是「规划做」的新能力。
|
||||||
|
|
||||||
```
|
```
|
||||||
gofmt -l . 空
|
gofmt -l . 空
|
||||||
go build ./... OK
|
go build ./... OK
|
||||||
go vet ./... OK
|
go vet ./... OK
|
||||||
go test ./... 全绿,258 个 Test 函数
|
go test ./... 全绿,282 个 Test 函数
|
||||||
|
go test -race 新增并发/剪贴板/回滚用例无数据竞争
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 一、待办:有明确证据的缺陷(6 项)
|
## 一、规划:新能力(6 项)
|
||||||
|
|
||||||
按「影响 ÷ 成本」排序。每项都给了证据位置,动手前先照着复核一遍——评估报告里已有三次「没验证就下结论、复核后翻转」的前科。
|
|
||||||
|
|
||||||
### T1 移动目录/文件时不同步 `package` 与 import
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 现状 | `internal/app/fileops.go` 的移动操作只改磁盘,没有任何 Go 感知 |
|
|
||||||
| 影响 | Go 项目里移动一个包 = 整个仓库编译失败,且要手工改两处:目录内 `.go` 的 `package` 行、全仓引用它的 `import` 路径。这是本项目作为 Go IDE 最硬的一个缺口 |
|
|
||||||
| 粗估 | 1.5–2 天 |
|
|
||||||
| 优先级 | **最高**(唯一「用错了直接编译失败」的项) |
|
|
||||||
|
|
||||||
**前提已实测(2026-11-09,gopls v0.23.0)**:评估报告 4.13 写的「可基于 gopls rename 实现」**不成立**。实测 `initialize` 返回的 capabilities:
|
|
||||||
|
|
||||||
```
|
|
||||||
fileOperations: {"didCreate": {"filters": [{"scheme":"file","pattern":{"glob":"**/*.go"}}]}}
|
|
||||||
renameProvider: true
|
|
||||||
```
|
|
||||||
|
|
||||||
只有 `didCreate`,**没有 `willRename`/`didRename`**。也就是说 gopls 不会响应 `workspace/willRenameFiles`,这条路走不通。`renameProvider` 改的是符号引用,改不了包路径。
|
|
||||||
|
|
||||||
**可行路径**(全部在应用层完成,不需要 gopls):
|
|
||||||
|
|
||||||
1. 移动前先收集:目标目录下所有 `.go` 文件的 package 名;全工作区里 `import` 到旧路径的文件清单。
|
|
||||||
2. 移动后改写:目录内 `package` 行改成新目录名(要处理 `foo_test` 外部测试包后缀);`import` 用 AST 精确定位字符串字面量的位置再替换,别用正则——中文注释里出现同名路径会被误伤。
|
|
||||||
3. 用 `go/parser` + `token.FileSet` 拿到 `*ast.ImportSpec` 的 `Path.ValuePos`,按字节偏移改,最后 `gofmt` 收口。
|
|
||||||
4. 失败兜底:任一改写失败就整体回滚移动,不留半成品仓库。
|
|
||||||
|
|
||||||
**完成标准**:移动一个被多处引用的包后,`go build ./...` 直接通过;有单测覆盖「同包多文件」「外部测试包 `_test` 后缀」「import 别名」「相对路径不受影响」四种情况。
|
|
||||||
|
|
||||||
### T2 终端与输出/问题面板没有右键菜单
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 证据 | `openPop` 全库仅 4 个入口:`titlebar.go:84`(标题栏菜单)、`view.go:183`(+ 号)、`view.go:342`(文件树行)、`view.go:531`(标签页) |
|
|
||||||
| 影响 | 复制终端里的报错、清屏、重跑上一条命令,都得靠快捷键记忆 |
|
|
||||||
| 粗估 | 0.5 天 |
|
|
||||||
| 优先级 | 中 |
|
|
||||||
|
|
||||||
第 9 项把编辑器的右键补齐了(16 项),这两处是同一批里剩下的。终端建议「复制 / 粘贴 / 清屏 / 重启 Shell」;输出面板建议「复制全部 / 复制选中 / 清空」。
|
|
||||||
|
|
||||||
注意 `openPop(anchor ui.Element, ...)` 的第一个参数必须是**本帧的元素**——内部立刻取 `Bounds()` 只存矩形,跨帧用会 panic。文件树那处(`view.go:342`)是现成参照。
|
|
||||||
|
|
||||||
### T3 补全不支持 snippet 占位
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 证据 | `internal/lsp/protocol.go:305` `"snippetSupport": false` |
|
|
||||||
| 影响 | 函数补全后要手工补参数名,没有 Tab 逐项跳转 |
|
|
||||||
| 粗估 | 约 0.5 天(v0.9.0 补齐了框架侧,见下) |
|
|
||||||
| 优先级 | 中 |
|
|
||||||
|
|
||||||
**前提已变(2026-11-12,mygo v0.9.0)**:v0.7.4 时代的结论是「框架的 `CompletionSnippet` 只是图标分类,不解析占位、没有 Tab 跳转,得自己造轮子」。**这个结论在 v0.9.0 已经不成立**——上游补齐了:
|
|
||||||
|
|
||||||
| 新增 API | 作用 |
|
|
||||||
|---|---|
|
|
||||||
| `editor.ParseSnippet(source string) (*Snippet, error)` | 解析 `$1` / `${1:name}` / `$0`。支持同号共享默认值;嵌套占位、变量、choices、transform 返回错误 |
|
|
||||||
| `State.InsertSnippet(s *Snippet) bool` | 插入并选中第一个占位;Tab / Shift+Tab 依次跳,Esc、undo、外部改动结束会话 |
|
|
||||||
| `Completion.Snippet *Snippet` | 补全项可直接带模板,`Kind` 只选图标、不解释内容 |
|
|
||||||
|
|
||||||
所以 T3 从「1 天 + 可能要给上游提 PR」降级成**纯接线,约 0.5 天**:
|
|
||||||
|
|
||||||
1. `protocol.go:305` 改 `snippetSupport: true`;
|
|
||||||
2. 解析 gopls 的 `CompletionItem` 时看 `insertTextFormat == 2`,把 `textEdit.newText`(或 `insertText`)交给 `ParseSnippet`;
|
|
||||||
3. 解析成功就填 `Completion.Snippet`,失败(上游返回了我们不支持的 choices/transform)**降级成纯文本**,别整条丢掉——框架文档明确说这是预期用法;
|
|
||||||
4. 解析结果要缓存,别每帧 parse(官方示例就是 `var goSnippets` 包级变量预解析)。
|
|
||||||
|
|
||||||
gopls 的 `completionProvider.triggerCharacters` 实测只有 `["."]`,所以「输入 `(` 自动弹补全」仍是客户端行为,不要指望服务端。
|
|
||||||
|
|
||||||
### T4 本地历史超过 4MB 静默跳过
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 证据 | `internal/app/history.go:29` `histMaxSize = 4 << 20`;`history.go:62` `if len(data) == 0 \|\| len(data) > histMaxSize { return nil }` |
|
|
||||||
| 影响 | 大文件改坏后没有任何快照可回,且用户完全不知道 |
|
|
||||||
| 粗估 | 0.5 天 |
|
|
||||||
| 优先级 | 中低 |
|
|
||||||
|
|
||||||
最低成本的改法不是「提高上限」(磁盘会炸),而是**让静默变可见**:首次跳过时在输出面板记一行「`xxx.go` 超过 4MB,未纳入本地历史」。再进一步可以只存 diff 而不是全量快照,但那属于新功能。
|
|
||||||
|
|
||||||
### T5 全局搜索串行读盘
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 证据 | `internal/app/palette.go:256-265`,逐个文件 `os.Stat` + `os.ReadFile` |
|
|
||||||
| 附加静默行为 | `palette.go:259` `info.Size() > 512*1024` 直接 `continue`,**大文件被静默排除**(评估报告未记录这条) |
|
|
||||||
| 影响 | 仓库上万文件时延迟随文件数线性增长;有 220ms 去抖兜底,所以感知不算尖锐 |
|
|
||||||
| 粗估 | 1 天 |
|
|
||||||
| 优先级 | 低(工作区不大时可缓) |
|
|
||||||
|
|
||||||
改法:固定 `runtime.NumCPU()` 个 worker 消费文件 channel,用 `atomic` 计数 + 提前取消(命中上限就停),结果按文件序合并保证稳定。顺手把 512KB 的静默跳过也做成可见提示。
|
|
||||||
|
|
||||||
### T6 根目录残留验证文件
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
|---|---|
|
|
||||||
| 现状 | `MyGoland-e2e.exe~`(23 MB)、`e2e.sock`、`e2e_run1/2/4.sock`、`e2e_shot1/2/4.png` |
|
|
||||||
| 是否入库 | **否**。`git check-ignore` 确认 `*.exe~`、`*.sock`、`e2e_shot*.png` 都被挡住 |
|
|
||||||
| 影响 | 只占磁盘、干扰 `ls`,不影响仓库 |
|
|
||||||
| 成本 | 5 分钟 |
|
|
||||||
|
|
||||||
`.sock` 在 Windows 上可能删不掉(进程未退出时),先确认没有 e2e 实例在跑再删。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 二、规划:新能力(6 项)
|
|
||||||
|
|
||||||
这些不是缺陷,是「有更好」。
|
这些不是缺陷,是「有更好」。
|
||||||
|
|
||||||
@@ -133,20 +28,20 @@ gopls 的 `completionProvider.triggerCharacters` 实测只有 `["."]`,所以
|
|||||||
| P2 | **调试 watch + attach** | 有 DAP,无 watch 表达式、无 attach 到已有进程 | 并发与线上问题排查才需要 | 3 天 |
|
| P2 | **调试 watch + attach** | 有 DAP,无 watch 表达式、无 attach 到已有进程 | 并发与线上问题排查才需要 | 3 天 |
|
||||||
| P3 | **`-race` / `-bench` 开关** | 测试只跑普通模式 | 低代码量高价值,可提前 | 0.5 天 |
|
| P3 | **`-race` / `-bench` 开关** | 测试只跑普通模式 | 低代码量高价值,可提前 | 0.5 天 |
|
||||||
| P4 | **CI + e2e 冒烟 3–5 条** | 无 `.github/workflows`;e2e 通路(`-tags e2e` + `MYGO_AUTOMATION` + `tools/shot`)已通,但全靠手工 | 把「每次提交必须绿」变成机器守门 | 1–2 天 |
|
| P4 | **CI + e2e 冒烟 3–5 条** | 无 `.github/workflows`;e2e 通路(`-tags e2e` + `MYGO_AUTOMATION` + `tools/shot`)已通,但全靠手工 | 把「每次提交必须绿」变成机器守门 | 1–2 天 |
|
||||||
| P5 | **架构减债** | `App` struct 100 个字段(`app.go`);`testEvent` 248 行巨型 switch | 可维护性;新增功能时不再往 `app.go` 堆 | 1–2 天(分批,不宜大重构) |
|
| P5 | **架构减债** | `App` struct 100+ 字段(`app.go`);`testEvent` 248 行巨型 switch | 可维护性;新增功能时不再往 `app.go` 堆 | 1–2 天(分批,不宜大重构) |
|
||||||
| P6 | **多根工作区** | `startLSP(root)` 单 Root | 多模块/多仓库免开多窗口 | 3–5 天,收益不确定 |
|
| P6 | **多根工作区** | `startLSP(root)` 单 Root | 多模块/多仓库免开多窗口 | 3–5 天,收益不确定 |
|
||||||
|
|
||||||
**P4 的具体做法**(评估报告 6.8 已给方向):
|
**P4 的具体做法**(评估报告 6.8 已给方向):
|
||||||
|
|
||||||
1. `build.cmd` 加 `go vet ./... && go test ./... -timeout 480s`;
|
1. `build.cmd` 加 `go vet ./... && go test ./... -timeout 480s`;
|
||||||
2. 把手工 e2e 流程固化成 `tools/e2e/main.go` 场景脚本:起实例 → 发指令 → 截图 → 像素断言。先覆盖 3 条:波浪线出现、补全弹窗、标签右键;
|
2. 把手工 e2e 流程固化成 `tools/e2e/main.go` 场景脚本:起实例 → 发指令 → 截图 → 像素断言。可覆盖的现成场景:波浪线出现、补全弹窗、标签右键、**输出面板右键**(这个是自绘 `openPop`,automation 插座能截到)、**snippet 补全后光标停在括号内**;
|
||||||
3. ⚠️ **右键菜单不能走 automation 的 `input` 右击**——框架 `docs/plugins/automation.md` 明确说系统弹菜单进自己的事件循环、各平台无法统一选择。要用 `ui.Tester` 的 `RightClickAt`/`Menu()`/`ChooseMenuItem`,参照 `internal/app/editor_menu_test.go` 的 `TestEditorMenuShowsInEditor`。
|
3. ⚠️ **原生右键菜单不能走 automation 的 `input` 右击**——框架 `docs/plugins/automation.md` 明确说系统弹菜单进自己的事件循环、各平台无法统一选择。要用 `ui.Tester` 的 `RightClickAt`/`Menu()`/`ChooseMenuItem`,参照 `internal/app/editor_menu_test.go` 的 `TestEditorMenuShowsInEditor`。
|
||||||
|
|
||||||
**P5 的边界**:不建议现在做大重构(单人维护、重构收益低于功能收益)。只做两件低成本的事——按职责切 `App` 的字段组、把 `testEvent` 的巨型 switch 拆成 3–4 个函数。
|
**P5 的边界**:不建议现在做大重构(单人维护、重构收益低于功能收益)。只做两件低成本的事——按职责切 `App` 的字段组、把 `testEvent` 的巨型 switch 拆成 3–4 个函数。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 三、明确不做(沿用两份文档的判断,复核后仍成立)
|
## 二、明确不做(沿用两份文档的判断,复核后仍成立)
|
||||||
|
|
||||||
| 项目 | 理由 |
|
| 项目 | 理由 |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -161,7 +56,7 @@ gopls 的 `completionProvider.triggerCharacters` 实测只有 `["."]`,所以
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 四、验证基线
|
## 三、验证基线
|
||||||
|
|
||||||
任何一项做完,以下四条必须全绿才算完成:
|
任何一项做完,以下四条必须全绿才算完成:
|
||||||
|
|
||||||
@@ -169,41 +64,55 @@ gopls 的 `completionProvider.triggerCharacters` 实测只有 `["."]`,所以
|
|||||||
gofmt -l . # 必须为空
|
gofmt -l . # 必须为空
|
||||||
go build ./...
|
go build ./...
|
||||||
go vet ./...
|
go vet ./...
|
||||||
go test ./... -count=1 # 基线:258 个 Test 函数全过
|
go test ./... -count=1 # 基线:282 个 Test 函数全过
|
||||||
```
|
```
|
||||||
|
|
||||||
涉及 UI 的改动额外要求:`go build -tags e2e -o e2e.exe .` → `MYGO_AUTOMATION=<socket> ./e2e.exe` → `tools/shot` 截图,用像素采样或 `ViewImage` 确认,**不接受「看起来应该没问题」**。
|
涉及 UI 的改动额外要求:`go build -tags e2e -o e2e.exe .` → `MYGO_AUTOMATION=<socket> ./e2e.exe` → `tools/shot` 截图,用像素采样确认,**不接受「看起来应该没问题」**。
|
||||||
|
|
||||||
涉及第三方行为(gopls / 框架)的改动,**先写探测再改代码**。本文 T1、T3 的前提就是这么测出来的,两次都推翻了原报告的判断。
|
涉及第三方行为(gopls / 框架)的改动,**先写探测再改代码**。本轮 T1、T3 的前提都是这么测出来的,两次都改变了实施方案。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 五、建议顺序
|
## 四、建议顺序
|
||||||
|
|
||||||
| 批次 | 内容 | 累计 |
|
| 批次 | 内容 | 累计 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 第一批 | T6(清垃圾)+ T4 + T2 | 1 天 |
|
| 第一批 | P3(`-race`/`-bench`)+ P4(CI + e2e 冒烟) | 2 天 |
|
||||||
| 第二批 | T1(移动包同步,前提结论已有,直接开工) | +2 天 |
|
|
||||||
| 第三批 | P3(`-race`/`-bench`)+ P4(CI + e2e 冒烟) | +2 天 |
|
|
||||||
| 第四批 | T3(snippet 接线)+ T5(并行搜索) | +1.5 天 |
|
|
||||||
| 按需 | P1 / P2 / P5 / P6 | — |
|
| 按需 | P1 / P2 / P5 / P6 | — |
|
||||||
|
|
||||||
第一批里 T6 只是清磁盘,其余两项都是「把静默失败变可见」的同类问题,一起做思路连贯。
|
P4 优先:这一轮新增了 24 个测试函数和一条完整的新链路(移动包改写 → 磁盘 → 缓冲区 → snippet 补全),没有自动化守门的话,回归只能靠人记着跑。
|
||||||
|
|
||||||
第二批是这批里唯一会改变「用错就编译失败」的项,收益最高,且前提已经探明,不用再调研。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 附:三次「没验证就下结论」的教训
|
## 附 A:2026-11-12 完成的待办(仅索引)
|
||||||
|
|
||||||
评估报告里有三处判断在复核时翻转,全部记在文档里作为方法论警示:
|
| 项 | 落地位置 | 关键验证 |
|
||||||
|
|
||||||
| 原判断 | 实测结论 | 位置 |
|
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 编辑器没有右键菜单 | 框架自带,应用层只是没往里加东西 | 4.5 |
|
| T1 移动包同步 | `internal/app/movepkg.go` + `renameentry.go` | 临时 Go 模块里移目录后 `go build ./...` 直接通过;含回滚与中文注释误伤用例 |
|
||||||
| 「生成测试」取不到、零宽位置丢快速修复 | 都取得到;真问题是选区被忽略、浏览命令淹没 | 4.12 |
|
| T2 输出/问题面板右键 | `internal/app/panel_menu.go` + `output.go` | 真窗口右键截图,菜单贴指针弹出、无裁切 |
|
||||||
| 移动包「可基于 gopls rename 实现」 | gopls 不声明 `willRename`,得自己实现 | 本文 T1 |
|
| 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,无影响) |
|
||||||
|
|
||||||
共同点:**把「代码里没看到」当成「能力不存在」**。凡涉及第三方服务端行为,先写 20 行探测代码问它一句,比读十篇文档都准。
|
**两处刻意缩窄的范围**:
|
||||||
|
|
||||||
**补充(2026-11-12)**:「前提」有保质期。T3 那条「框架不支持 snippet」在写下三天后就因为 mygo 升到 v0.9.0 而失效——上游把 `ParseSnippet` / `InsertSnippet` 补上了。所以**升级依赖后要回头扫一遍待办里标注「前提」的项**,别拿旧结论继续估工时。
|
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: 68 KiB |
@@ -10,6 +10,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
@@ -258,6 +259,10 @@ type App struct {
|
|||||||
// 标题栏整体是 DragWindow,按钮自己的 Clicked 收不到事件,
|
// 标题栏整体是 DragWindow,按钮自己的 Clicked 收不到事件,
|
||||||
// 只能靠 PointerPosition 的命中来判断。
|
// 只能靠 PointerPosition 的命中来判断。
|
||||||
menuHits []menuHit
|
menuHits []menuHit
|
||||||
|
|
||||||
|
// histWarned 记下哪些文件已经提示过「超过本地历史上限」。
|
||||||
|
// 自动快照每分钟一次,不去重会把输出面板刷满;每个文件整个会话只提一次。
|
||||||
|
histWarned sync.Map
|
||||||
}
|
}
|
||||||
|
|
||||||
// New 创建一个未打开工作区的应用。
|
// New 创建一个未打开工作区的应用。
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
-3
@@ -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)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
@@ -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 未保存标记能写能读能清。
|
||||||
|
|||||||
+3
-1
@@ -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 补全类型。
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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("同名不该改")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -467,6 +467,9 @@ func (a *App) runView(c *ui.Context) {
|
|||||||
a.jumpTo(loc)
|
a.jumpTo(loc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if list.RightClicked() {
|
||||||
|
a.openListPop(list, a.outputMenuEntries())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// problemView 是「问题」页签的内容。
|
// problemView 是「问题」页签的内容。
|
||||||
@@ -505,6 +508,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 汇总所有已打开文件的诊断。
|
||||||
@@ -547,12 +553,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 画出一行输出。
|
||||||
|
|||||||
+122
-31
@@ -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
|
||||||
})
|
})
|
||||||
}()
|
}()
|
||||||
@@ -240,49 +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{}
|
||||||
}
|
}
|
||||||
|
if len(files) == 0 {
|
||||||
|
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))
|
||||||
|
info, err := os.Stat(abs)
|
||||||
|
if err != nil || info.Size() > 512*1024 {
|
||||||
|
per[i].tooLarge = 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(abs)
|
||||||
|
if err != nil || !utf8.Valid(data) {
|
||||||
|
per[i].unreadable = 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var hits []paletteItem
|
||||||
|
for ln, line := range strings.Split(string(data), "\n") {
|
||||||
|
if !match(line) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 按字符截断,别切坏中文(见 strutil.go 的注释)。
|
||||||
|
hits = append(hits, paletteItem{
|
||||||
|
Kind: itemLine,
|
||||||
|
Path: abs,
|
||||||
|
Line: ln + 1,
|
||||||
|
Label: rel,
|
||||||
|
Text: trimTo(strings.TrimSpace(line), 160),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
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 out []paletteItem
|
||||||
for _, rel := range files {
|
var stats searchStats
|
||||||
abs := filepath.Join(root, filepath.FromSlash(rel))
|
for i := range per {
|
||||||
info, err := os.Stat(abs)
|
stats.tooLarge += per[i].tooLarge
|
||||||
if err != nil || info.Size() > 512*1024 {
|
stats.unreadable += per[i].unreadable
|
||||||
continue
|
for _, it := range per[i].items {
|
||||||
}
|
out = append(out, it)
|
||||||
data, err := os.ReadFile(abs)
|
|
||||||
if err != nil || !utf8.Valid(data) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for i, line := range strings.Split(string(data), "\n") {
|
|
||||||
if !match(line) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// 按字符截断,别切坏中文(见 strutil.go 的注释)。
|
|
||||||
trimmed := trimTo(strings.TrimSpace(line), 160)
|
|
||||||
out = append(out, paletteItem{
|
|
||||||
Kind: itemLine,
|
|
||||||
Path: abs,
|
|
||||||
Line: i + 1,
|
|
||||||
Label: rel,
|
|
||||||
Hint: "",
|
|
||||||
Text: trimmed,
|
|
||||||
})
|
|
||||||
if len(out) >= limit {
|
if len(out) >= limit {
|
||||||
return out
|
return out, stats
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out
|
return out, stats
|
||||||
}
|
}
|
||||||
|
|
||||||
// moveSel 上下移动选中项。
|
// moveSel 上下移动选中项。
|
||||||
@@ -428,6 +515,10 @@ func (a *App) paletteView(c *ui.Context) {
|
|||||||
ui.Textf(c, "索引已截断至 %d 个文件", indexFileCap).
|
ui.Textf(c, "索引已截断至 %d 个文件", indexFileCap).
|
||||||
FontSize(10).TextColor(t.Warning)
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -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())
|
}
|
||||||
return
|
if renameErr != nil {
|
||||||
}
|
a.alert("重命名失败", renameErr.Error())
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
a.afterRename(old, target)
|
if err := a.applyGoMoveEdits(edits); err != nil {
|
||||||
|
// 内容同步失败就把移动也退回去,别留下一个编译不过的仓库。
|
||||||
|
_ = os.Rename(target, old)
|
||||||
|
a.alert("移动失败", "已回滚文件移动;同步 import 时出错:"+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
a.afterRename(old, target) // 先把内存里的路径搬到新位置
|
||||||
|
a.syncGoMoveBuffers(edits)
|
||||||
a.win.Update(func() {})
|
a.win.Update(func() {})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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))])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,14 +85,15 @@ func (m *MarkupContent) UnmarshalJSON(b []byte) error {
|
|||||||
|
|
||||||
// CompletionItem 是一条补全建议。
|
// CompletionItem 是一条补全建议。
|
||||||
type CompletionItem struct {
|
type CompletionItem struct {
|
||||||
Label string `json:"label"`
|
Label string `json:"label"`
|
||||||
Kind int `json:"kind"`
|
Kind int `json:"kind"`
|
||||||
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"`
|
||||||
TextEdit *TextEdit `json:"textEdit"`
|
InsertTextFormat int `json:"insertTextFormat"` // 1=纯文本 2=snippet
|
||||||
FilterText string `json:"filterText"`
|
TextEdit *TextEdit `json:"textEdit"`
|
||||||
SortText string `json:"sortText"`
|
FilterText string `json:"filterText"`
|
||||||
|
SortText string `json:"sortText"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CompletionList 是补全结果的一种包装。
|
// CompletionList 是补全结果的一种包装。
|
||||||
@@ -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,
|
||||||
|
|||||||
Reference in new issue
Block a user