generate.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package generate
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "github.com/tal-tech/go-zero/tools/goctl/config"
  6. "github.com/tal-tech/go-zero/tools/goctl/model/mongo/template"
  7. "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  9. )
  10. // Context defines the model generation data what they needs
  11. type Context struct {
  12. Types []string
  13. Cache bool
  14. Output string
  15. Cfg *config.Config
  16. }
  17. // Do executes model template and output the result into the specified file path
  18. func Do(ctx *Context) error {
  19. if ctx.Cfg == nil {
  20. return errors.New("missing config")
  21. }
  22. err := generateModel(ctx)
  23. if err != nil {
  24. return err
  25. }
  26. return generateError(ctx)
  27. }
  28. func generateModel(ctx *Context) error {
  29. for _, t := range ctx.Types {
  30. fn, err := format.FileNamingFormat(ctx.Cfg.NamingFormat, t+"_model")
  31. if err != nil {
  32. return err
  33. }
  34. text, err := util.LoadTemplate(category, modelTemplateFile, template.Text)
  35. if err != nil {
  36. return err
  37. }
  38. output := filepath.Join(ctx.Output, fn+".go")
  39. err = util.With("model").Parse(text).GoFmt(true).SaveTo(map[string]interface{}{
  40. "Type": t,
  41. "Cache": ctx.Cache,
  42. }, output, false)
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. return nil
  48. }
  49. func generateError(ctx *Context) error {
  50. text, err := util.LoadTemplate(category, errTemplateFile, template.Error)
  51. if err != nil {
  52. return err
  53. }
  54. output := filepath.Join(ctx.Output, "error.go")
  55. return util.With("error").Parse(text).GoFmt(true).SaveTo(ctx, output, false)
  56. }