-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
commander.go
57 lines (47 loc) · 1.03 KB
/
commander.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
package main
import (
"fmt"
"log"
"os/exec"
"strings"
)
type ShellError struct {
Command string
Err error
}
func (e *ShellError) Error() string {
return fmt.Sprintf("Cannot run %q. Error %v", e.Command, e.Err)
}
type Commander interface {
Exec(cmd *exec.Cmd) (string, error)
ExecSilently(cmd *exec.Cmd) error
}
type DefaultCommander struct {
logger *log.Logger
}
func (c DefaultCommander) Exec(cmd *exec.Cmd) (string, error) {
if c.logger != nil {
c.logger.Println(strings.Join(cmd.Args, " "))
}
output, err := cmd.CombinedOutput()
if err != nil {
if c.logger != nil {
c.logger.Println(err, string(output))
}
return "", &ShellError{strings.Join(cmd.Args, " "), err}
}
return strings.TrimSuffix(string(output), "\n"), nil
}
func (c DefaultCommander) ExecSilently(cmd *exec.Cmd) error {
if c.logger != nil {
c.logger.Println(strings.Join(cmd.Args, " "))
}
err := cmd.Run()
if err != nil {
if c.logger != nil {
c.logger.Println(err)
}
return &ShellError{strings.Join(cmd.Args, " "), err}
}
return nil
}