-
Notifications
You must be signed in to change notification settings - Fork 18
/
compiler.go
90 lines (76 loc) · 1.48 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package compiler
import (
"context"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
)
type Compiler struct {
dir string
}
func New() *Compiler {
tempDir, err := ioutil.TempDir("", "acceptance-tests")
if err != nil {
panic(err)
}
return &Compiler{
dir: tempDir,
}
}
func (c *Compiler) Dir() string {
return c.dir
}
func (c *Compiler) Cleanup() {
_ = os.RemoveAll(c.dir)
}
type Work struct {
Name string
Target string
Source string
Environment []string
Result *string
}
// Compile a binary for testing. target is the path to the main package.
func (c *Compiler) Compile(ctx context.Context, work Work) (string, error) {
cwd, err := filepath.Abs(work.Target)
if err != nil {
return "", err
}
path := binaryPath(work.Name, c.dir)
goBin := goPath()
// #nosec - this is fine
cmd := exec.CommandContext(ctx, goBin, "build",
"-ldflags=-w -s",
"-o", path,
work.Source,
)
cmd.Dir = cwd
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
cmd.Env = append(cmd.Env, work.Environment...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return "", err
}
if work.Result != nil {
*work.Result = path
}
return path, err
}
func goPath() string {
goroot := os.Getenv("GOROOT")
if goroot == "" {
return "go"
}
return filepath.Join(goroot, "bin", "go")
}
func binaryPath(name, tempDir string) string {
path := filepath.Join(tempDir, name)
if runtime.GOOS == "windows" {
return path + ".exe"
}
return path
}