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

71 lines
1.2 KiB
Go
Raw Normal View History

package util
import (
"bytes"
goformat "go/format"
"io/ioutil"
"text/template"
)
2020-10-15 16:36:49 +08:00
const regularPerm = 0666
type defaultTemplate struct {
name string
text string
goFmt bool
savePath string
}
func With(name string) *defaultTemplate {
return &defaultTemplate{
name: name,
}
}
func (t *defaultTemplate) Parse(text string) *defaultTemplate {
t.text = text
return t
}
func (t *defaultTemplate) GoFmt(format bool) *defaultTemplate {
t.goFmt = format
return t
}
func (t *defaultTemplate) SaveTo(data interface{}, path string, forceUpdate bool) error {
if 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)
}
2020-10-15 16:36:49 +08:00
func (t *defaultTemplate) Execute(data interface{}) (*bytes.Buffer, error) {
tem, err := template.New(t.name).Parse(t.text)
if err != nil {
return nil, err
}
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, err
}
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 {
return nil, err
}
2020-10-15 16:36:49 +08:00
buf.Reset()
buf.Write(formatOutput)
return buf, nil
}