-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
cover.go
259 lines (206 loc) · 5.83 KB
/
cover.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package coverage
import (
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"golang.org/x/tools/cover"
)
const IgnoreText = "coverage-ignore"
type Config struct {
Profiles []string
LocalPrefix string
ExcludePaths []string
}
func GenerateCoverageStats(cfg Config) ([]Stats, error) {
profiles, err := parseProfiles(cfg.Profiles)
if err != nil {
return nil, fmt.Errorf("parsing profiles: %w", err)
}
fileStats := make([]Stats, 0, len(profiles))
excludeRules := compileExcludePathRules(cfg.ExcludePaths)
for _, profile := range profiles {
file, noPrefixName, err := findFile(profile.FileName, cfg.LocalPrefix)
if err != nil {
return nil, fmt.Errorf("could not find file [%s]: %w", profile.FileName, err)
}
if ok := matches(excludeRules, noPrefixName); ok {
continue // this file is excluded
}
source, err := os.ReadFile(file)
if err != nil { // coverage-ignore
return nil, fmt.Errorf("failed reading file source [%s]: %w", profile.FileName, err)
}
funcs, blocks, err := findFuncsAndBlocks(source)
if err != nil { // coverage-ignore
return nil, err
}
annotations, err := findAnnotations(source)
if err != nil { // coverage-ignore
return nil, err
}
s := coverageForFile(profile, funcs, blocks, annotations)
if s.Total == 0 {
// do not include files that doesn't have statements
// this can happen when everything is excluded with comment annotations, or
// simply file doesn't have any statement
continue
}
s.Name = noPrefixName
fileStats = append(fileStats, s)
}
return fileStats, nil
}
// findFile finds the location of the named file in GOROOT, GOPATH etc.
func findFile(file, prefix string) (string, string, error) {
profileFile := file
noPrefixName := stripPrefix(file, prefix)
if _, err := os.Stat(noPrefixName); err == nil { // coverage-ignore
return noPrefixName, noPrefixName, nil
}
dir, file := filepath.Split(file)
pkg, err := build.Import(dir, ".", build.FindOnly)
if err != nil {
return "", "", fmt.Errorf("can't find file %q: %w", profileFile, err)
}
file = filepath.Join(pkg.Dir, file)
if _, err := os.Stat(file); err == nil {
return file, stripPrefix(file, pkg.Root), nil
}
return "", "", fmt.Errorf("can't find file %q", profileFile)
}
func findAnnotations(source []byte) ([]extent, error) {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, "", source, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("can't parse comments: %w", err)
}
var res []extent
for _, c := range node.Comments {
if strings.Contains(c.Text(), IgnoreText) {
res = append(res, newExtent(fset, c))
}
}
return res, nil
}
func findFuncsAndBlocks(source []byte) ([]extent, []extent, error) {
fset := token.NewFileSet()
parsedFile, err := parser.ParseFile(fset, "", source, 0)
if err != nil {
return nil, nil, fmt.Errorf("can't parse source: %w", err)
}
v := &visitor{fset: fset}
ast.Walk(v, parsedFile)
return v.funcs, v.blocks, nil
}
type visitor struct {
fset *token.FileSet
funcs []extent
blocks []extent
}
// Visit implements the ast.Visitor interface.
func (v *visitor) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.FuncDecl:
v.funcs = append(v.funcs, newExtent(v.fset, n.Body))
case *ast.IfStmt:
v.addBlock(n.Body)
case *ast.SwitchStmt:
v.addBlock(n.Body)
case *ast.TypeSwitchStmt:
v.addBlock(n.Body)
case *ast.SelectStmt: // coverage-ignore
v.addBlock(n.Body)
case *ast.ForStmt:
v.addBlock(n.Body)
case *ast.RangeStmt:
v.addBlock(n.Body)
}
return v
}
func (v *visitor) addBlock(n ast.Node) {
v.blocks = append(v.blocks, newExtent(v.fset, n))
}
type extent struct {
StartLine int
StartCol int
EndLine int
EndCol int
}
func newExtent(fset *token.FileSet, n ast.Node) extent {
start := fset.Position(n.Pos())
end := fset.Position(n.End())
return extent{
StartLine: start.Line,
StartCol: start.Column,
EndLine: end.Line,
EndCol: end.Column,
}
}
func findExtentWithStartLine(ee []extent, line int) (extent, bool) {
for _, e := range ee {
if e.StartLine <= line && e.EndLine >= line {
return e, true
}
}
return extent{}, false
}
func hasExtentWithStartLine(ee []extent, startLine int) bool {
_, found := findExtentWithStartLine(ee, startLine)
return found
}
func coverageForFile(profile *cover.Profile, funcs, blocks, annotations []extent) Stats {
s := Stats{}
for _, f := range funcs {
c, t := coverage(profile, f, blocks, annotations)
s.Total += t
s.Covered += c
}
return s
}
// coverage returns the fraction of the statements in the
// function that were covered, as a numerator and denominator.
//
//nolint:cyclop,gocognit // relax
func coverage(profile *cover.Profile, f extent, blocks, annotations []extent) (int64, int64) {
if hasExtentWithStartLine(annotations, f.StartLine) {
// case when entire function is ignored
return 0, 0
}
var (
covered, total int64
skip extent
)
// the blocks are sorted, so we can stop counting as soon as
// we reach the end of the relevant block.
for _, b := range profile.Blocks {
if b.StartLine > f.EndLine || (b.StartLine == f.EndLine && b.StartCol >= f.EndCol) {
// past the end of the function.
break
}
if b.EndLine < f.StartLine || (b.EndLine == f.StartLine && b.EndCol <= f.StartCol) {
// before the beginning of the function
continue
}
if b.StartLine < skip.EndLine || (b.EndLine == f.StartLine && b.StartCol <= skip.EndCol) {
// this block has comment annotation
continue
}
// add block to coverage statistics only if it was not ignored using comment annotations
if hasExtentWithStartLine(annotations, b.StartLine) {
if e, found := findExtentWithStartLine(blocks, b.StartLine); found {
skip = e
}
continue
}
total += int64(b.NumStmt)
if b.Count > 0 {
covered += int64(b.NumStmt)
}
}
return covered, total
}