forked from cep21/gobuild
/
main.go
375 lines (335 loc) · 10.4 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"io"
"path/filepath"
"os/exec"
"github.com/cep21/gobuild/internal/golang.org/x/net/context"
)
type gobuildMain struct {
args []string
flags struct {
verbose bool
verboseFile string
chunkSize int
forceAbs bool
filenamePrefix string
}
tc templateCache
storageDir string
testrunStorageDir string
verboseLog logger
errLog logger
stderr io.Writer
onClose []func() error
}
var mainInstance = gobuildMain{
tc: templateCache{
cache: make(map[string]*buildTemplate),
},
stderr: os.Stdout,
}
func init() {
flag.BoolVar(&mainInstance.flags.verbose, "verbose", false, "Add verbose log to stderr")
flag.StringVar(&mainInstance.flags.verboseFile, "verbosefile", "", "Will verbose log to a filename rather than stderr")
flag.IntVar(&mainInstance.flags.chunkSize, "chunksize", 250, "size to chunk xargs into")
flag.StringVar(&mainInstance.flags.filenamePrefix, "filename_prefix", "", "Prefix to append to all generated files")
flag.BoolVar(&mainInstance.flags.forceAbs, "abs", false, "will force abs paths for ... dirs")
}
func main() {
flag.Parse()
mainInstance.args = flag.Args()
if err := mainInstance.main(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
}
func (g *gobuildMain) parseFlags() error {
vlog := ioutil.Discard
if g.flags.verbose {
vlog = os.Stderr
if g.flags.verboseFile != "" {
verboseFile, err := os.Create(g.flags.verboseFile)
if err != nil {
return wraperr(err, "cannot create verbose file %s", g.flags.verboseFile)
}
vlog = verboseFile
g.onClose = append(g.onClose, verboseFile.Close)
}
}
g.verboseLog = log.New(vlog, "[gobuild-verbose]", log.LstdFlags|log.Lshortfile)
g.errLog = log.New(os.Stderr, "[gobuild-err]", log.LstdFlags|log.Lshortfile)
g.tc.verboseLog = g.verboseLog
var err error
g.storageDir, err = g.storageDirectory()
if err != nil {
return wraperr(err, "cannot create test storage directory")
}
g.testrunStorageDir, err = g.testReportDirectory()
if err != nil {
return wraperr(err, "cannot create test run storage directory")
}
g.verboseLog.Printf("Storing results to %s", g.storageDir)
return nil
}
func (g *gobuildMain) getArgs() (string, []string) {
if len(g.args) == 0 {
return "check", []string{"./..."}
}
if len(g.args) == 1 {
return g.args[0], []string{"./..."}
}
return g.args[0], g.args[1:]
}
func (g *gobuildMain) fix(ctx context.Context, dirs []string) error {
if err := g.install(ctx, dirs); err != nil {
return wraperr(err, "cannot install subcommands")
}
c := fixCmd{
dirs: dirs,
chunkSize: g.flags.chunkSize,
verboseOut: g.verboseLog,
errOut: g.errLog,
}
return c.Run(ctx)
}
func (g *gobuildMain) lint(ctx context.Context, dirs []string) error {
if err := g.install(ctx, dirs); err != nil {
return wraperr(err, "cannot install subcommands")
}
testDirs, err := dirsWithFileGob(dirs, "*.go")
if err != nil {
return wraperr(err, "cannot find *.go files in dirs")
}
c := gometalinterCmd{
verboseLog: g.verboseLog,
errLog: g.errLog,
metaOutput: &myselfOutput{&nopCloseWriter{os.Stderr}},
dirsToLint: testDirs,
cache: &g.tc,
}
return c.Run(ctx)
}
func (g *gobuildMain) build(ctx context.Context, dirs []string) error {
buildableDirs, err := dirsWithFileGob(dirs, "*.go")
if err != nil {
return wraperr(err, "cannot find *.go files in dirs")
}
c := cmdBuild{
verboseLog: g.verboseLog,
errorLog: g.errLog,
cmdStdout: &myselfOutput{&nopCloseWriter{os.Stdout}},
cmdStderr: &myselfOutput{&nopCloseWriter{os.Stderr}},
dirs: buildableDirs,
cache: &g.tc,
}
return c.Run(ctx)
}
func (g *gobuildMain) dupl(ctx context.Context, dirs []string) error {
if err := g.install(ctx, dirs); err != nil {
return wraperr(err, "cannot install subcommands")
}
tmpl, err := g.tc.loadInDir(".")
if err != nil {
return wraperr(err, "cannot load root dir template")
}
htmlOut, err := os.Create(filepath.Join(g.storageDir, g.flags.filenamePrefix+"dupl.html"))
if err != nil {
return wraperr(err, "cannot create coverage html file")
}
c := duplCmd{
verboseLog: g.verboseLog,
dirs: dirs,
consoleOut: os.Stdout,
htmlOut: htmlOut,
tmpl: tmpl,
}
return multiErr([]error{c.Run(ctx), htmlOut.Close()})
}
func (g *gobuildMain) install(ctx context.Context, dirs []string) error {
tmpl, err := g.tc.loadInDir(".")
if err != nil {
return wraperr(err, "cannot load root dir template")
}
c := installCmd{
forceReinstall: false,
verboseLog: g.verboseLog,
errLog: g.errLog,
stdoutOutput: os.Stdout,
stderrOutput: os.Stderr,
tmpl: tmpl,
}
return c.Run(ctx)
}
func (g *gobuildMain) testReportDirectory() (string, error) {
return g.makeEnvDirectory("testReportEnv", "gobuild-tests")
}
func (g *gobuildMain) storageDirectory() (string, error) {
return g.makeEnvDirectory("artifactsEnv", "gobuild")
}
func (g *gobuildMain) makeEnvDirectory(envName string, subdirName string) (string, error) {
tmpl, err := g.tc.loadInDir(".")
if err != nil {
return "", wraperr(err, "cannot load root template directory")
}
fromEnv := os.Getenv(tmpl.varStr(envName))
if fromEnv != "" {
return fromEnv, nil
}
artifactDir := filepath.Join(os.TempDir(), subdirName)
if err := os.RemoveAll(artifactDir); err != nil {
return "", wraperr(err, "Cannot clean directory %s", artifactDir)
}
if err := os.MkdirAll(artifactDir, 0777); err != nil {
return "", wraperr(err, "Cannot create directory %s", artifactDir)
}
return artifactDir, nil
}
func (g *gobuildMain) test(ctx context.Context, dirs []string) error {
testDirs, err := dirsWithFileGob(dirs, "*.go")
if err != nil {
return wraperr(err, "cannot find *.go files in dirs")
}
fullCoverageFilename := filepath.Join(g.storageDir, g.flags.filenamePrefix+"full_coverage_output.cover.txt")
fullOut, err := os.Create(fullCoverageFilename)
if err != nil {
return wraperr(err, "cannot create full coverage profile file")
}
fullTestOutputFilename := filepath.Join(g.storageDir, g.flags.filenamePrefix+"full_test_output.txt")
fullTestStdout, err := os.Create(fullTestOutputFilename)
if err != nil {
return wraperr(err, "cannot create full test output file")
}
c := goCoverageCheck{
dirs: testDirs,
cache: &g.tc,
coverProfileOutTo: inDirStreamer(g.storageDir, ".cover.txt"),
testStdoutOutputTo: &myselfOutput{&nopCloseWriter{os.Stdout}},
testStderrOutputTo: &myselfOutput{&nopCloseWriter{os.Stderr}},
verboseLog: g.verboseLog,
errLog: g.errLog,
fullCoverageOutput: fullOut,
aggregateTestStdout: fullTestStdout,
}
e1 := c.Run(ctx)
e2 := fullOut.Close()
var e3 error
if e2 == nil {
htmlFilename := filepath.Join(g.storageDir, g.flags.filenamePrefix+"full_coverage_output.cover.html")
e3 = g.genCoverageHTML(ctx, fullCoverageFilename, htmlFilename)
}
e4 := fullTestStdout.Close()
var e5 error
if e4 == nil {
e5 = g.genJunitXML(ctx, fullTestOutputFilename)
}
return multiErr([]error{e1, e2, e3, e4, e5})
}
func (g *gobuildMain) genJunitXML(ctx context.Context, fullTestOutputFilename string) error {
junitXMLOutputFileDir := filepath.Join(g.testrunStorageDir, "gotest")
if _, err := os.Stat(junitXMLOutputFileDir); err != nil {
if err := os.Mkdir(junitXMLOutputFileDir, 0777); err != nil {
return wraperr(err, "cannot make temp dir %s", junitXMLOutputFileDir)
}
}
xmlOutFilename := filepath.Join(junitXMLOutputFileDir, g.flags.filenamePrefix+"junit-gotest.xml")
xmlOutFile, err := os.Create(xmlOutFilename)
if err != nil {
return wraperr(err, "cannot open xml run output file")
}
fullTestOutput, err := os.Open(fullTestOutputFilename)
if err != nil {
return wraperr(err, "cannot open test file for output")
}
return multiErr([]error{g.genJunitXMLFromBuffers(ctx, fullTestOutput, xmlOutFile), xmlOutFile.Close(), fullTestOutput.Close()})
}
func (g *gobuildMain) genJunitXMLFromBuffers(ctx context.Context, testInput io.Reader, testOutput io.Writer) error {
cmd := exec.Command("go-junit-report")
cmd.Stdin = testInput
cmd.Stderr = os.Stderr
cmd.Stdout = testOutput
g.verboseLog.Printf("Generating junit XML with %v", cmd)
if err := cmd.Run(); err != nil {
return wraperr(err, "test junit XML generation failed")
}
return nil
}
func (g *gobuildMain) genCoverageHTML(ctx context.Context, coverFilename string, htmlFilename string) error {
cmd := exec.Command("go", "tool", "cover", "-o", htmlFilename, "-html", coverFilename)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
g.verboseLog.Printf("Generating coverage html %s => %s with %v", coverFilename, htmlFilename, cmd)
if err := cmd.Run(); err != nil {
return wraperr(err, "coverage HTML generation failed")
}
return nil
}
func (g *gobuildMain) check(ctx context.Context, dirs []string) error {
buildErr := g.build(ctx, dirs)
lintErr := g.lint(ctx, dirs)
duplErr := g.dupl(ctx, dirs)
testErr := g.test(ctx, dirs)
return multiErr([]error{buildErr, lintErr, duplErr, testErr})
}
func (g *gobuildMain) list(ctx context.Context, dirs []string) error {
g.verboseLog.Printf("len(dirs) = %d", len(dirs))
fmt.Printf("%s\n", strings.Join(dirs, "\n"))
return nil
}
func (g *gobuildMain) Close() error {
errs := make([]error, 0, len(g.onClose))
for _, f := range g.onClose {
if err := f(); err != nil {
errs = append(errs, err)
}
}
return multiErr(errs)
}
func (g *gobuildMain) main() error {
defer func() {
if err := g.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Cannot close mainInstance: %s\n", err.Error())
}
}()
if err := g.parseFlags(); err != nil {
return wraperr(err, "cannot parse flags")
}
ctx := context.Background()
pe := pathExpansion{
forceAbs: g.flags.forceAbs,
log: g.verboseLog,
template: &g.tc,
}
cmdMap := map[string]func(context.Context, []string) error{
"fix": g.fix,
"lint": g.lint,
"list": g.list,
"build": g.build,
"test": g.test,
"dupl": g.dupl,
"install": g.install,
"check": g.check,
}
cmd, args := g.getArgs()
f, exists := cmdMap[cmd]
if !exists {
fmt.Fprintf(g.stderr, "Unknown command %s\nValid commands:\n", cmd)
for k := range cmdMap {
fmt.Fprintf(g.stderr, " %s\n", k)
}
return fmt.Errorf("unknown command %s", cmd)
}
dirs, err := pe.expandPaths(args)
if err != nil {
return wraperr(err, "cannot expand paths %s", strings.Join(args, ","))
}
if err := f(ctx, dirs); err != nil {
return wraperr(err, "Failure in command %s", cmd)
}
return nil
}