env.go 1.8 KB

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