forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd.go
116 lines (94 loc) · 2.2 KB
/
cmd.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package cmd
import (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"github.com/github/hub/ui"
"github.com/github/hub/utils"
"github.com/kballard/go-shellquote"
)
type Cmd struct {
Name string
Args []string
}
func (cmd Cmd) String() string {
return fmt.Sprintf("%s %s", cmd.Name, strings.Join(cmd.Args, " "))
}
func (cmd *Cmd) WithArg(arg string) *Cmd {
cmd.Args = append(cmd.Args, arg)
return cmd
}
func (cmd *Cmd) WithArgs(args ...string) *Cmd {
for _, arg := range args {
cmd.WithArg(arg)
}
return cmd
}
func (cmd *Cmd) CombinedOutput() (string, error) {
verboseLog(cmd)
output, err := exec.Command(cmd.Name, cmd.Args...).CombinedOutput()
return string(output), err
}
func (cmd *Cmd) Success() bool {
verboseLog(cmd)
err := exec.Command(cmd.Name, cmd.Args...).Run()
return err == nil
}
// Run runs command with `Exec` on platforms except Windows
// which only supports `Spawn`
func (cmd *Cmd) Run() error {
if runtime.GOOS == "windows" {
return cmd.Spawn()
} else {
return cmd.Exec()
}
}
// Spawn runs command with spawn(3)
func (cmd *Cmd) Spawn() error {
verboseLog(cmd)
c := exec.Command(cmd.Name, cmd.Args...)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
// Exec runs command with exec(3)
// Note that Windows doesn't support exec(3): http://golang.org/src/pkg/syscall/exec_windows.go#L339
func (cmd *Cmd) Exec() error {
verboseLog(cmd)
binary, err := exec.LookPath(cmd.Name)
if err != nil {
return &exec.Error{
Name: cmd.Name,
Err: fmt.Errorf("command not found"),
}
}
args := []string{binary}
args = append(args, cmd.Args...)
return syscall.Exec(binary, args, os.Environ())
}
func New(cmd string) *Cmd {
cmds, err := shellquote.Split(cmd)
utils.Check(err)
name := cmds[0]
args := make([]string, 0)
for _, arg := range cmds[1:] {
args = append(args, arg)
}
return &Cmd{Name: name, Args: args}
}
func NewWithArray(cmd []string) *Cmd {
return &Cmd{Name: cmd[0], Args: cmd[1:]}
}
func verboseLog(cmd *Cmd) {
if os.Getenv("HUB_VERBOSE") != "" {
msg := fmt.Sprintf("$ %s %s", cmd.Name, strings.Join(cmd.Args, " "))
if ui.IsTerminal(os.Stderr) {
msg = fmt.Sprintf("\033[35m%s\033[0m", msg)
}
ui.Errorln(msg)
}
}