-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
92 lines (76 loc) · 1.71 KB
/
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
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
87
88
89
90
91
92
package main
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/exec"
"strings"
)
type Command struct {
cmd *exec.Cmd
stdout *bytes.Buffer
stderr *bytes.Buffer
env map[string]string
}
func NewCommand(command string, args ...string) *Command {
c := &Command{}
c.cmd = exec.Command(command, args...)
c.stdout = bytes.NewBuffer([]byte{})
c.stderr = bytes.NewBuffer([]byte{})
c.cmd.Stdout = c.stdout
c.cmd.Stderr = c.stderr
c.env = make(map[string]string)
return c
}
func NewGoCommand(args ...string) *Command {
return NewCommand("go", args...)
}
func NewGitCommand(args ...string) *Command {
return NewCommand("git", args...)
}
func (c *Command) CleanArgs() {
c.cmd.Args = []string{}
}
func (c *Command) SetEnv(name, value string) *Command {
c.env[name] = value
return c
}
func (c *Command) AppendArgs(arg ...string) *Command {
c.cmd.Args = append(c.cmd.Args, arg...)
return c
}
func (c *Command) PrepareCommand() {
c.cmd.Env = os.Environ()
for k, v := range c.env {
c.cmd.Env = append(c.cmd.Env, k+"="+v)
}
}
func (c *Command) Start() error {
c.PrepareCommand()
return c.cmd.Start()
}
func (c *Command) String() string {
c.PrepareCommand()
return strings.Join(c.cmd.Env, " ") + c.cmd.Path + " " + strings.Join(c.cmd.Args, " ")
}
func (c *Command) Wait() error {
err := c.cmd.Wait()
if err != nil {
strStderr := string(c.Stderr())
if strStderr == "" {
strStderr = string(c.Stdout())
}
return errors.New(err.Error() + "\n" + strings.TrimSpace(strStderr))
}
return nil
}
func (c *Command) Stdout() []byte {
return c.stdout.Bytes()
}
func (c *Command) Stderr() []byte {
return c.stderr.Bytes()
}
func (c *Command) JSONStdout(i any) error {
return json.Unmarshal(c.stdout.Bytes(), i)
}