env.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package env
  2. import (
  3. "os"
  4. "os/exec"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. "github.com/zeromicro/go-zero/tools/goctl/vars"
  9. )
  10. const (
  11. bin = "bin"
  12. binGo = "go"
  13. binProtoc = "protoc"
  14. binProtocGenGo = "protoc-gen-go"
  15. binProtocGenGrpcGo = "protoc-gen-go-grpc"
  16. )
  17. // LookUpGo searches an executable go in the directories
  18. // named by the GOROOT/bin or PATH environment variable.
  19. func LookUpGo() (string, error) {
  20. goRoot := runtime.GOROOT()
  21. suffix := getExeSuffix()
  22. xGo := binGo + suffix
  23. path := filepath.Join(goRoot, bin, xGo)
  24. if _, err := os.Stat(path); err == nil {
  25. return path, nil
  26. }
  27. return LookPath(xGo)
  28. }
  29. // LookUpProtoc searches an executable protoc in the directories
  30. // named by the PATH environment variable.
  31. func LookUpProtoc() (string, error) {
  32. suffix := getExeSuffix()
  33. xProtoc := binProtoc + suffix
  34. return LookPath(xProtoc)
  35. }
  36. // LookUpProtocGenGo searches an executable protoc-gen-go in the directories
  37. // named by the PATH environment variable.
  38. func LookUpProtocGenGo() (string, error) {
  39. suffix := getExeSuffix()
  40. xProtocGenGo := binProtocGenGo + suffix
  41. return LookPath(xProtocGenGo)
  42. }
  43. // LookUpProtocGenGoGrpc searches an executable protoc-gen-go-grpc in the directories
  44. // named by the PATH environment variable.
  45. func LookUpProtocGenGoGrpc() (string, error) {
  46. suffix := getExeSuffix()
  47. xProtocGenGoGrpc := binProtocGenGrpcGo + suffix
  48. return LookPath(xProtocGenGoGrpc)
  49. }
  50. // LookPath searches for an executable named file in the
  51. // directories named by the PATH environment variable,
  52. // for the os windows, the named file will be spliced with the
  53. // .exe suffix.
  54. func LookPath(xBin string) (string, error) {
  55. suffix := getExeSuffix()
  56. if len(suffix) > 0 && !strings.HasSuffix(xBin, suffix) {
  57. xBin = xBin + suffix
  58. }
  59. bin, err := exec.LookPath(xBin)
  60. if err != nil {
  61. return "", err
  62. }
  63. return bin, nil
  64. }
  65. // CanExec reports whether the current system can start new processes
  66. // using os.StartProcess or (more commonly) exec.Command.
  67. func CanExec() bool {
  68. switch runtime.GOOS {
  69. case vars.OsJs, vars.OsIOS:
  70. return false
  71. default:
  72. return true
  73. }
  74. }
  75. func getExeSuffix() string {
  76. if runtime.GOOS == vars.OsWindows {
  77. return ".exe"
  78. }
  79. return ""
  80. }