genpb.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package generator
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/zeromicro/go-zero/tools/goctl/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, 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, 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, grpc bool) (string, error) {
  58. fileSystem := os.DirFS(current)
  59. var ret string
  60. err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
  61. if d.IsDir() {
  62. return nil
  63. }
  64. if strings.HasSuffix(path, pbSuffix) {
  65. if grpc {
  66. if strings.HasSuffix(path, grpcSuffix) {
  67. ret = path
  68. return os.ErrExist
  69. }
  70. } else if !strings.HasSuffix(path, grpcSuffix) {
  71. ret = path
  72. return os.ErrExist
  73. }
  74. }
  75. return nil
  76. })
  77. if err == os.ErrExist {
  78. return filepath.Dir(filepath.Join(current, ret)), nil
  79. }
  80. return "", err
  81. }