-
Notifications
You must be signed in to change notification settings - Fork 3
/
terminal.go
70 lines (53 loc) · 1.14 KB
/
terminal.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
package main
import (
"github.com/kballard/go-shellquote"
"os"
"os/exec"
"strings"
)
type Terminal interface {
Exec(cmd string) (out []byte, err error)
ExecPath(cmd, path string) (out []byte, err error)
SetEnv(name, value string)
Close()
}
type LocalTerminal struct {
env map[string]string
}
func (t *LocalTerminal) ExecPath(cmd, path string) (out []byte, err error) {
args, err := shellquote.Split(cmd)
if err != nil {
return
}
command := exec.Command(args[0], args[1:]...)
command.Env = t.getEnv()
if path != "" {
command.Dir = path
}
return command.CombinedOutput()
}
func (t *LocalTerminal) SetEnv(name, value string) {
if t.env == nil {
t.env = make(map[string]string, 0)
}
t.env[name] = value
}
func (t *LocalTerminal) Exec(cmd string) (out []byte, err error) {
return t.ExecPath(cmd, "")
}
func (t *LocalTerminal) getEnv() []string {
env := make([]string, 0, 5)
for _, v := range os.Environ() {
parts := strings.Split(v, "=")
if _, ok := t.env[parts[0]]; !ok {
env = append(env, v)
}
}
for k, v := range t.env {
env = append(env, k+"="+v)
}
return env
}
func (t *LocalTerminal) Close() {
// noop
}