-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathruntime.go
62 lines (53 loc) · 1.11 KB
/
runtime.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
package kanvas
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
)
type Runtime struct {
}
func NewRuntime() *Runtime {
return &Runtime{}
}
type ExecOption func(*exec.Cmd)
func ExecStdout(w io.Writer) ExecOption {
return func(c *exec.Cmd) {
c.Stdout = w
}
}
func ExecAddEnv(env map[string]string) ExecOption {
return func(c *exec.Cmd) {
c.Env = os.Environ()
for k, v := range env {
c.Env = append(c.Env, fmt.Sprintf("%s=%s", k, v))
}
}
}
func (r *Runtime) Exec(dir string, cmd []string, opts ...ExecOption) error {
c := exec.CommandContext(context.TODO(), cmd[0], cmd[1:]...)
c.Dir = dir
for _, o := range opts {
o(c)
}
if c.Stdout != nil {
var stderr bytes.Buffer
c.Stderr = &stderr
if err := c.Run(); err != nil {
return fmt.Errorf("executing %q in %q: %w: %s", cmd, dir, err, stderr.String())
}
} else {
var (
stdout, stderr bytes.Buffer
)
c.Stdout = io.MultiWriter(&stdout, os.Stderr)
c.Stderr = io.MultiWriter(&stderr, os.Stderr)
err := c.Run()
if err != nil {
return fmt.Errorf("executing %q in %q: %w: %s", cmd, dir, err, stderr.String())
}
}
return nil
}