/
gosh.go
48 lines (38 loc) · 1.11 KB
/
gosh.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
package comm
import (
"context"
"os"
"strings"
"time"
"github.com/pkg/errors"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
)
func RunGoShellCommand(vars map[string]any, dir string, cmd string) CommandOutput {
var err error
var sf *syntax.File
if sf, err = syntax.NewParser().Parse(strings.NewReader(cmd), ""); err != nil {
panic(errors.Wrapf(err, "failed to parse command: \n%s", cmd))
}
out := strings.Builder{}
environ := append(os.Environ(), EnvironList(vars)...)
opts := []interp.RunnerOption{
interp.Params("-e"),
interp.Env(expand.ListEnviron(environ...)),
interp.ExecHandler(GoshExecHandler(6 * time.Second)),
interp.OpenHandler(openHandler),
interp.StdIO(nil, &out, &out),
}
if len(dir) > 0 {
opts = append(opts, interp.Dir(dir))
}
var runner *interp.Runner
if runner, err = interp.New(opts...); err != nil {
panic(errors.Wrapf(err, "failed to create runner for command: \n%s", cmd))
}
if err = runner.Run(context.TODO(), sf); err != nil {
panic(errors.Wrapf(err, "failed to run command: \n%s", cmd))
}
return ParseCommandOutput(out.String())
}