-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
324 lines (281 loc) · 8.25 KB
/
main.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
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"golang.org/x/xerrors"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli/v2"
"golang.org/x/tools/benchmark/parse"
)
type result struct {
Name string
RatioNsPerOp float64
RatioAllocedBytesPerOp float64
}
type comparedScore struct {
nsPerOp bool
allocedBytesPerOp bool
}
func main() {
app := &cli.App{
Name: "cob",
Usage: "Continuous Benchmark for Go project",
Action: func(c *cli.Context) error {
return run(newConfig(c))
},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "only-degression",
Usage: "Show only benchmarks with worse score",
},
&cli.BoolFlag{
Name: "fail-without-results",
Usage: "Exit with an error if the parsing fails",
},
&cli.Float64Flag{
Name: "threshold",
Usage: "The program fails if the benchmark gets worse than the threshold",
Value: 0.2,
},
&cli.StringFlag{
Name: "base",
Usage: "Specify a base commit compared with HEAD",
Value: "HEAD~1",
},
&cli.StringFlag{
Name: "compare",
Usage: "Which score to compare",
Value: "ns/op,B/op",
},
&cli.StringFlag{
Name: "bench-cmd",
Usage: "Specify a command to measure benchmarks",
Value: "go",
},
&cli.StringFlag{
Name: "bench-args",
Usage: "Specify arguments passed to -cmd",
Value: "test -run '^$' -bench . -benchmem ./...",
},
&cli.StringFlag{
Name: "git-path",
Usage: "Specify the path of the git repo",
Value: ".",
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func run(c config) error {
r, err := git.PlainOpen(c.gitPath)
if err != nil {
return xerrors.Errorf("unable to open the git repository: %w", err)
}
head, err := r.Head()
if err != nil {
return xerrors.Errorf("unable to get the reference where HEAD is pointing to: %w", err)
}
commit, err := r.CommitObject(head.Hash())
if err != nil {
return xerrors.Errorf("unable to get the head commit: %w", err)
}
if strings.Contains(strings.ToLower(commit.Message), "[skip cob]") {
log.Println("[skip cob] is detected, so the benchmark is skipped")
return nil
}
prev, err := r.ResolveRevision(plumbing.Revision(c.base))
if err != nil {
return xerrors.Errorf("unable to resolves revision to corresponding hash: %w", err)
}
w, err := r.Worktree()
if err != nil {
return xerrors.Errorf("unable to get a worktree based on the given fs: %w", err)
}
s, err := w.Status()
if err != nil {
return xerrors.Errorf("unable to get the working tree status: %w", err)
}
if !s.IsClean() {
return xerrors.New("the repository is dirty: commit all changes before running 'cob'")
}
err = w.Reset(&git.ResetOptions{Commit: *prev, Mode: git.HardReset})
if err != nil {
return xerrors.Errorf("failed to reset the worktree to a previous commit: %w", err)
}
defer func() {
_ = w.Reset(&git.ResetOptions{Commit: head.Hash(), Mode: git.HardReset})
}()
log.Printf("Run Benchmark: %s %s", prev, c.base)
prevSet, err := runBenchmark(c.benchCmd, c.benchArgs)
if err != nil {
return xerrors.Errorf("failed to run a benchmark: %w", err)
}
err = w.Reset(&git.ResetOptions{Commit: head.Hash(), Mode: git.HardReset})
if err != nil {
return xerrors.Errorf("failed to reset the worktree to HEAD: %w", err)
}
log.Printf("Run Benchmark: %s %s", head.Hash(), "HEAD")
headSet, err := runBenchmark(c.benchCmd, c.benchArgs)
if err != nil {
return xerrors.Errorf("failed to run a benchmark: %w", err)
}
if c.failWithoutResults {
if len(prevSet) == 0 {
return xerrors.New("could not parse any benchmark results for the previous commit")
}
if len(headSet) == 0 {
return xerrors.New("could not parse any benchmark results for the current commit")
}
}
var ratios []result
var rows [][]string
for benchName, headBenchmarks := range headSet {
var prevBench, headBench *parse.Benchmark
if len(headBenchmarks) > 0 {
headBench = headBenchmarks[0]
}
rows = append(rows, generateRow("HEAD", headBench))
prevBenchmarks, ok := prevSet[benchName]
if !ok {
rows = append(rows, []string{benchName, c.base, "-", "-"})
continue
}
if len(prevBenchmarks) > 0 {
prevBench = prevBenchmarks[0]
}
rows = append(rows, generateRow(c.base, prevBench))
var ratioNsPerOp float64
if prevBench.NsPerOp != 0 {
ratioNsPerOp = (headBench.NsPerOp - prevBench.NsPerOp) / prevBench.NsPerOp
}
var ratioAllocedBytesPerOp float64
if prevBench.AllocedBytesPerOp != 0 {
ratioAllocedBytesPerOp = (float64(headBench.AllocedBytesPerOp) - float64(prevBench.AllocedBytesPerOp)) / float64(prevBench.AllocedBytesPerOp)
}
ratios = append(ratios, result{
Name: benchName,
RatioNsPerOp: ratioNsPerOp,
RatioAllocedBytesPerOp: ratioAllocedBytesPerOp,
})
}
if !c.onlyDegression {
showResult(os.Stdout, rows)
}
degression := showRatio(os.Stdout, ratios, c.threshold, whichScoreToCompare(c.compare), c.onlyDegression)
if degression {
return xerrors.New("This commit makes benchmarks worse")
}
return nil
}
func runBenchmark(cmdStr string, args []string) (parse.Set, error) {
var stderr bytes.Buffer
cmd := exec.Command(cmdStr, args...)
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
if strings.HasSuffix(strings.TrimSpace(stderr.String()), "no packages to test") {
return parse.Set{}, nil
}
log.Println(string(out))
log.Println(stderr.String())
return nil, xerrors.Errorf("failed to run '%s' command: %w", cmd, err)
}
b := bytes.NewBuffer(out)
s, err := parse.ParseSet(b)
if err != nil {
return nil, xerrors.Errorf("failed to parse a result of benchmarks: %w", err)
}
return s, nil
}
func generateRow(ref string, b *parse.Benchmark) []string {
return []string{b.Name, ref, fmt.Sprintf(" %.2f ns/op", b.NsPerOp),
fmt.Sprintf(" %d B/op", b.AllocedBytesPerOp)}
}
func showResult(w io.Writer, rows [][]string) {
fmt.Fprintln(w, "\nResult")
fmt.Fprintf(w, "%s\n\n", strings.Repeat("=", 6))
table := tablewriter.NewWriter(w)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_CENTER)
headers := []string{"Name", "Commit", "NsPerOp", "AllocedBytesPerOp"}
table.SetHeader(headers)
table.SetAutoMergeCells(true)
table.SetRowLine(true)
table.AppendBulk(rows)
table.Render()
}
func showRatio(w io.Writer, results []result, threshold float64, comparedScore comparedScore, onlyDegression bool) bool {
table := tablewriter.NewWriter(w)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_CENTER)
table.SetRowLine(true)
headers := []string{"Name", "NsPerOp", "AllocedBytesPerOp"}
table.SetHeader(headers)
var degression bool
for _, result := range results {
if comparedScore.nsPerOp && threshold < result.RatioNsPerOp {
degression = true
} else if comparedScore.allocedBytesPerOp && threshold < result.RatioAllocedBytesPerOp {
degression = true
} else {
if onlyDegression {
continue
}
}
row := []string{result.Name, generateRatioItem(result.RatioNsPerOp), generateRatioItem(result.RatioAllocedBytesPerOp)}
colors := []tablewriter.Colors{{}, generateColor(result.RatioNsPerOp), generateColor(result.RatioAllocedBytesPerOp)}
if !comparedScore.nsPerOp {
row[1] = "-"
colors[1] = tablewriter.Colors{}
}
if !comparedScore.allocedBytesPerOp {
row[2] = "-"
colors[2] = tablewriter.Colors{}
}
table.Rich(row, colors)
}
if table.NumLines() > 0 {
fmt.Fprintln(w, "\nComparison")
fmt.Fprintf(w, "%s\n\n", strings.Repeat("=", 10))
table.Render()
fmt.Fprintln(w)
}
return degression
}
func generateRatioItem(ratio float64) string {
if -0.0001 < ratio && ratio < 0.0001 {
ratio = 0
}
if 0 <= ratio {
return fmt.Sprintf("%.2f%%", 100*ratio)
}
return fmt.Sprintf("%.2f%%", -100*ratio)
}
func generateColor(ratio float64) tablewriter.Colors {
if ratio > 0 {
return tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor}
}
return tablewriter.Colors{tablewriter.Bold, tablewriter.FgBlueColor}
}
func whichScoreToCompare(c []string) comparedScore {
var comparedScore comparedScore
for _, cc := range c {
switch cc {
case "ns/op":
comparedScore.nsPerOp = true
case "B/op":
comparedScore.allocedBytesPerOp = true
}
}
return comparedScore
}