execx.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package execx
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  10. "github.com/zeromicro/go-zero/tools/goctl/vars"
  11. )
  12. // RunFunc defines a function type of Run function
  13. type RunFunc func(string, string, ...*bytes.Buffer) (string, error)
  14. // Run provides the execution of shell scripts in golang,
  15. // which can support macOS, Windows, and Linux operating systems.
  16. // Other operating systems are currently not supported
  17. func Run(arg, dir string, in ...*bytes.Buffer) (string, error) {
  18. goos := runtime.GOOS
  19. var cmd *exec.Cmd
  20. switch goos {
  21. case vars.OsMac, vars.OsLinux:
  22. cmd = exec.Command("sh", "-c", arg)
  23. case vars.OsWindows:
  24. cmd = exec.Command("cmd.exe", "/c", arg)
  25. default:
  26. return "", fmt.Errorf("unexpected os: %v", goos)
  27. }
  28. if len(dir) > 0 {
  29. cmd.Dir = dir
  30. }
  31. stdout := new(bytes.Buffer)
  32. stderr := new(bytes.Buffer)
  33. if len(in) > 0 {
  34. cmd.Stdin = in[0]
  35. }
  36. cmd.Stdout = stdout
  37. cmd.Stderr = stderr
  38. err := cmd.Run()
  39. if err != nil {
  40. if stderr.Len() > 0 {
  41. return "", errors.New(strings.TrimSuffix(stderr.String(), pathx.NL))
  42. }
  43. return "", err
  44. }
  45. return strings.TrimSuffix(stdout.String(), pathx.NL), nil
  46. }