protocgengo.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package protocgengo
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/zeromicro/go-zero/tools/goctl/pkg/goctl"
  6. "github.com/zeromicro/go-zero/tools/goctl/pkg/golang"
  7. "github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
  8. "github.com/zeromicro/go-zero/tools/goctl/util/env"
  9. )
  10. const (
  11. Name = "protoc-gen-go"
  12. url = "google.golang.org/protobuf/cmd/protoc-gen-go@latest"
  13. )
  14. func Install(cacheDir string) (string, error) {
  15. return goctl.Install(cacheDir, Name, func(dest string) (string, error) {
  16. err := golang.Install(url)
  17. return dest, err
  18. })
  19. }
  20. func Exists() bool {
  21. ver, err := Version()
  22. if err != nil {
  23. return false
  24. }
  25. return len(ver) > 0
  26. }
  27. // Version is used to get the version of the protoc-gen-go plugin. For older versions, protoc-gen-go does not support
  28. // version fetching, so if protoc-gen-go --version is executed, it will cause the process to block, so it is controlled
  29. // by a timer to prevent the older version process from blocking.
  30. func Version() (string, error) {
  31. path, err := env.LookUpProtocGenGo()
  32. if err != nil {
  33. return "", err
  34. }
  35. versionC := make(chan string)
  36. go func(c chan string) {
  37. version, _ := execx.Run(path+" --version", "")
  38. fields := strings.Fields(version)
  39. if len(fields) > 1 {
  40. c <- fields[1]
  41. }
  42. }(versionC)
  43. t := time.NewTimer(time.Second)
  44. select {
  45. case <-t.C:
  46. return "", nil
  47. case version := <-versionC:
  48. return version, nil
  49. }
  50. }