This repository has been archived by the owner on Jul 13, 2018. It is now read-only.
/
coverage.go
88 lines (83 loc) · 1.7 KB
/
coverage.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"github.com/gernest/mad/cover"
"github.com/urfave/cli"
)
func runCoverage(ctx *cli.Context) error {
f := ctx.Args().First()
if f != "" {
b, err := ioutil.ReadFile(f)
if err != nil {
return err
}
p := []cover.Profile{}
err = json.Unmarshal(b, &p)
if err != nil {
return err
}
txt := ctx.Bool("text")
mode := "set"
if len(p) > 1 {
mode = p[0].Mode
}
if txt {
return cover.FormatLine(os.Stdout, mode, p)
}
printCoverage(p)
}
return nil
}
func printCoverage(p []cover.Profile) {
m := make(map[string][]cover.Profile)
var keys []string
for _, v := range p {
b := filepath.Base(v.FileName)
pkgName := strings.TrimSuffix(v.FileName, b)
pkgName = strings.TrimSuffix(pkgName, "/")
if pkg, ok := m[pkgName]; ok {
pkg = append(pkg, v)
m[pkgName] = pkg
continue
}
keys = append(keys, pkgName)
m[pkgName] = []cover.Profile{v}
}
sort.Strings(keys)
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
for _, v := range keys {
c := cover.Calc(m[v])
fmt.Fprintf(w, "%s\t %.1f%%\n", v, 100*c)
}
v := cover.Calc(p)
fmt.Fprintf(w, "Total\t %.1f%%\n", 100*v)
w.Flush()
}
func mergeProfiles(a, b []cover.Profile) []cover.Profile {
cache := make(map[string]cover.Profile)
for _, v := range a {
cache[v.FileName] = v
}
for _, v := range b {
if c, ok := cache[v.FileName]; ok {
for key, value := range c.Blocks {
c.Blocks[key].Count = c.Blocks[key].Count + value.Count
}
cache[v.FileName] = c
} else {
cache[v.FileName] = v
}
}
var o []cover.Profile
for _, v := range cache {
o = append(o, v)
}
return o
}