-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathexec.go
86 lines (71 loc) · 2.07 KB
/
exec.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
// Package exec provides the xk6 Modules implementation for running local commands using Javascript
package exec
import (
"errors"
"log"
"os"
"os/exec"
"strings"
"go.k6.io/k6/js/modules"
)
func init() {
modules.Register("k6/x/exec", new(RootModule))
}
// RootModule is the global module object type. It is instantiated once per test
// run and will be used to create `k6/x/exec` module instances for each VU.
type RootModule struct{}
// EXEC represents an instance of the EXEC module for every VU.
type EXEC struct {
vu modules.VU
}
// CommandOptions contains the options that can be passed to command.
type CommandOptions struct {
Dir string
ContinueOnError bool
IncludeStdoutOnError bool
}
type MyExitError struct {
ProcessState *os.ProcessState
Stderr []byte
Stdout []byte
}
func (e *MyExitError) Error() string {
return e.ProcessState.String()
}
// Ensure the interfaces are implemented correctly.
var (
_ modules.Module = &RootModule{}
_ modules.Instance = &EXEC{}
)
// NewModuleInstance implements the modules.Module interface to return
// a new instance for each VU.
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
return &EXEC{vu: vu}
}
// Exports implements the modules.Instance interface and returns the exports
// of the JS module.
func (exec *EXEC) Exports() modules.Exports {
return modules.Exports{Default: exec}
}
// Command is a wrapper for Go exec.Command
func (*EXEC) Command(name string, args []string, option CommandOptions) (string, error) {
cmd := exec.Command(name, args...)
if option.Dir != "" {
cmd.Dir = option.Dir
}
out, err := cmd.Output()
if err != nil && !option.ContinueOnError {
log.Fatal(err.Error() + " on command: " + name + " " + strings.Join(args, " "))
}
if err != nil && option.IncludeStdoutOnError {
var exitErr *exec.ExitError
var myExitError MyExitError
if errors.As(err, &exitErr) {
myExitError.Stderr = exitErr.Stderr
myExitError.Stdout = out
myExitError.ProcessState = exitErr.ProcessState
return string(out), &myExitError
}
}
return string(out), err
}