-
Notifications
You must be signed in to change notification settings - Fork 7
/
shell.go
105 lines (90 loc) · 2.58 KB
/
shell.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
package tools
import (
"os"
"os/exec"
"runtime"
"strings"
)
// stringLiteral is a type of string that cannot be passed as a variable.
// This helps to avoid code injection by enforcing executable names to be hard coded.
type stringLiteral string
// CommandInShell sets up a new command with the environment set up by user's environment.
// In darwin or other Unix systems the shell will be loaded by running the terminal and accessing env command.
// The command is run directly so stdout and stderr can be read directly from the returned `exec.Cmd`.
// The cmd parameter must be a string constant to avoid possible code injection attacks.
func CommandInShell(cmd stringLiteral, args ...string) *exec.Cmd {
// lookup command path in target env
path := string(cmd)
if runtime.GOOS == "darwin" {
data, err := runInShell("which", path).Output()
if err == nil {
// parse lines as shell can output header
lines := strings.Split(string(data), "\n")
if len(lines) > 0 {
path = lines[len(lines)-1]
// possibly trailing empty line
if path == "" && len(lines) > 1 {
path = lines[len(lines)-2]
}
}
}
}
return runInShell(path, args...)
}
func runInShell(cmd string, args ...string) *exec.Cmd {
var env []string
switch runtime.GOOS {
case "darwin": // darwin apps don't run in the user shell environment
args = quoteArgs(args...)
data, err := exec.Command(getDarwinShell(), "-c", "-i", "env").Output()
if err == nil {
env = strings.Split(string(data), "\n")
}
case "linux", "freebsd", "netbsd", "openbsd", "dragonflybsd": // unix environment may be set up in shell
args = quoteArgs(args...)
data, err := exec.Command(getUnixShell(), "-c", "env").Output()
if err == nil {
env = strings.Split(string(data), "\n")
}
}
run := exec.Command(cmd, args...)
run.Env = append(run.Env, env...)
return run
}
func quoteArgs(args ...string) []string {
ret := make([]string, len(args))
for i, s := range args {
if strings.Contains(s, " ") {
ret[i] = quoteString(s)
} else {
ret[i] = args[i]
}
}
return ret
}
func quoteString(s string) string {
s = strings.ReplaceAll(s, "\"", "\\\"")
return "\"" + s + "\""
}
func getDarwinShell() string {
home, err := os.UserHomeDir()
if err != nil {
return "zsh"
}
out, err := exec.Command("dscl", ".", "-read", home, "UserShell").Output()
if err != nil {
return "zsh"
}
items := strings.Split(string(out), ":")
if len(items) < 2 {
return "zsh"
}
return strings.TrimSpace(items[1])
}
func getUnixShell() string {
shell, ok := os.LookupEnv("SHELL")
if !ok || shell == "" {
return "/bin/sh"
}
return shell
}