forked from t-yuki/gocover-cobertura
/
gocover-cobertura.go
192 lines (170 loc) · 4.4 KB
/
gocover-cobertura.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
package main
import (
"encoding/xml"
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"strings"
"time"
)
const coberturaDTDDecl = "<!DOCTYPE coverage SYSTEM \"http://cobertura.sourceforge.net/xml/coverage-04.dtd\">\n"
var replacePath string
var withPath string
func init() {
flag.StringVar(&replacePath, "replace", "", "Replace path")
flag.StringVar(&withPath, "with", "", "With path")
}
func main() {
flag.Parse()
convert(os.Stdin, os.Stdout)
}
func convert(in io.Reader, out io.Writer) {
profiles, err := ParseProfiles(in)
if err != nil {
panic("Can't parse profiles")
}
srcDirs := build.Default.SrcDirs()
sources := make([]*Source, len(srcDirs)+1)
for i, dir := range srcDirs {
sources[i] = &Source{dir}
}
sources[len(srcDirs)] = &Source{"/"}
coverage := Coverage{Sources: sources, Packages: nil, Timestamp: time.Now().UnixNano() / int64(time.Millisecond)}
coverage.parseProfiles(profiles)
fmt.Fprintf(out, xml.Header)
fmt.Fprintf(out, coberturaDTDDecl)
encoder := xml.NewEncoder(out)
encoder.Indent("", "\t")
err = encoder.Encode(coverage)
if err != nil {
panic(err)
}
fmt.Fprintln(out)
}
func (cov *Coverage) parseProfiles(profiles []*Profile) error {
cov.Packages = []*Package{}
for _, profile := range profiles {
cov.parseProfile(profile)
}
cov.LinesValid = cov.NumLines()
cov.LinesCovered = cov.NumLinesWithHits()
cov.LineRate = cov.HitRate()
return nil
}
func (cov *Coverage) parseProfile(profile *Profile) (err error) {
fileName := profile.FileName
var absFilePath string
if replacePath != "" {
absFilePath = strings.ReplaceAll(fileName, replacePath, withPath)
} else {
absFilePath, err = findFile(fileName)
if err != nil {
return err
}
}
fset := token.NewFileSet()
parsed, err := parser.ParseFile(fset, absFilePath, nil, 0)
if err != nil {
return err
}
data, err := os.ReadFile(absFilePath)
if err != nil {
return err
}
pkgPath, _ := filepath.Split(fileName)
pkgPath = strings.TrimRight(pkgPath, string(os.PathSeparator))
var pkg *Package
for _, p := range cov.Packages {
if p.Name == pkgPath {
pkg = p
}
}
if pkg == nil {
pkg = &Package{Name: pkgPath, Classes: []*Class{}}
cov.Packages = append(cov.Packages, pkg)
}
visitor := &fileVisitor{
fset: fset,
fileName: absFilePath,
fileData: data,
classes: make(map[string]*Class),
pkg: pkg,
profile: profile,
}
ast.Walk(visitor, parsed)
pkg.LineRate = pkg.HitRate()
return nil
}
type fileVisitor struct {
fset *token.FileSet
fileName string
fileData []byte
pkg *Package
classes map[string]*Class
profile *Profile
}
func (v *fileVisitor) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.FuncDecl:
class := v.class(n)
method := v.method(n)
method.LineRate = method.Lines.HitRate()
class.Methods = append(class.Methods, method)
for _, line := range method.Lines {
class.Lines = append(class.Lines, line)
}
class.LineRate = class.Lines.HitRate()
}
return v
}
func (v *fileVisitor) method(n *ast.FuncDecl) *Method {
method := &Method{Name: n.Name.Name}
method.Lines = []*Line{}
start := v.fset.Position(n.Pos())
end := v.fset.Position(n.End())
startLine := start.Line
startCol := start.Column
endLine := end.Line
endCol := end.Column
// The blocks are sorted, so we can stop counting as soon as we reach the end of the relevant block.
for _, b := range v.profile.Blocks {
if b.StartLine > endLine || (b.StartLine == endLine && b.StartCol >= endCol) {
// Past the end of the function.
break
}
if b.EndLine < startLine || (b.EndLine == startLine && b.EndCol <= startCol) {
// Before the beginning of the function
continue
}
for i := b.StartLine; i <= b.EndLine; i++ {
method.Lines.AddOrUpdateLine(i, int64(b.Count))
}
}
return method
}
func (v *fileVisitor) class(n *ast.FuncDecl) *Class {
className := v.recvName(n)
var class *Class = v.classes[className]
if class == nil {
class = &Class{Name: className, Filename: v.fileName, Methods: []*Method{}, Lines: []*Line{}}
v.classes[className] = class
v.pkg.Classes = append(v.pkg.Classes, class)
}
return class
}
func (v *fileVisitor) recvName(n *ast.FuncDecl) string {
if n.Recv == nil {
return "-"
}
recv := n.Recv.List[0].Type
start := v.fset.Position(recv.Pos())
end := v.fset.Position(recv.End())
name := string(v.fileData[start.Offset:end.Offset])
return strings.TrimSpace(strings.TrimLeft(name, "*"))
}