genpb.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package gen
  2. import (
  3. "bytes"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "github.com/tal-tech/go-zero/core/collection"
  8. "github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
  9. "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
  10. )
  11. const (
  12. protocCmd = "protoc"
  13. grpcPluginCmd = "--go_out=plugins=grpc"
  14. )
  15. func (g *defaultRpcGenerator) genPb() error {
  16. pbPath := g.dirM[dirPb]
  17. imports, containsAny, err := parser.ParseImport(g.Ctx.ProtoFileSrc)
  18. if err != nil {
  19. return err
  20. }
  21. err = g.protocGenGo(pbPath, imports)
  22. if err != nil {
  23. return err
  24. }
  25. ast, err := parser.Transfer(g.Ctx.ProtoFileSrc, pbPath, imports, g.Ctx.Console)
  26. if err != nil {
  27. return err
  28. }
  29. ast.ContainsAny = containsAny
  30. if len(ast.Service) == 0 {
  31. return fmt.Errorf("service not found")
  32. }
  33. g.ast = ast
  34. return nil
  35. }
  36. func (g *defaultRpcGenerator) protocGenGo(target string, imports []*parser.Import) error {
  37. dir := filepath.Dir(g.Ctx.ProtoFileSrc)
  38. // cmd join,see the document of proto generating class @https://developers.google.com/protocol-buffers/docs/proto3#generating
  39. // template: protoc -I=${import_path} -I=${other_import_path} -I=${...} --go_out=plugins=grpc,M${pb_package_kv}, M${...} :${target_dir}
  40. // eg: protoc -I=${GOPATH}/src -I=. example.proto --go_out=plugins=grpc,Mbase/base.proto=github.com/go-zero/base.proto:.
  41. // note: the external import out of the project which are found in ${GOPATH}/src so far.
  42. buffer := new(bytes.Buffer)
  43. buffer.WriteString(protocCmd + " ")
  44. targetImportFiltered := collection.NewSet()
  45. for _, item := range imports {
  46. buffer.WriteString(fmt.Sprintf("-I=%s ", item.OriginalDir))
  47. if len(item.BridgeImport) == 0 {
  48. continue
  49. }
  50. targetImportFiltered.AddStr(item.BridgeImport)
  51. }
  52. buffer.WriteString("-I=${GOPATH}/src ")
  53. buffer.WriteString(fmt.Sprintf("-I=%s %s ", dir, g.Ctx.ProtoFileSrc))
  54. buffer.WriteString(grpcPluginCmd)
  55. if targetImportFiltered.Count() > 0 {
  56. buffer.WriteString(fmt.Sprintf(",%v", strings.Join(targetImportFiltered.KeysStr(), ",")))
  57. }
  58. buffer.WriteString(":" + target)
  59. g.Ctx.Debug("-> " + buffer.String())
  60. stdout, err := execx.Run(buffer.String(), "")
  61. if err != nil {
  62. return err
  63. }
  64. if len(stdout) > 0 {
  65. g.Ctx.Info(stdout)
  66. }
  67. return nil
  68. }