forked from codeclimate/test-reporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source_file.go
126 lines (108 loc) · 2.53 KB
/
source_file.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
package formatters
import (
"encoding/json"
"fmt"
"os"
"strings"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"github.com/Sirupsen/logrus"
"github.com/codeclimate/test-reporter/env"
"github.com/gobuffalo/envy"
"github.com/markbates/pop/nulls"
"github.com/pkg/errors"
)
type SourceFile struct {
BlobID string `json:"blob_id"`
Coverage Coverage `json:"coverage"`
CoveredPercent float64 `json:"covered_percent"`
CoveredStrength float64 `json:"covered_strength"`
LineCounts LineCounts `json:"line_counts"`
Name string `json:"name"`
}
func (a SourceFile) Merge(b SourceFile) (SourceFile, error) {
if len(a.Coverage) != len(b.Coverage) {
return a, errors.Errorf("coverage length mismatch for %s", a.Name)
}
for i, bc := range b.Coverage {
ac := a.Coverage[i]
if ac.Valid && bc.Valid {
// they're both valid numbers so add them:
a.Coverage[i] = nulls.NewInt(ac.Int + bc.Int)
continue
}
if !bc.Valid {
//default is to nothing and use the ac value
continue
}
// ac is null and bc isn't so use bc
if !ac.Valid {
a.Coverage[i] = bc
}
}
a.CalcLineCounts()
return a, nil
}
func (sf *SourceFile) CalcLineCounts() {
lc := LineCounts{}
for _, c := range sf.Coverage {
if !c.Valid {
continue
}
lc.Total++
lc.Strength += c.Int
if c.Int == 0 {
lc.Missed++
continue
}
lc.Covered++
}
sf.LineCounts = lc
sf.CoveredPercent = lc.CoveredPercent()
sf.CoveredStrength = lc.CoveredStrength()
}
func NewSourceFile(name string, commit *object.Commit) (SourceFile, error) {
if prefix, err := envy.MustGet("PREFIX"); err == nil {
prefix := fmt.Sprintf("%s%s", prefix, string(os.PathSeparator))
name = strings.TrimPrefix(name, prefix)
}
sf := SourceFile{
Name: name,
Coverage: Coverage{},
}
var err error
sf.BlobID, err = env.GitBlob(name, commit)
if err != nil {
return sf, errors.WithStack(err)
}
return sf, nil
}
type SourceFiles map[string]SourceFile
func (sf SourceFiles) MarshalJSON() ([]byte, error) {
files := []SourceFile{}
for _, s := range sf {
s.CalcLineCounts()
files = append(files, s)
}
b, err := json.Marshal(files)
if err != nil {
logrus.Errorf("error marshalling source files: %+v\n", sf)
}
return b, err
}
func (sf SourceFiles) UnmarshalJSON(text []byte) error {
files := []SourceFile{}
err := json.Unmarshal(text, &files)
if err != nil {
return err
}
for _, f := range files {
if ff, ok := sf[f.Name]; ok {
f, err = ff.Merge(f)
if err != nil {
return err
}
}
sf[f.Name] = f
}
return nil
}