-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.go
342 lines (304 loc) · 8.57 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
// Copyright 2020 Matthew Holt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"strings"
"go.k6.io/xk6"
)
var (
k6Version = os.Getenv("K6_VERSION")
k6Repo = os.Getenv("XK6_K6_REPO")
raceDetector = os.Getenv("XK6_RACE_DETECTOR") == "1"
skipCleanup = os.Getenv("XK6_SKIP_CLEANUP") == "1"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go trapSignals(ctx, cancel)
if len(os.Args) > 1 && os.Args[1] == "build" {
if err := runBuild(ctx, os.Args[2:]); err != nil {
log.Fatalf("[ERROR] %v", err)
}
return
}
if err := runDev(ctx, os.Args[1:]); err != nil {
log.Fatalf("[ERROR] %v", err)
}
}
func runBuild(ctx context.Context, args []string) error {
// parse the command line args... rather primitively
var argK6Version, output string
var outputOverride bool
var extensions []xk6.Dependency
var replacements []xk6.Replace
for i := 0; i < len(args); i++ {
switch args[i] {
case "--with":
if i == len(args)-1 {
return fmt.Errorf("expected value after --with flag")
}
i++
mod, ver, repl, err := splitWith(args[i])
if err != nil {
return err
}
mod = strings.TrimSuffix(mod, "/") // easy to accidentally leave a trailing slash if pasting from a URL, but is invalid for Go modules
extensions = append(extensions, xk6.Dependency{
PackagePath: mod,
Version: ver,
})
if repl != "" {
repl, err = expandPath(repl)
if err != nil {
return err
}
replacements = append(replacements, xk6.NewReplace(mod, repl))
}
case "--replace":
if i == len(args)-1 {
return fmt.Errorf("expected value after --replace flag")
}
i++
mod, _, repl, err := splitWith(args[i])
if err != nil {
return err
}
if repl == "" {
return fmt.Errorf("replace value must be of format 'module=replace' or 'module=replace@version'")
}
// easy to accidentally leave a trailing slash if pasting from a URL, but is invalid for Go modules
mod = strings.TrimSuffix(mod, "/")
repl, err = expandPath(repl)
if err != nil {
return err
}
replacements = append(replacements, xk6.NewReplace(mod, repl))
case "--output":
if i == len(args)-1 {
return fmt.Errorf("expected value after --output flag")
}
i++
output = args[i]
outputOverride = true
default:
if argK6Version != "" {
return fmt.Errorf("missing flag; k6 version already set at %s", argK6Version)
}
argK6Version = args[i]
}
}
// prefer k6 version from command line argument over env var
if argK6Version != "" {
k6Version = argK6Version
}
// ensure an output file is always specified
if output == "" {
output = getK6OutputFile()
}
// perform the build
builder := xk6.Builder{
Compile: xk6.Compile{
Cgo: os.Getenv("CGO_ENABLED") == "1",
},
K6Repo: k6Repo,
K6Version: k6Version,
Extensions: extensions,
Replacements: replacements,
RaceDetector: raceDetector,
SkipCleanup: skipCleanup,
}
err := builder.Build(ctx, output)
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
// prove the build is working by printing the version
if runtime.GOOS == os.Getenv("GOOS") && runtime.GOARCH == os.Getenv("GOARCH") {
if !filepath.IsAbs(output) {
output = "." + string(filepath.Separator) + output
}
fmt.Println()
fmt.Printf("%s version\n", output)
cmd := exec.Command(output, "version")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
}
if !outputOverride {
path, _ := os.Getwd()
fmt.Println()
fmt.Println("xk6 has now produced a new k6 binary which may be different than the command on your system path!")
fmt.Printf("Be sure to run '%v run <SCRIPT_NAME>' from the '%v' directory.\n", output, path)
}
return nil
}
func getK6OutputFile() string {
if runtime.GOOS == "windows" {
return ".\\k6.exe"
}
return "./k6"
}
func runDev(ctx context.Context, args []string) error {
binOutput := getK6OutputFile()
// get current/main module name
cmd := exec.Command("go", "list", "-m")
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
return fmt.Errorf("exec %v: %v: %s", cmd.Args, err, string(out))
}
currentModule := strings.TrimSpace(string(out))
// get the root directory of the main module
cmd = exec.Command("go", "list", "-m", "-f={{.Dir}}")
cmd.Stderr = os.Stderr
out, err = cmd.Output()
if err != nil {
return fmt.Errorf("exec %v: %v: %s", cmd.Args, err, string(out))
}
moduleDir := strings.TrimSpace(string(out))
// make sure the module being developed is replaced
// so that the local copy is used
replacements := []xk6.Replace{
xk6.NewReplace(currentModule, moduleDir),
}
// replace directives only apply to the top-level/main go.mod,
// and since this tool is a carry-through for the user's actual
// go.mod, we need to transfer their replace directives through
// to the one we're making
cmd = exec.Command("go", "list", "-mod=readonly", "-m", "-f={{if .Replace}}{{.Path}} => {{.Replace}}{{end}}", "all")
cmd.Stderr = os.Stderr
out, err = cmd.Output()
if err != nil {
return fmt.Errorf("exec %v: %v: %s", cmd.Args, err, string(out))
}
for _, line := range strings.Split(string(out), "\n") {
parts := strings.Split(line, "=>")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
continue
}
replacements = append(replacements, xk6.NewReplace(
strings.TrimSpace(parts[0]),
strings.TrimSpace(parts[1]),
))
}
// reconcile remaining path segments; for example if a module foo/a
// is rooted at directory path /home/foo/a, but the current directory
// is /home/foo/a/b, then the package to import should be foo/a/b
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("unable to determine current directory: %v", err)
}
importPath := normalizeImportPath(currentModule, cwd, moduleDir)
// build k6 with this module plugged in
builder := xk6.Builder{
Compile: xk6.Compile{
Cgo: os.Getenv("CGO_ENABLED") == "1",
},
K6Repo: k6Repo,
K6Version: k6Version,
Extensions: []xk6.Dependency{
{PackagePath: importPath},
},
Replacements: replacements,
RaceDetector: raceDetector,
SkipCleanup: skipCleanup,
}
err = builder.Build(ctx, binOutput)
if err != nil {
return err
}
log.Printf("[INFO] Running %v\n\n", append([]string{binOutput}, args...))
cmd = exec.Command(binOutput, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
return err
}
defer func() {
if skipCleanup {
log.Printf("[INFO] Skipping cleanup as requested; leaving artifact: %s", binOutput)
return
}
err = os.Remove(binOutput)
if err != nil && !os.IsNotExist(err) {
log.Printf("[ERROR] Deleting temporary binary %s: %v", binOutput, err)
}
}()
return cmd.Wait()
}
func normalizeImportPath(currentModule, cwd, moduleDir string) string {
return path.Join(currentModule, filepath.ToSlash(strings.TrimPrefix(cwd, moduleDir)))
}
func trapSignals(ctx context.Context, cancel context.CancelFunc) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
select {
case <-sig:
log.Printf("[INFO] SIGINT: Shutting down")
cancel()
case <-ctx.Done():
return
}
}
func splitWith(arg string) (module, version, replace string, err error) {
const versionSplit, replaceSplit = "@", "="
parts := strings.SplitN(arg, replaceSplit, 2)
if len(parts) > 1 {
replace = parts[1]
} else {
replace = ""
}
module = parts[0]
moduleParts := strings.SplitN(module, versionSplit, 2)
if len(moduleParts) > 1 {
module = moduleParts[0]
version = moduleParts[1]
}
if module == "" {
err = fmt.Errorf("module name is required")
}
return
}
func expandPath(path string) (string, error) {
// expand local directory
if path == "." {
if cwd, err := os.Getwd(); err != nil {
return "", err
} else {
return cwd, nil
}
}
// expand ~ as shortcut for home directory
if strings.HasPrefix(path, "~") {
if home, err := os.UserHomeDir(); err != nil {
return "", err
} else {
return strings.Replace(path, "~", home, 1), nil
}
}
return path, nil
}