forked from drone-plugins/drone-coverage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_publish.go
349 lines (308 loc) · 8.12 KB
/
cmd_publish.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/drone-plugins/drone-coverage/client"
"github.com/drone-plugins/drone-coverage/coverage"
"github.com/joho/godotenv"
"github.com/mattn/go-zglob"
"github.com/urfave/cli"
"golang.org/x/tools/cover"
)
// PublishCmd is the exported command for publishing coverage files.
var PublishCmd = cli.Command{
Name: "publish",
Usage: "publish coverage report",
Flags: []cli.Flag{
cli.StringFlag{
Name: "repo.fullname",
Usage: "repository full name",
EnvVar: "DRONE_REPO",
},
cli.StringFlag{
Name: "build.event",
Value: "push",
Usage: "build event",
EnvVar: "DRONE_BUILD_EVENT",
},
cli.IntFlag{
Name: "build.number",
Usage: "build number",
EnvVar: "DRONE_BUILD_NUMBER",
},
cli.StringFlag{
Name: "build.link",
Usage: "build link",
EnvVar: "DRONE_BUILD_LINK",
},
cli.StringFlag{
Name: "commit.sha",
Usage: "git commit sha",
EnvVar: "DRONE_COMMIT_SHA",
},
cli.StringFlag{
Name: "commit.ref",
Value: "refs/heads/master",
Usage: "git commit ref",
EnvVar: "DRONE_COMMIT_REF",
},
cli.StringFlag{
Name: "commit.branch",
Value: "master",
Usage: "git commit branch",
EnvVar: "DRONE_COMMIT_BRANCH",
},
cli.StringFlag{
Name: "commit.message",
Usage: "git commit message",
EnvVar: "DRONE_COMMIT_MESSAGE",
},
cli.StringFlag{
Name: "commit.author.name",
Usage: "git author name",
EnvVar: "DRONE_COMMIT_AUTHOR",
},
cli.StringFlag{
Name: "commit.author.avatar",
Usage: "git author avatar",
EnvVar: "DRONE_COMMIT_AUTHOR_AVATAR",
},
cli.StringFlag{
Name: "pattern",
Usage: "coverage file pattern",
Value: "**/*.*",
EnvVar: "PLUGIN_PATTERN",
},
cli.StringFlag{
Name: "server",
Usage: "coverage server",
Value: "**/*.*",
EnvVar: "PLUGIN_SERVER",
},
cli.Float64Flag{
Name: "threshold",
Usage: "coverage threshold",
EnvVar: "PLUGIN_THRESHOLD",
},
cli.BoolFlag{
Name: "increase",
Usage: "coverage must increase",
EnvVar: "PLUGIN_MUST_INCREASE",
},
cli.StringFlag{
Name: "cert",
Usage: "coverage cert",
EnvVar: "COVERAGE_CERT",
},
cli.StringFlag{
Name: "token",
Usage: "github token",
EnvVar: "GITHUB_TOKEN",
},
cli.StringFlag{
Name: "env-file",
Usage: "source env file",
},
cli.StringFlag{
Name: "trim-prefix",
Usage: "trim prefix from coverage files",
EnvVar: "PLUGIN_TRIM_PREFIX",
},
},
Action: func(c *cli.Context) error {
return publish(c)
},
}
func publish(c *cli.Context) error {
if c.String("env-file") != "" {
_ = godotenv.Load(c.String("env-file"))
}
logrus.Debugf("finding coverage files that match %s", c.String("pattern"))
matches, err := zglob.Glob(c.String("pattern"))
if err != nil {
return err
}
var profiles []*cover.Profile
for _, match := range matches {
ok, reader := coverage.FromFile(match)
if !ok {
continue
}
logrus.Debugf("found coverage file %s", match)
parsed, rerr := reader.ReadFile(match)
if rerr != nil {
return err
}
for _, p := range parsed {
profiles = addProfile(profiles, p)
}
}
// create the coverage payload that gets sent to the
// coverage reporting server.
report := profileToReport(profiles)
build := client.Build{
Number: c.Int("build.number"),
Event: c.String("build.event"),
Commit: c.String("commit.sha"),
Branch: c.String("commit.branch"),
Ref: c.String("commit.ref"),
Message: c.String("commit.message"),
Author: c.String("commit.author.name"),
Avatar: c.String("commit.author.avatar"),
Link: c.String("build.link"),
Timestamp: time.Now().UTC().Unix(),
}
// get the base directory
base := c.String("trim.prefix")
if len(base) == 0 {
base, err = os.Getwd()
if err != nil {
return err
}
logrus.Debug("Using current working directory")
}
logrus.Debugf("Base directory is %s", base)
findFileReferences(report, base)
var (
repo = c.String("repo.fullname")
server = c.String("server")
secret = c.String("token")
cert = c.String("cert")
)
cli := newClient(server, cert, "")
token, err := cli.Token(secret)
if err != nil {
return err
}
cli = newClient(server, cert, token.Access)
// check and see if the repository exists. if not, activate
if _, err := cli.Repo(repo); err != nil {
if _, err := cli.Activate(repo); err != nil {
return err
}
}
resp, err := cli.Submit(repo, &build, report)
if err != nil {
return err
}
switch {
case resp.Changed > 0:
fmt.Printf("Code coverage increased %.1f%% to %.1f%%\n", resp.Changed, resp.Coverage)
case resp.Changed < 0:
fmt.Printf("Code coverage dropped %.1f%% to %.1f%%\n", resp.Changed, resp.Coverage)
default:
fmt.Printf("Code coverage unchanged, %.1f%%\n", resp.Coverage)
}
if c.Float64("threshold") < resp.Coverage && c.Float64("threshold") != 0 {
return fmt.Errorf("Failing build. Coverage threshold may not fall below %.1f%%\n", c.Float64("threshold"))
}
if resp.Changed < 0 && c.Bool("increase") {
return fmt.Errorf("Failing build. Coverage may not decrease")
}
return nil
}
func findFileReferences(report *client.Report, base string) {
var files []*client.File
// normalize the file path based on the working directory
// also ignore any files outside of the directory
for _, file := range report.Files {
fileName := file.FileName
var prefix string
if path.IsAbs(fileName) {
if !strings.HasPrefix(fileName, base) {
logrus.Warningf("File referenced in coverage not found at %s", fileName)
continue
}
prefix = base
} else if _, err := os.Stat(fileName); err == nil {
logrus.Debugf("File found at relative path %s", fileName)
prefix = ""
} else {
var err error
prefix, err = coverage.PathPrefix(fileName, base)
if err != nil {
// See if file is on disk
logrus.Warningf("File referenced in coverage not found at %s", fileName)
continue
}
logrus.Debugf("Found common path at %s", prefix)
}
// Add the file to the report
file.FileName = strings.TrimPrefix(fileName, prefix)
files = append(files, file)
}
report.Files = files
}
// profileToReport is a helper function that converts the merged coverage
// report to the Report JSON format expected by the coverage server.
func profileToReport(profiles []*cover.Profile) *client.Report {
report := client.Report{}
report.Files = make([]*client.File, len(profiles), len(profiles))
for i, profile := range profiles {
file := client.File{
Mode: profile.Mode,
FileName: profile.FileName,
}
file.Blocks = make([]*client.Block, len(profile.Blocks), len(profile.Blocks))
for ii, block := range profile.Blocks {
file.Blocks[ii] = &client.Block{
StartLine: block.StartLine,
StartCol: block.StartCol,
EndLine: block.EndLine,
EndCol: block.EndCol,
NumStmt: block.NumStmt,
Count: block.Count,
}
}
covered, total, percent := percentCovered(profile)
file.Lines = total
file.Covered = covered
file.Coverage = percent
report.Files[i] = &file
report.Lines += file.Lines
report.Covered += file.Covered
}
if report.Lines != 0 {
report.Coverage = float64(report.Covered) / float64(report.Lines) * float64(100)
}
return &report
}
// percentCovered is a helper fucntion that calculate the percent
// coverage for coverage profile.
func percentCovered(p *cover.Profile) (int64, int64, float64) {
var total, covered int64
for _, b := range p.Blocks {
total += int64(b.NumStmt)
if b.Count > 0 {
covered += int64(b.NumStmt)
}
}
var percent float64
if total != 0 {
percent = float64(covered) / float64(total) * float64(100)
}
return covered, total, percent
}
// newClient returns a new coverage server client.
func newClient(server, cert, token string) client.Client {
pool, err := x509.SystemCertPool()
if err != nil {
pool = x509.NewCertPool()
}
conf := &tls.Config{RootCAs: pool}
pem, _ := ioutil.ReadFile(cert)
if len(pem) != 0 {
pool.AppendCertsFromPEM(pem)
}
if len(token) == 0 {
return client.NewClientTLS(server, conf)
}
return client.NewClientTokenTLS(server, token, conf)
}