gen.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package generator
  2. import (
  3. "path/filepath"
  4. conf "github.com/tal-tech/go-zero/tools/goctl/config"
  5. "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
  6. "github.com/tal-tech/go-zero/tools/goctl/util"
  7. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/ctx"
  9. )
  10. // RPCGenerator defines a generator and configure
  11. type RPCGenerator struct {
  12. g Generator
  13. cfg *conf.Config
  14. }
  15. // NewDefaultRPCGenerator wraps Generator with configure
  16. func NewDefaultRPCGenerator(style string) (*RPCGenerator, error) {
  17. cfg, err := conf.NewConfig(style)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return NewRPCGenerator(NewDefaultGenerator(), cfg), nil
  22. }
  23. // NewRPCGenerator creates an instance for RPCGenerator
  24. func NewRPCGenerator(g Generator, cfg *conf.Config) *RPCGenerator {
  25. return &RPCGenerator{
  26. g: g,
  27. cfg: cfg,
  28. }
  29. }
  30. // Generate generates an rpc service, through the proto file,
  31. // code storage directory, and proto import parameters to control
  32. // the source file and target location of the rpc service that needs to be generated
  33. func (g *RPCGenerator) Generate(src, target string, protoImportPath []string) error {
  34. abs, err := filepath.Abs(target)
  35. if err != nil {
  36. return err
  37. }
  38. err = util.MkdirIfNotExist(abs)
  39. if err != nil {
  40. return err
  41. }
  42. err = g.g.Prepare()
  43. if err != nil {
  44. return err
  45. }
  46. projectCtx, err := ctx.Prepare(abs)
  47. if err != nil {
  48. return err
  49. }
  50. p := parser.NewDefaultProtoParser()
  51. proto, err := p.Parse(src)
  52. if err != nil {
  53. return err
  54. }
  55. dirCtx, err := mkdir(projectCtx, proto)
  56. if err != nil {
  57. return err
  58. }
  59. err = g.g.GenEtc(dirCtx, proto, g.cfg)
  60. if err != nil {
  61. return err
  62. }
  63. err = g.g.GenPb(dirCtx, protoImportPath, proto, g.cfg)
  64. if err != nil {
  65. return err
  66. }
  67. err = g.g.GenConfig(dirCtx, proto, g.cfg)
  68. if err != nil {
  69. return err
  70. }
  71. err = g.g.GenSvc(dirCtx, proto, g.cfg)
  72. if err != nil {
  73. return err
  74. }
  75. err = g.g.GenLogic(dirCtx, proto, g.cfg)
  76. if err != nil {
  77. return err
  78. }
  79. err = g.g.GenServer(dirCtx, proto, g.cfg)
  80. if err != nil {
  81. return err
  82. }
  83. err = g.g.GenMain(dirCtx, proto, g.cfg)
  84. if err != nil {
  85. return err
  86. }
  87. err = g.g.GenCall(dirCtx, proto, g.cfg)
  88. console.NewColorConsole().MarkDone()
  89. return err
  90. }