generate.go 1.5 KB

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