genpb.go 2.2 KB

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