-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
49 lines (44 loc) · 924 Bytes
/
command.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
package main
import (
"bytes"
"io"
"os"
"os/exec"
"strings"
)
type Command struct {
Envs []string
Args []string
Output string
}
func newCommand(args []string) *Command {
envs, commandArgs := splitArgsToEnvsAndCommand(args)
return &Command{
Envs: envs,
Args: commandArgs,
}
}
func (c *Command) Run() error {
cmd := exec.Command(c.Args[0], c.Args[1:]...)
cmd.Env = append(os.Environ(), c.Envs...)
cmd.Stdin = os.Stdin
var buf bytes.Buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &buf)
cmd.Stderr = io.MultiWriter(os.Stderr, &buf)
if err := cmd.Run(); err != nil {
return err
}
c.Output = buf.String()
return nil
}
func splitArgsToEnvsAndCommand(args []string) ([]string, []string) {
equalNotFound := false
return splitStringsInto2(args, func(arg string) bool {
if !equalNotFound && strings.Contains(arg, "=") {
return true
} else {
equalNotFound = true
return false
}
})
}