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

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

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

验证:build.cmd verify 全绿(286 个测试)、go run ./tools/e2e 两次 4/4、
GOOS=linux 交叉编译通过。
2026-11-12 16:36:02 +08:00

452 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package app
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/task"
)
// 覆盖率:跑 `go test -coverprofile`,把 coverprofile 解析成行区间,
// 用编辑器的 LineBackgrounds 给行铺底色(跑到的绿、没跑到的红)。
//
// coverprofile 的格式(每行一个块):
//
// 文件名:起始行.起始列,结束行.结束列 语句数 命中次数
// coverBlock 是 coverprofile 里的一个块。
type coverBlock struct {
Start, End int // 行号,1 起
Stmts int
Count int
}
// coverFile 是一个文件的覆盖率数据。
type coverFile struct {
Blocks []coverBlock
Total int // 语句总数
Hit int // 命中的语句数
}
// percent 返回覆盖率百分比。
func (f coverFile) percent() float64 {
if f.Total == 0 {
return 0
}
return float64(f.Hit) * 100 / float64(f.Total)
}
// coverState 是覆盖率面板的状态。
type coverState struct {
running bool
files map[string]coverFile // 键是小写规范化的绝对路径
all float64
total string // 整体一行摘要,显示在状态栏
// failMsg 非空表示这一轮 go test 有失败,覆盖率数字不可信;
// 详情已写进输出面板,界面上只放这一行摘要。
failMsg string
}
// parseCoverProfile 解析 coverprofile 文本。
func parseCoverProfile(text string) map[string]coverFile {
out := map[string]coverFile{}
sc := bufio.NewScanner(strings.NewReader(text))
sc.Buffer(make([]byte, 0, 64*1024), 8*1024*1024)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "mode:") {
continue
}
// name.go:3.14,5.2 2 1
colon := strings.LastIndex(line, ":")
if colon <= 0 {
continue
}
file := line[:colon]
rest := line[colon+1:]
fields := strings.Fields(rest)
if len(fields) < 3 {
continue
}
spans := strings.Split(fields[0], ",")
if len(spans) != 2 {
continue
}
startLine, err1 := lineOfSpan(spans[0])
endLine, err2 := lineOfSpan(spans[1])
if err1 != nil || err2 != nil {
continue
}
stmts, err3 := strconv.Atoi(fields[1])
count, err4 := strconv.Atoi(fields[2])
if err3 != nil || err4 != nil {
continue
}
key := coverKey(file)
f := out[key]
f.Blocks = append(f.Blocks, coverBlock{Start: startLine, End: endLine, Stmts: stmts, Count: count})
f.Total += stmts
if count > 0 {
f.Hit += stmts
}
out[key] = f
}
return out
}
// lineOfSpan 从 "12.5" 里取出行号 12。
func lineOfSpan(s string) (int, error) {
if i := strings.IndexByte(s, '.'); i >= 0 {
s = s[:i]
}
return strconv.Atoi(s)
}
// coverKey 把 coverprofile 里的路径规范化成 map 键。
//
// -coverprofile 里的文件名是「模块路径/包目录/文件」或者绝对路径,
// 统一按小写 + 正斜杠比较,避免 Windows 上大小写和分隔符差异。
func coverKey(p string) string {
return strings.ToLower(filepath.ToSlash(p))
}
// RunCoverage 跑覆盖率并刷新行底色。
func (a *App) RunCoverage() {
if a.root == "" {
a.alert("覆盖率", "先打开一个工作区。")
return
}
if a.cover.running {
return
}
out, err := os.CreateTemp("", "mygoland-cover-*.out")
if err != nil {
a.alert("覆盖率", err.Error())
return
}
path := out.Name()
out.Close()
defer os.Remove(path)
args := a.withTestFlags([]string{"test", "-coverprofile=" + path, "./..."})
t, err := task.Start(a.root, "go", args...)
if err != nil {
a.alert("覆盖率", err.Error())
return
}
a.cover.running = true
// 跑起来就把面板切到覆盖率页,用户不用自己找。
a.panel = true
a.panelTab = 6
if a.panelH < 240 {
a.panelH = 280
}
a.refresh()
go func() {
var lines []string
for line := range t.Lines {
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 {
if code != 0 {
a.appendOut("覆盖率失败:测试未通过,没有生成 coverprofile")
} else {
a.appendOut("覆盖率失败:没拿到 coverprofile")
}
a.refresh()
return
}
a.applyCoverage(string(data))
})
}()
}
// 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)
a.cover.files = files
var totalStmts, totalHit int
for _, f := range files {
totalStmts += f.Total
totalHit += f.Hit
}
if totalStmts > 0 {
a.cover.all = float64(totalHit) * 100 / float64(totalStmts)
a.cover.total = fmt.Sprintf("覆盖率 %.1f%%", a.cover.all)
}
a.applyCoverDecorations()
a.appendOut(fmt.Sprintf("覆盖率:%.1f%%(%d/%d 条语句)", a.cover.all, totalHit, totalStmts))
a.refresh()
}
// applyCoverDecorations 给每个打开的文档重新算行底色。
func (a *App) applyCoverDecorations() {
for _, d := range a.docs {
if d.st == nil {
continue
}
d.coverBG = a.coverBackgrounds(d)
}
}
// coverBackgrounds 生成一个文件的行底色。
func (a *App) coverBackgrounds(d *Doc) []editor.LineBackground {
if len(a.cover.files) == 0 {
return nil
}
f, ok := a.coverFor(d.path)
if !ok {
return nil
}
// 每一行取覆盖它所有块里「命中最差」的那个结果:
// 一行可能被拆成多块(比如 `if x { y() }`),有一块没跑到就算没覆盖。
hit := map[int]bool{}
seen := map[int]bool{}
for _, b := range f.Blocks {
for line := b.Start; line <= b.End; line++ {
seen[line] = true
if b.Count > 0 {
hit[line] = true
}
}
}
var out []editor.LineBackground
for line := range seen {
if line < 1 {
continue
}
c := a.th.Danger.Alpha(0.18)
if hit[line] {
c = a.th.Success.Alpha(0.20)
}
out = append(out, editor.LineBackground{First: line - 1, Last: line - 1, Color: c})
}
return out
}
// coverFor 找到某个文件对应的覆盖率数据。
//
// coverprofile 里的路径可能是「模块路径+包目录」的形式,所以按后缀匹配:
// 路径以「/pkg/dir/file.go」结尾就算同一个文件。
func (a *App) coverFor(path string) (coverFile, bool) {
slash := filepath.ToSlash(path)
for key, f := range a.cover.files {
if key == strings.ToLower(slash) {
return f, true
}
}
// 退一步按「包目录/文件名」后缀比,把两边都归一成 / 分隔。
norm := strings.ToLower(slash)
for key, f := range a.cover.files {
if strings.HasSuffix(norm, "/"+packageSuffix(key)) {
return f, true
}
}
return coverFile{}, false
}
// packageSuffix 取「包目录/文件名」这一段,用于后缀匹配。
func packageSuffix(key string) string {
parts := strings.Split(key, "/")
if len(parts) < 2 {
return key
}
return parts[len(parts)-2] + "/" + parts[len(parts)-1]
}
// clearCoverage 关掉覆盖率着色。
func (a *App) clearCoverage() {
a.cover = coverState{}
for _, d := range a.docs {
if d.st != nil {
d.coverBG = nil
}
}
a.refresh()
}
// coverStatText 是状态栏上的覆盖率摘要。
func (a *App) coverStatText(path string) string {
if len(a.cover.files) == 0 {
return ""
}
f, ok := a.coverFor(path)
if !ok {
return ""
}
return fmt.Sprintf("覆盖 %.0f%%", f.percent())
}
// coverageView 是面板里的「覆盖率」页签。
func (a *App) coverageView(c *ui.Context) {
t := c.Theme()
ui.Column(c).FillHeight().Children(func() {
ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center).
BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() {
if a.cover.total != "" {
ui.Text(c, a.cover.total).FontSize(11).TextColor(t.Text).SingleLine()
} else {
ui.Text(c, "还没有覆盖率数据").FontSize(11).TextColor(t.TextMuted)
}
ui.Box(c).Grow(1)
if a.cover.running {
ui.Text(c, "统计中…").FontSize(11).TextColor(t.Accent)
}
if ui.Button(c, "统计覆盖率").Clicked() {
a.RunCoverage()
}
if len(a.cover.files) > 0 && ui.Button(c, "清除").Clicked() {
a.clearCoverage()
}
})
// 上一轮测试没全过:数字不可信,先把话说明白,再给个去看日志的入口。
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).
TextColor(t.TextMuted)
})
return
}
// 按覆盖率从低到高排:最该补的地方排前面。
type row struct {
name string
pct float64
}
var rows []row
for key, f := range a.cover.files {
rows = append(rows, row{name: key, pct: f.percent()})
}
for i := 0; i < len(rows); i++ {
for j := i + 1; j < len(rows); j++ {
if rows[j].pct < rows[i].pct {
rows[i], rows[j] = rows[j], rows[i]
}
}
}
ui.Scroll(c).Grow(1).Children(func() {
ui.Column(c).Gap(1).Children(func() {
for _, r := range rows {
ui.Row(c).FillWidth().Padding(2, 10).Gap(10).Children(func() {
color := t.Success
if r.pct < 50 {
color = t.Danger
} else if r.pct < 80 {
color = t.Warning
}
ui.Textf(c, "%.0f%%", r.pct).FontSize(11).TextColor(color).Width(40)
ui.Text(c, r.name).FontSize(11).TextColor(t.TextMuted).SingleLine()
})
}
})
})
})
}