-
Notifications
You must be signed in to change notification settings - Fork 0
/
execx.go
42 lines (38 loc) · 842 Bytes
/
execx.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
package execx
import (
"bytes"
"errors"
"fmt"
"os/exec"
"runtime"
"strings"
"github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars"
)
func Run(arg string, dir string) (string, error) {
goos := runtime.GOOS
var cmd *exec.Cmd
switch goos {
case vars.OsMac, vars.OsLinux:
cmd = exec.Command("sh", "-c", arg)
case vars.OsWindows:
cmd = exec.Command("cmd.exe", "/c", arg)
default:
return "", fmt.Errorf("unexpected os: %v", goos)
}
if len(dir) > 0 {
cmd.Dir = dir
}
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
cmd.Stdout = stdout
cmd.Stderr = stderr
err := cmd.Run()
if err != nil {
if stderr.Len() > 0 {
return "", errors.New(strings.TrimSuffix(stderr.String(), util.NL))
}
return "", err
}
return strings.TrimSuffix(stdout.String(), util.NL), nil
}