genpb.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package generator
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/rpc/execx"
  9. )
  10. // GenPb generates the pb.go file, which is a layer of packaging for protoc to generate gprc,
  11. // but the commands and flags in protoc are not completely joined in goctl. At present, proto_path(-I) is introduced
  12. func (g *Generator) GenPb(ctx DirContext, c *ZRpcContext) error {
  13. return g.genPbDirect(ctx, c)
  14. }
  15. func (g *Generator) genPbDirect(ctx DirContext, c *ZRpcContext) error {
  16. g.log.Debug("[command]: %s", c.ProtocCmd)
  17. pwd, err := os.Getwd()
  18. if err != nil {
  19. return err
  20. }
  21. _, err = execx.Run(c.ProtocCmd, pwd)
  22. if err != nil {
  23. return err
  24. }
  25. return g.setPbDir(ctx, c)
  26. }
  27. func (g *Generator) setPbDir(ctx DirContext, c *ZRpcContext) error {
  28. pbDir, err := findPbFile(c.GoOutput, c.Src, false)
  29. if err != nil {
  30. return err
  31. }
  32. if len(pbDir) == 0 {
  33. return fmt.Errorf("pg.go is not found under %q", c.GoOutput)
  34. }
  35. grpcDir, err := findPbFile(c.GrpcOutput, c.Src, true)
  36. if err != nil {
  37. return err
  38. }
  39. if len(grpcDir) == 0 {
  40. return fmt.Errorf("_grpc.pb.go is not found in %q", c.GrpcOutput)
  41. }
  42. if pbDir != grpcDir {
  43. return fmt.Errorf("the pb.go and _grpc.pb.go must under the same dir: "+
  44. "\n pb.go: %s\n_grpc.pb.go: %s", pbDir, grpcDir)
  45. }
  46. if pbDir == c.Output {
  47. return fmt.Errorf("the output of pb.go and _grpc.pb.go must not be the same "+
  48. "with --zrpc_out:\npb output: %s\nzrpc out: %s", pbDir, c.Output)
  49. }
  50. ctx.SetPbDir(pbDir, grpcDir)
  51. return nil
  52. }
  53. const (
  54. pbSuffix = "pb.go"
  55. grpcSuffix = "_grpc.pb.go"
  56. )
  57. func findPbFile(current string, src string, grpc bool) (string, error) {
  58. protoName := strings.TrimSuffix(filepath.Base(src), filepath.Ext(src))
  59. pbFile := protoName + "." + pbSuffix
  60. grpcFile := protoName + grpcSuffix
  61. fileSystem := os.DirFS(current)
  62. var ret string
  63. err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
  64. if d.IsDir() {
  65. return nil
  66. }
  67. if strings.HasSuffix(path, pbSuffix) {
  68. if grpc {
  69. if strings.HasSuffix(path, grpcFile) {
  70. ret = path
  71. return os.ErrExist
  72. }
  73. } else if strings.HasSuffix(path, pbFile) {
  74. ret = path
  75. return os.ErrExist
  76. }
  77. }
  78. return nil
  79. })
  80. if err == os.ErrExist {
  81. return filepath.Dir(filepath.Join(current, ret)), nil
  82. }
  83. return "", err
  84. }