-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.go
335 lines (317 loc) · 8.33 KB
/
convert.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// Copyright (c) 2013 The Gocov Authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package gocov
import (
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"regexp"
"golang.org/x/tools/cover"
)
func ConvertProfiles(filenames ...string) error {
err := ConvertProfilesWithOutput(filenames, os.Stdout)
if err != nil {
return err
}
fmt.Println()
return nil
}
func ConvertProfilesWithOutput(filenames []string, output io.Writer, excludePatterns ...*regexp.Regexp) error {
var ps Packages
for i := range filenames {
converter := converter{
packages: make(map[string]*Package),
}
profiles, err := cover.ParseProfiles(filenames[i])
if err != nil {
return err
}
exclude := func(s string) bool {
for _, p := range excludePatterns {
if p.MatchString(s) {
return true
}
}
return false
}
for _, p := range profiles {
if !exclude(p.FileName) {
if err := converter.convertProfile(p); err != nil {
return err
}
}
}
for _, pkg := range converter.packages {
ps.AddPackage(pkg)
}
}
bytes, err := marshalJson(ps)
if err != nil {
return err
}
_, err = output.Write(bytes)
if err != nil {
return err
}
return nil
}
type converter struct {
packages map[string]*Package
}
// wrapper for gocov.Statement
type statement struct {
*Statement
*StmtExtent
}
func (c *converter) convertProfile(p *cover.Profile) error {
file, pkgpath, err := findFile(p.FileName)
if err != nil {
return err
}
pkg := c.packages[pkgpath]
if pkg == nil {
pkg = &Package{Name: pkgpath}
c.packages[pkgpath] = pkg
}
// Find function and statement extents; create corresponding
// gocov.Functions and gocov.Statements, and keep a separate
// slice of gocov.Statements so we can match them with profile
// blocks.
extents, err := findFuncs(file)
if err != nil {
return err
}
var stmts []statement
for _, fe := range extents {
f := &Function{
Name: fe.name,
File: file,
Start: fe.startOffset,
End: fe.endOffset,
}
for _, se := range fe.stmts {
s := statement{
Statement: &Statement{Start: se.startOffset, End: se.endOffset},
StmtExtent: se,
}
f.Statements = append(f.Statements, s.Statement)
stmts = append(stmts, s)
}
pkg.Functions = append(pkg.Functions, f)
}
// For each profile block in the file, find the statement(s) it
// covers and increment the Reached field(s).
blocks := p.Blocks
for _, s := range stmts {
for i, b := range blocks {
if b.StartLine > s.endLine || (b.StartLine == s.endLine && b.StartCol >= s.endCol) {
// Past the end of the statement
blocks = blocks[i:]
break
}
if b.EndLine < s.startLine || (b.EndLine == s.startLine && b.EndCol <= s.startCol) {
// Before the beginning of the statement
continue
}
s.Reached += int64(b.Count)
break
}
}
return nil
}
// findFile finds the location of the named file in GOROOT, GOPATH etc.
func findFile(file string) (filename string, pkgpath string, err error) {
dir, file := filepath.Split(file)
if dir != "" {
dir = dir[:len(dir)-1] // drop trailing '/'
}
pkg, err := build.Import(dir, ".", build.FindOnly)
if err != nil {
return "", "", fmt.Errorf("can't find %q: %v", file, err)
}
return filepath.Join(pkg.Dir, file), pkg.ImportPath, nil
}
// findFuncs parses the file and returns a slice of FuncExtent descriptors.
func findFuncs(name string) ([]*FuncExtent, error) {
fset := token.NewFileSet()
parsedFile, err := parser.ParseFile(fset, name, nil, 0)
if err != nil {
return nil, err
}
visitor := &FuncVisitor{fset: fset}
ast.Walk(visitor, parsedFile)
return visitor.funcs, nil
}
type extent struct {
startOffset int
startLine int
startCol int
endOffset int
endLine int
endCol int
}
// FuncExtent describes a function's extent in the source by file and position.
type FuncExtent struct {
extent
name string
stmts []*StmtExtent
}
// StmtExtent describes a statements's extent in the source by file and position.
type StmtExtent extent
// FuncVisitor implements the visitor that builds the function position list for a file.
type FuncVisitor struct {
fset *token.FileSet
funcs []*FuncExtent
}
// Visit implements the ast.Visitor interface.
func (v *FuncVisitor) Visit(node ast.Node) ast.Visitor {
var body *ast.BlockStmt
var name string
switch n := node.(type) {
case *ast.FuncLit:
body = n.Body
case *ast.FuncDecl:
body = n.Body
name = n.Name.Name
// Function name is prepended with "T." if there is a receiver, where
// T is the type of the receiver, dereferenced if it is a pointer.
if n.Recv != nil {
field := n.Recv.List[0]
switch recv := field.Type.(type) {
case *ast.StarExpr:
name = recv.X.(*ast.Ident).Name + "." + name
case *ast.Ident:
name = recv.Name + "." + name
}
}
}
if body != nil {
start := v.fset.Position(node.Pos())
end := v.fset.Position(node.End())
if name == "" {
name = fmt.Sprintf("@%d:%d", start.Line, start.Column)
}
fe := &FuncExtent{
name: name,
extent: extent{
startOffset: start.Offset,
startLine: start.Line,
startCol: start.Column,
endOffset: end.Offset,
endLine: end.Line,
endCol: end.Column,
},
}
v.funcs = append(v.funcs, fe)
sv := StmtVisitor{fset: v.fset, function: fe}
sv.VisitStmt(body)
}
return v
}
type StmtVisitor struct {
fset *token.FileSet
function *FuncExtent
}
func (v *StmtVisitor) VisitStmt(s ast.Stmt) {
var statements *[]ast.Stmt
switch s := s.(type) {
case *ast.BlockStmt:
statements = &s.List
case *ast.CaseClause:
statements = &s.Body
case *ast.CommClause:
statements = &s.Body
case *ast.ForStmt:
if s.Init != nil {
v.VisitStmt(s.Init)
}
if s.Post != nil {
v.VisitStmt(s.Post)
}
v.VisitStmt(s.Body)
case *ast.IfStmt:
if s.Init != nil {
v.VisitStmt(s.Init)
}
v.VisitStmt(s.Body)
if s.Else != nil {
// Code copied from go.tools/cmd/cover, to deal with "if x {} else if y {}"
const backupToElse = token.Pos(len("else ")) // The AST doesn't remember the else location. We can make an accurate guess.
switch stmt := s.Else.(type) {
case *ast.IfStmt:
block := &ast.BlockStmt{
Lbrace: stmt.If - backupToElse, // So the covered part looks like it starts at the "else".
List: []ast.Stmt{stmt},
Rbrace: stmt.End(),
}
s.Else = block
case *ast.BlockStmt:
stmt.Lbrace -= backupToElse // So the block looks like it starts at the "else".
default:
panic("unexpected node type in if")
}
v.VisitStmt(s.Else)
}
case *ast.LabeledStmt:
v.VisitStmt(s.Stmt)
case *ast.RangeStmt:
v.VisitStmt(s.Body)
case *ast.SelectStmt:
v.VisitStmt(s.Body)
case *ast.SwitchStmt:
if s.Init != nil {
v.VisitStmt(s.Init)
}
v.VisitStmt(s.Body)
case *ast.TypeSwitchStmt:
if s.Init != nil {
v.VisitStmt(s.Init)
}
v.VisitStmt(s.Assign)
v.VisitStmt(s.Body)
}
if statements == nil {
return
}
for i := 0; i < len(*statements); i++ {
s := (*statements)[i]
switch s.(type) {
case *ast.CaseClause, *ast.CommClause, *ast.BlockStmt:
break
default:
start, end := v.fset.Position(s.Pos()), v.fset.Position(s.End())
se := &StmtExtent{
startOffset: start.Offset,
startLine: start.Line,
startCol: start.Column,
endOffset: end.Offset,
endLine: end.Line,
endCol: end.Column,
}
v.function.stmts = append(v.function.stmts, se)
}
v.VisitStmt(s)
}
}