go-zero/tools/goctl/util/templatex.go

96 lines
2.2 KiB
Go
Raw Normal View History

package util
import (
"bytes"
goformat "go/format"
"io/ioutil"
"regexp"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/internal/errorx"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
2021-04-15 19:49:17 +08:00
const regularPerm = 0o666
2020-10-15 16:36:49 +08:00
2021-02-20 19:50:03 +08:00
// DefaultTemplate is a tool to provides the text/template operations
type DefaultTemplate struct {
2021-09-29 13:09:20 +08:00
name string
text string
goFmt bool
2020-10-15 16:36:49 +08:00
}
2022-11-04 21:55:17 +08:00
// With returns an instance of DefaultTemplate
2021-02-20 19:50:03 +08:00
func With(name string) *DefaultTemplate {
return &DefaultTemplate{
name: name,
}
}
2021-02-20 19:50:03 +08:00
// Parse accepts a source template and returns DefaultTemplate
func (t *DefaultTemplate) Parse(text string) *DefaultTemplate {
t.text = text
return t
}
2021-03-08 18:23:12 +08:00
// GoFmt sets the value to goFmt and marks the generated codes will be formatted or not
2021-02-20 19:50:03 +08:00
func (t *DefaultTemplate) GoFmt(format bool) *DefaultTemplate {
t.goFmt = format
return t
}
2021-02-20 19:50:03 +08:00
// SaveTo writes the codes to the target path
func (t *DefaultTemplate) SaveTo(data any, path string, forceUpdate bool) error {
if pathx.FileExists(path) && !forceUpdate {
return nil
}
2020-10-15 16:36:49 +08:00
output, err := t.Execute(data)
if err != nil {
return err
}
2020-10-15 16:36:49 +08:00
return ioutil.WriteFile(path, output.Bytes(), regularPerm)
}
2021-02-20 19:50:03 +08:00
// Execute returns the codes after the template executed
func (t *DefaultTemplate) Execute(data any) (*bytes.Buffer, error) {
tem, err := template.New(t.name).Parse(t.text)
if err != nil {
return nil, errorx.Wrap(err, "template parse error:", t.text)
}
2020-10-15 16:36:49 +08:00
buf := new(bytes.Buffer)
2020-10-15 16:36:49 +08:00
if err = tem.Execute(buf, data); err != nil {
return nil, errorx.Wrap(err, "template execute error:", t.text)
}
2020-10-15 16:36:49 +08:00
if !t.goFmt {
return buf, nil
}
2020-10-15 16:36:49 +08:00
formatOutput, err := goformat.Source(buf.Bytes())
if err != nil {
2021-09-29 13:09:20 +08:00
return nil, errorx.Wrap(err, "go format error:", buf.String())
}
2020-10-15 16:36:49 +08:00
buf.Reset()
buf.Write(formatOutput)
return buf, nil
}
// IsTemplateVariable returns true if the text is a template variable.
// The text must start with a dot and be a valid template.
func IsTemplateVariable(text string) bool {
match, _ := regexp.MatchString(`(?m)^{{(\.\w+)+}}$`, text)
return match
}
// TemplateVariable returns the variable name of the template.
func TemplateVariable(text string) string {
if IsTemplateVariable(text) {
return text[3 : len(text)-2]
}
return ""
}