-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcompiler.go
More file actions
117 lines (103 loc) · 2.11 KB
/
compiler.go
File metadata and controls
117 lines (103 loc) · 2.11 KB
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
package compiler
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
func newCompiler(baseDir, ldFlags string) *compiler {
return &compiler{
baseDir: baseDir,
ldFlags: ldFlags,
}
}
type compiler struct {
baseDir string
ldFlags string
}
func (c *compiler) Dir() string {
return c.baseDir
}
type Work struct {
Name string
Target string
Source string
WithCoverage bool
Tags 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
}
goos := runtime.GOOS
for _, e := range work.Environment {
if strings.HasPrefix(e, "GOOS=") {
goos = strings.SplitN(e, "=", 2)[1]
}
}
path := binaryPath(work.Name, c.baseDir, goos)
goBin := goPath()
var cmd *exec.Cmd
if !work.WithCoverage {
args := []string{
"build",
"-ldflags=" + c.ldFlags,
"-o", path,
}
if work.Tags != "" {
args = append(args, "-tags", work.Tags)
}
args = append(args, work.Source)
// #nosec - this is fine
cmd = exec.CommandContext(ctx, goBin, args...)
} else {
args := make([]string, 0, 9)
args = append(args,
"test",
"-coverpkg=./...",
"-c",
work.Source,
"-o", path,
"-tags", "testrunmain",
)
if work.Tags != "" {
args[len(args)-1] += " " + work.Tags
}
args = append(args, work.Source)
// #nosec - this is fine
cmd = exec.CommandContext(ctx, goBin, args...)
}
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, goos string) string {
path := filepath.Join(tempDir, name)
if goos == "windows" {
return path + ".exe"
}
return path
}