gen.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. type RpcGenerator struct {
  11. g Generator
  12. cfg *conf.Config
  13. }
  14. func NewDefaultRpcGenerator(style string) (*RpcGenerator, error) {
  15. cfg, err := conf.NewConfig(style)
  16. if err != nil {
  17. return nil, err
  18. }
  19. return NewRpcGenerator(NewDefaultGenerator(), cfg), nil
  20. }
  21. func NewRpcGenerator(g Generator, cfg *conf.Config) *RpcGenerator {
  22. return &RpcGenerator{
  23. g: g,
  24. cfg: cfg,
  25. }
  26. }
  27. func (g *RpcGenerator) Generate(src, target string, protoImportPath []string) error {
  28. abs, err := filepath.Abs(target)
  29. if err != nil {
  30. return err
  31. }
  32. err = util.MkdirIfNotExist(abs)
  33. if err != nil {
  34. return err
  35. }
  36. err = g.g.Prepare()
  37. if err != nil {
  38. return err
  39. }
  40. projectCtx, err := ctx.Prepare(abs)
  41. if err != nil {
  42. return err
  43. }
  44. p := parser.NewDefaultProtoParser()
  45. proto, err := p.Parse(src)
  46. if err != nil {
  47. return err
  48. }
  49. dirCtx, err := mkdir(projectCtx, proto)
  50. if err != nil {
  51. return err
  52. }
  53. err = g.g.GenEtc(dirCtx, proto, g.cfg)
  54. if err != nil {
  55. return err
  56. }
  57. err = g.g.GenPb(dirCtx, protoImportPath, proto, g.cfg)
  58. if err != nil {
  59. return err
  60. }
  61. err = g.g.GenConfig(dirCtx, proto, g.cfg)
  62. if err != nil {
  63. return err
  64. }
  65. err = g.g.GenSvc(dirCtx, proto, g.cfg)
  66. if err != nil {
  67. return err
  68. }
  69. err = g.g.GenLogic(dirCtx, proto, g.cfg)
  70. if err != nil {
  71. return err
  72. }
  73. err = g.g.GenServer(dirCtx, proto, g.cfg)
  74. if err != nil {
  75. return err
  76. }
  77. err = g.g.GenMain(dirCtx, proto, g.cfg)
  78. if err != nil {
  79. return err
  80. }
  81. err = g.g.GenCall(dirCtx, proto, g.cfg)
  82. console.NewColorConsole().MarkDone()
  83. return err
  84. }