-
Notifications
You must be signed in to change notification settings - Fork 12
/
cmd.go
84 lines (75 loc) · 1.67 KB
/
cmd.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
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
)
func NewGitCmd(args []string) *Command {
gitCmd := &Command{
Name: "git",
Args: args,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
return gitCmd
}
type Command struct {
Name string
Args []string
Stdin *os.File
Stdout *os.File
Stderr *os.File
}
func (cmd Command) String() string {
return fmt.Sprintf("%s %s", cmd.Name, strings.Join(cmd.Args, " "))
}
// Run runs command with `Exec` on platforms except Windows
// which only supports `Spawn`
func (cmd *Command) Run() error {
if isWindows() {
return cmd.Spawn()
} else {
return cmd.Exec()
}
}
func isWindows() bool {
return runtime.GOOS == "windows" || detectWSL()
}
// https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364
func detectWSL() bool {
var detectedWSLContents string
b := make([]byte, 1024)
f, err := os.Open("/proc/version")
if err == nil {
f.Read(b)
f.Close()
detectedWSLContents = string(b)
}
return strings.Contains(detectedWSLContents, "Microsoft")
}
// Spawn runs command with spawn(3)
func (cmd *Command) Spawn() error {
c := exec.Command(cmd.Name, cmd.Args...)
c.Stdin = cmd.Stdin
c.Stdout = cmd.Stdout
c.Stderr = cmd.Stderr
return c.Run()
}
// Exec runs command with exec(3)
// Note that Windows doesn't support exec(3): http://golang.org/src/pkg/syscall/exec_windows.go#L339
func (cmd *Command) Exec() error {
binary, err := exec.LookPath(cmd.Name)
if err != nil {
return &exec.Error{
Name: cmd.Name,
Err: fmt.Errorf("command not found"),
}
}
args := []string{binary}
args = append(args, cmd.Args...)
return syscall.Exec(binary, args, os.Environ())
}