-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathruncmd.go
68 lines (59 loc) · 1.55 KB
/
runcmd.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
package main
import (
// "fmt"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
)
func runCmdInternal(dir string, cmd []string) error {
exec := exec.Command(cmd[0], cmd[1:]...)
exec.Dir = dir
exec.Stdin = os.Stdin
exec.Stdout = os.Stdout
exec.Stderr = os.Stderr
err := exec.Run()
return err
}
// receives
// ["git add $FILES", "$FILES", ["a","b"] ]
// returns
// ["git", "add", "a", "b"]
func expandInArray(arr []string, when string, with []string) []string {
expanded := make([]string, 0, len(arr))
for _, e := range arr {
if e == when {
for _, arg := range with {
expanded = append(expanded, arg)
}
} else {
expanded = append(expanded, e)
}
}
return expanded
}
// On OSX, both shell=true and shell=false work w/ GUI apps. Both work with text vim too.
// On Windows, I think GUI apps will lock the command prompt if shell=false (CHECK).
//
// Are there any disadvantadges in always using shell=true?
func runCmdWithArgs(dir string, userCommand string, shell bool, files []string) error {
var cmd []string
cmd = strings.Split(userCommand, " ")
cmd = expandInArray(cmd, "$FILES", files)
if shell {
if runtime.GOOS == "windows" {
cmd = append([]string{"cmd", "/c"}, cmd...)
} else {
cmd = []string{"sh", "-c"}
quotedFiles := make([]string, len(files))
for i, f := range files {
quotedFiles[i] = strconv.Quote(f)
}
filesString := strings.Join(quotedFiles, " ")
cmdReplaced := strings.Replace(userCommand, "$FILES", filesString, -1)
cmd = append(cmd, cmdReplaced)
}
}
return runCmdInternal(dir, cmd)
}