forked from codeclimate/test-reporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source_file.go
108 lines (93 loc) · 2.13 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
package formatters
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/codeclimate/test-reporter/env"
"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 int `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++
if c.Int == 0 {
lc.Missed++
continue
}
lc.Covered++
}
sf.LineCounts = lc
sf.CoveredPercent = lc.CoveredPercent()
}
func NewSourceFile(name string) (SourceFile, error) {
if pwd, err := os.Getwd(); err == nil {
pwd := fmt.Sprintf("%s%s", pwd, string(os.PathSeparator))
name = strings.TrimPrefix(name, pwd)
}
sf := SourceFile{Name: name}
var err error
sf.BlobID, err = env.GitBlob(name)
return sf, err
}
type SourceFiles map[string]SourceFile
func (sf SourceFiles) MarshalJSON() ([]byte, error) {
files := []SourceFile{}
for _, s := range sf {
s.CalcLineCounts()
files = append(files, s)
}
return json.Marshal(files)
}
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
}