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 // 整体一行摘要,显示在状态栏 } // 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) t, err := task.Start(a.root, "go", "test", "-coverprofile="+path, "./...") 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() data, readErr := os.ReadFile(path) a.win.Update(func() { a.cover.running = false if readErr != nil { a.appendOut("覆盖率失败:没拿到 coverprofile") a.refresh() return } a.applyCoverage(string(data)) }) _ = lines }() } // 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 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() }) } }) }) }) }