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
|
package utils
import (
"fmt"
"os/exec"
"strings"
)
// CliError is an error of cli command
type CliError struct {
Err error
Cmd string
}
func (c *CliError) Error() string {
return fmt.Sprintf("%v\n\nThe command was:\n%v", c.Err, c.Cmd)
}
// GetCmdStr returns the string of a command
func GetCmdStr(bin string, args []string) string {
s := bin
for _, a := range args {
if strings.Index(a, "\"") > -1 {
a = strings.Replace(a, "\"", "\\\"", -1)
}
s += fmt.Sprintf(" %v", a)
}
return s
}
// Exec a command
func Exec(bin string, args []string) (string, error) {
cmd := exec.Command(bin, args...)
out, err := cmd.CombinedOutput()
if err != nil {
return "", &CliError{Err: err, Cmd: GetCmdStr(bin, args)}
}
return string(out), nil
}
|