forked from go-task/task
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
72 lines (61 loc) · 1.31 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
package execext
import (
"context"
"errors"
"io"
"os"
"strings"
"mvdan.cc/sh/interp"
"mvdan.cc/sh/syntax"
)
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
)
// RunCommand runs a shell command
func RunCommand(ctx context.Context, opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
environ := opts.Env
if len(environ) == 0 {
environ = os.Environ()
}
env, err := interp.EnvFromList(environ)
if err != nil {
return err
}
r, err := interp.New(
interp.Dir(opts.Dir),
interp.Env(env),
interp.Module(interp.DefaultExec),
interp.Module(interp.OpenDevImpls(interp.DefaultOpen)),
interp.StdIO(opts.Stdin, opts.Stdout, opts.Stderr),
)
if err != nil {
return err
}
return r.Run(ctx, p)
}
// IsExitError returns true the given error is an exis status error
func IsExitError(err error) bool {
switch err.(type) {
case interp.ExitStatus, interp.ShellExitStatus:
return true
default:
return false
}
}