-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.go
113 lines (88 loc) · 1.91 KB
/
console.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
package build
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
func CreateConsole(dir string) (*Console, error) {
c := &Console{
Dir: dir,
}
return c, nil
}
type Console struct {
Dir string
}
func (r *Console) FindExecutable(cmd string) (string, error) {
result, err := exec.LookPath(cmd)
if err != nil {
return "", errors.Wrapf(err, "%v executable not found in PATH", cmd)
}
result, err = filepath.Abs(result)
if err != nil {
return "", err
}
return result, nil
}
func (r *Console) RunInline(args ...interface{}) error {
cmd, err := r.createCommand(args)
if err != nil {
return err
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
tmp := make([]string, len(args))
for i, a := range args {
tmp[i] = fmt.Sprint(a)
}
fmt.Printf("Executing '%v'\n", strings.Join(tmp, "' '"))
return cmd.Run()
}
func (r *Console) RunAndReturnOutput(args ...interface{}) (string, error) {
cmd, err := r.createCommand(args)
if err != nil {
return "", err
}
output, err := cmd.Output()
if err != nil {
return "", errors.Wrapf(err, "error calling %v %v", cmd.Path, cmd.Args)
}
result := string(output)
result = strings.TrimRight(result, "\r\n")
return result, nil
}
func (r *Console) createCommand(args []interface{}) (*exec.Cmd, error) {
var err error
var env []string
var name string
var cargs []string
dir := r.Dir
for i, a := range args {
s := fmt.Sprint(a)
switch {
case i == 0 && strings.HasPrefix(s, "cd "):
dir = s[3:]
if !filepath.IsAbs(dir) {
filepath.Join(r.Dir, s[3:])
}
dir, err = filepath.Abs(dir)
if err != nil {
return nil, err
}
case name == "" && strings.IndexAny(s, "=") > 0:
env = append(env, s)
case name == "":
name = s
default:
cargs = append(cargs, s)
}
}
cmd := exec.Command(name, cargs...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), env...)
return cmd, nil
}