forked from estebangarcia21/subprocess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spawner.go
89 lines (78 loc) · 2.14 KB
/
spawner.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
package subprocess
import (
"fmt"
"os/exec"
"runtime"
"strings"
)
// spawner is a command located in the system's PATH that begins the
// process. Each major operating system has its own spawner.
//
// Each key is PATH command that can open the process. Their position in
// the map determines their priority. For example, if the first
// command is not present in the PATH then it will attempt to use the
// second command and so on.
//
// Each value is an optional set of flags that will be passed to the command.
type spawner map[string][]string
var (
windowsSpawner = spawner{
"cmd": {"/C", "powershell", "-Command"},
}
macSpawner = spawner{
"bash": {"-c"},
"sh": {"-c"},
}
linuxSpawner = spawner{
"bash": {"-c"},
"sh": {"-c"},
}
)
// CreateCommand creates an exec.Cmd that is prepared with the root command.
func (s spawner) CreateCommand(cmd string, args []string, shell bool, os string) (*exec.Cmd, error) {
spawnCmd, err := s.getAvailableSpawnCommand()
if err != nil {
return nil, err
}
if shell || os == "windows" {
cmdStr := fmt.Sprintf("%s %s", cmd, strings.Join(args, " "))
return exec.Command(spawnCmd, append(s[spawnCmd], cmdStr)...), nil
}
return exec.Command(cmd, args...), nil
}
// getAvailableSpawnCommand gets the first available spawn command. It returns
// an error if no command is available.
func (s spawner) getAvailableSpawnCommand() (string, error) {
var cmd string
for k := range s {
if _, err := exec.LookPath(k); err != nil {
continue
}
cmd = k
break
}
if cmd == "" {
keys := make([]string, 0, len(s))
for k := range s {
keys = append(keys, k)
}
return "", fmt.Errorf("no available subprocess spawner found in the system PATH. Available spawners for your OS: %s", strings.Join(keys, ", "))
}
return cmd, nil
}
// spawnerFromOS returns the proper process spawner and OS (computed from GOOS).
func spawnerFromOS() (spawner, string, error) {
os := runtime.GOOS
var s spawner
switch os {
case "windows":
s = windowsSpawner
case "darwin":
s = macSpawner
case "linux":
s = linuxSpawner
default:
return s, os, fmt.Errorf("unsupported operating system %s", os)
}
return s, os, nil
}