templatex.go 1.5 KB

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