execx.go 904 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package execx
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/vars"
  11. )
  12. func Run(arg string, dir string, in ...*bytes.Buffer) (string, error) {
  13. goos := runtime.GOOS
  14. var cmd *exec.Cmd
  15. switch goos {
  16. case vars.OsMac, vars.OsLinux:
  17. cmd = exec.Command("sh", "-c", arg)
  18. case vars.OsWindows:
  19. cmd = exec.Command("cmd.exe", "/c", arg)
  20. default:
  21. return "", fmt.Errorf("unexpected os: %v", goos)
  22. }
  23. if len(dir) > 0 {
  24. cmd.Dir = dir
  25. }
  26. stdout := new(bytes.Buffer)
  27. stderr := new(bytes.Buffer)
  28. if len(in) > 0 {
  29. cmd.Stdin = in[0]
  30. }
  31. cmd.Stdout = stdout
  32. cmd.Stderr = stderr
  33. err := cmd.Run()
  34. if err != nil {
  35. if stderr.Len() > 0 {
  36. return "", errors.New(strings.TrimSuffix(stderr.String(), util.NL))
  37. }
  38. return "", err
  39. }
  40. return strings.TrimSuffix(stdout.String(), util.NL), nil
  41. }