protocgengo.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. _, err := env.LookUpProtocGenGo()
  22. return err == nil
  23. }
  24. // Version is used to get the version of the protoc-gen-go plugin. For older versions, protoc-gen-go does not support
  25. // version fetching, so if protoc-gen-go --version is executed, it will cause the process to block, so it is controlled
  26. // by a timer to prevent the older version process from blocking.
  27. func Version() (string, error) {
  28. path, err := env.LookUpProtocGenGo()
  29. if err != nil {
  30. return "", err
  31. }
  32. versionC := make(chan string)
  33. go func(c chan string) {
  34. version, _ := execx.Run(path+" --version", "")
  35. fields := strings.Fields(version)
  36. if len(fields) > 1 {
  37. c <- fields[1]
  38. }
  39. }(versionC)
  40. t := time.NewTimer(time.Second)
  41. select {
  42. case <-t.C:
  43. return "", nil
  44. case version := <-versionC:
  45. return version, nil
  46. }
  47. }