templatex.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package util
  2. import (
  3. "bytes"
  4. goformat "go/format"
  5. "io/ioutil"
  6. "text/template"
  7. "github.com/zeromicro/go-zero/tools/goctl/internal/errorx"
  8. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  9. )
  10. const regularPerm = 0o666
  11. // DefaultTemplate is a tool to provides the text/template operations
  12. type DefaultTemplate struct {
  13. name string
  14. text string
  15. goFmt bool
  16. }
  17. // With returns a instance of DefaultTemplate
  18. func With(name string) *DefaultTemplate {
  19. return &DefaultTemplate{
  20. name: name,
  21. }
  22. }
  23. // Parse accepts a source template and returns DefaultTemplate
  24. func (t *DefaultTemplate) Parse(text string) *DefaultTemplate {
  25. t.text = text
  26. return t
  27. }
  28. // GoFmt sets the value to goFmt and marks the generated codes will be formatted or not
  29. func (t *DefaultTemplate) GoFmt(format bool) *DefaultTemplate {
  30. t.goFmt = format
  31. return t
  32. }
  33. // SaveTo writes the codes to the target path
  34. func (t *DefaultTemplate) SaveTo(data interface{}, path string, forceUpdate bool) error {
  35. if pathx.FileExists(path) && !forceUpdate {
  36. return nil
  37. }
  38. output, err := t.Execute(data)
  39. if err != nil {
  40. return err
  41. }
  42. return ioutil.WriteFile(path, output.Bytes(), regularPerm)
  43. }
  44. // Execute returns the codes after the template executed
  45. func (t *DefaultTemplate) Execute(data interface{}) (*bytes.Buffer, error) {
  46. tem, err := template.New(t.name).Parse(t.text)
  47. if err != nil {
  48. return nil, errorx.Wrap(err, "template parse error:", t.text)
  49. }
  50. buf := new(bytes.Buffer)
  51. if err = tem.Execute(buf, data); err != nil {
  52. return nil, errorx.Wrap(err, "template execute error:", t.text)
  53. }
  54. if !t.goFmt {
  55. return buf, nil
  56. }
  57. formatOutput, err := goformat.Source(buf.Bytes())
  58. if err != nil {
  59. return nil, errorx.Wrap(err, "go format error:", buf.String())
  60. }
  61. buf.Reset()
  62. buf.Write(formatOutput)
  63. return buf, nil
  64. }