-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
53 lines (43 loc) · 1014 Bytes
/
exec.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
package helper
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"github.com/4nkitd/gobackup/logger"
)
var (
spaceRegexp = regexp.MustCompile("[\\s]+")
)
// Exec cli commands
func Exec(command string, args ...string) (output string, err error) {
commands := spaceRegexp.Split(command, -1)
command = commands[0]
commandArgs := []string{}
if len(commands) > 1 {
commandArgs = commands[1:]
}
if len(args) > 0 {
commandArgs = append(commandArgs, args...)
}
fullCommand, err := exec.LookPath(command)
if err != nil {
return "", fmt.Errorf("%s cannot be found", command)
}
cmd := exec.Command(fullCommand, commandArgs...)
cmd.Env = os.Environ()
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
// logger.Debug(fullCommand, " ", strings.Join(commandArgs, " "))
out, err := cmd.Output()
if err != nil {
logger.Debug(fullCommand, " ", strings.Join(commandArgs, " "))
err = errors.New(stdErr.String())
return
}
output = strings.Trim(string(out), "\n")
return
}