-
Notifications
You must be signed in to change notification settings - Fork 18
/
compiler.go
73 lines (63 loc) · 1.37 KB
/
compiler.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
/*
Package binary provides a convenient mechanism for building and running a service binary
as part of an acceptance test suite.
*/
package compiler
import (
"context"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
)
type Compiler struct {
dir string
}
func New() (*Compiler, error) {
tempDir, err := ioutil.TempDir("", "acceptance-tests")
if err != nil {
return nil, err
}
return &Compiler{
dir: tempDir,
}, nil
}
func (c *Compiler) Cleanup() {
_ = os.RemoveAll(c.dir)
}
// Compile a binary for testing. target is the path to the main package.
func (c *Compiler) Compile(ctx context.Context, name, target string, source string) (string, error) {
cwd, err := filepath.Abs(target)
if err != nil {
return "", err
}
path := binaryPath(name, c.dir)
goBin := goPath()
// #nosec - this is fine
cmd := exec.CommandContext(ctx, goBin, "test",
"-coverpkg=./...",
"-c",
"-tags", "testrunmain",
source,
"-o", path)
cmd.Dir = cwd
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return path, cmd.Run()
}
func goPath() string {
goroot := os.Getenv("GOROOT")
if goroot == "" {
return "go"
}
return filepath.Join(filepath.Dir(goroot), "bin", "go")
}
func binaryPath(name, tempDir string) string {
path := filepath.Join(tempDir, name)
if runtime.GOOS == "windows" {
return path + ".exe"
}
return path
}