diff --git a/.gitignore b/.gitignore index 4e39f16..50bb191 100644 --- a/.gitignore +++ b/.gitignore @@ -9,5 +9,8 @@ __debug_bin* *.sock e2e_shot*.png +# 本地临时验证目录(e2e 构建、截图、验证脚本) +.tmp/ + # WorkBuddy 本地工作区数据(记忆/日志,不入库) .workbuddy/ diff --git a/docs/plans/2026-10-29-mygoland-design.md b/docs/plans/2026-10-29-mygoland-design.md index 28d4e54..2d2bf3c 100644 --- a/docs/plans/2026-10-29-mygoland-design.md +++ b/docs/plans/2026-10-29-mygoland-design.md @@ -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` 的判断。) + +新增 `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 文件名。 diff --git a/internal/app/coverage.go b/internal/app/coverage.go index 73a1ad7..600b713 100644 --- a/internal/app/coverage.go +++ b/internal/app/coverage.go @@ -49,6 +49,9 @@ type coverState struct { files map[string]coverFile // 键是小写规范化的绝对路径 all float64 total string // 整体一行摘要,显示在状态栏 + // failMsg 非空表示这一轮 go test 有失败,覆盖率数字不可信; + // 详情已写进输出面板,界面上只放这一行摘要。 + failMsg string } // parseCoverProfile 解析 coverprofile 文本。 @@ -153,20 +156,101 @@ func (a *App) RunCoverage() { lines = append(lines, line) } t.Wait() + // Task.Wait 没有返回值,退出状态只能从 ExitCode 取(未结束是 -1)。 + code := t.ExitCode() data, readErr := os.ReadFile(path) a.win.Update(func() { 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 { - a.appendOut("覆盖率失败:没拿到 coverprofile") + if code != 0 { + a.appendOut("覆盖率失败:测试未通过,没有生成 coverprofile") + } else { + a.appendOut("覆盖率失败:没拿到 coverprofile") + } a.refresh() return } 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 套到打开的文件上。 func (a *App) applyCoverage(text string) { files := parseCoverProfile(text) @@ -308,6 +392,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 { ui.Column(c).Grow(1).FillHeight().Center().Children(func() { ui.Text(c, "点「统计覆盖率」跑一遍 go test -coverprofile").FontSize(12). diff --git a/internal/app/coverage_test.go b/internal/app/coverage_test.go index 2e3510b..218310c 100644 --- a/internal/app/coverage_test.go +++ b/internal/app/coverage_test.go @@ -1,6 +1,7 @@ package app import ( + "strings" "testing" "github.com/egoist/mygo/ui" @@ -91,3 +92,90 @@ func TestCoverStatText(t *testing.T) { 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) + } +} diff --git a/internal/app/gitlog.go b/internal/app/gitlog.go index b242eea..4879f7a 100644 --- a/internal/app/gitlog.go +++ b/internal/app/gitlog.go @@ -1,10 +1 @@ package app - -// trimTo 把字符串截断到 n 个字符,历史列表里的标题用。 -func trimTo(s string, n int) string { - r := []rune(s) - if len(r) <= n { - return s - } - return string(r[:n]) + "…" -} diff --git a/internal/app/grep.go b/internal/app/grep.go index 0d5400c..f2cf7ba 100644 --- a/internal/app/grep.go +++ b/internal/app/grep.go @@ -10,38 +10,54 @@ import ( // 文件名索引与模糊匹配,供快速打开使用。 +// indexFileCap 是文件索引的规模上限。超过就截断并置 indexState.truncated, +// 界面据此提示——静默截断会让用户以为「搜不到就是没有」。 +const indexFileCap = 20000 + // indexState 是工作区文件索引。 type indexState struct { - mu sync.Mutex - root string - files []string // 相对路径,正斜杠 - ready bool + mu sync.Mutex + root string + files []string // 相对路径,正斜杠 + ready bool + truncated bool // 是否因超过 indexFileCap 被截断 } // buildIndex 在后台遍历工作区,收集可打开的文件。 +// +// 跳过规则有三层:内置目录(.git/vendor/dist…)、根 .gitignore、 +// 生成物后缀(.exe/.test)。vendor 必须跳过——一个 Go 项目的 vendor +// 能塞几千个包,进索引后快速打开与全局搜索全是第三方噪音。 func (a *App) buildIndex(root string) { + rules := loadIgnoreRules(root) go func() { var files []string + truncated := false _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { if err != nil { return nil } name := d.Name() + rel, relErr := filepath.Rel(root, p) + relSlash := "" + if relErr == nil { + relSlash = filepath.ToSlash(rel) + } if d.IsDir() { - if p != root && skipDir(name) { + if p != root && (isBuiltinSkipDir(name) || rules.match(relSlash, true)) { return filepath.SkipDir } return nil } - if skipFile(name) { + if skipFile(name) || rules.match(relSlash, false) { return nil } - rel, err := filepath.Rel(root, p) - if err != nil { + if relErr != nil { return nil } - files = append(files, filepath.ToSlash(rel)) - if len(files) > 20000 { + files = append(files, relSlash) + if len(files) > indexFileCap { + truncated = true return filepath.SkipAll } return nil @@ -51,6 +67,7 @@ func (a *App) buildIndex(root string) { if a.index.root == root { a.index.files = files a.index.ready = true + a.index.truncated = truncated } a.index.mu.Unlock() }() @@ -72,6 +89,14 @@ func (a *App) indexSnapshot() ([]string, bool) { 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 的子序列,并给出一个分数(越大越靠前)。 // // 规则很朴素:连续匹配、匹配到文件名部分、匹配位置靠前,都会加分。 diff --git a/internal/app/ignore.go b/internal/app/ignore.go new file mode 100644 index 0000000..bd8703e --- /dev/null +++ b/internal/app/ignore.go @@ -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 +} diff --git a/internal/app/ignore_test.go b/internal/app/ignore_test.go new file mode 100644 index 0000000..d82733d --- /dev/null +++ b/internal/app/ignore_test.go @@ -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) + } +} diff --git a/internal/app/palette.go b/internal/app/palette.go index 8f42845..2e56ea1 100644 --- a/internal/app/palette.go +++ b/internal/app/palette.go @@ -209,24 +209,30 @@ func (a *App) workspaceFiles() []string { if files, ready := a.indexSnapshot(); ready { return files } + rules := loadIgnoreRules(root) var files []string _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { if err != nil { return nil } + rel, relErr := filepath.Rel(root, p) + relSlash := "" + if relErr == nil { + relSlash = filepath.ToSlash(rel) + } if d.IsDir() { - if p != root && skipDir(d.Name()) { + if p != root && (isBuiltinSkipDir(d.Name()) || rules.match(relSlash, true)) { return filepath.SkipDir } return nil } - if skipFile(d.Name()) { + if skipFile(d.Name()) || rules.match(relSlash, false) { return nil } - if rel, err := filepath.Rel(root, p); err == nil { - files = append(files, filepath.ToSlash(rel)) + if relErr == nil { + files = append(files, relSlash) } - if len(files) > 20000 { + if len(files) > indexFileCap { return filepath.SkipAll } return nil @@ -261,10 +267,8 @@ func (a *App) searchInWorkspace(query string, limit int, o searchOpts) []palette if !match(line) { continue } - trimmed := strings.TrimSpace(line) - if len(trimmed) > 160 { - trimmed = trimmed[:160] + "…" - } + // 按字符截断,别切坏中文(见 strutil.go 的注释)。 + trimmed := trimTo(strings.TrimSpace(line), 160) out = append(out, paletteItem{ Kind: itemLine, Path: abs, @@ -419,6 +423,11 @@ func (a *App) paletteView(c *ui.Context) { ui.Text(c, "Enter 打开").FontSize(10).TextColor(t.TextMuted) ui.Text(c, "Esc 关闭").FontSize(10).TextColor(t.TextMuted) ui.Box(c).Grow(1) + // 索引被上限截断时说一声:否则「搜不到」会被当成「不存在」。 + if !a.pal.search && a.indexTruncated() { + ui.Textf(c, "索引已截断至 %d 个文件", indexFileCap). + FontSize(10).TextColor(t.Warning) + } if n := len(a.pal.items); n > 0 { ui.Textf(c, "%d 项", n).FontSize(10).TextColor(t.TextMuted) } diff --git a/internal/app/rename.go b/internal/app/rename.go index 5e00c82..6b4d949 100644 --- a/internal/app/rename.go +++ b/internal/app/rename.go @@ -82,10 +82,7 @@ func linePreview(path string, line int) string { return "" } s := strings.TrimSpace(lines[line-1]) - if len(s) > 140 { - s = s[:140] + "…" - } - return s + return trimTo(s, 140) } // RenameSymbol 打开重命名弹窗,光标处的词作为默认值。 diff --git a/internal/app/strutil.go b/internal/app/strutil.go new file mode 100644 index 0000000..6146ab7 --- /dev/null +++ b/internal/app/strutil.go @@ -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]) + "…" +} diff --git a/internal/app/strutil_test.go b/internal/app/strutil_test.go new file mode 100644 index 0000000..3dc49fe --- /dev/null +++ b/internal/app/strutil_test.go @@ -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) + } +} diff --git a/internal/app/tabmenu_test.go b/internal/app/tabmenu_test.go new file mode 100644 index 0000000..612f668 --- /dev/null +++ b/internal/app/tabmenu_test.go @@ -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) +} diff --git a/internal/app/view.go b/internal/app/view.go index f6a5320..0729096 100644 --- a/internal/app/view.go +++ b/internal/app/view.go @@ -519,6 +519,13 @@ func (a *App) tabBar(c *ui.Context) { open := ui.ButtonBase(c).Padding(3, 7).Children(func() { 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() { a.active = d.path }