go-zero/tools/goctl/util/files.go
Keson 41964f9d52
gozero template (#147)
* model/rpc generate code from template cache

* delete unused(deprecated) code

* support template init|update|clean|revert

* model: return the execute result for insert and update operation

* // deprecated: containsAny

* add template test

* add default buildVersion

* update build version
2020-10-21 14:59:35 +08:00

88 lines
1.5 KiB
Go

package util
import (
"io/ioutil"
"os"
"path/filepath"
)
const goctlDir = ".goctl"
func GetTemplateDir(category string) (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, goctlDir, category), nil
}
func InitTemplates(category string, templates map[string]string) error {
dir, err := GetTemplateDir(category)
if err != nil {
return err
}
if err := MkdirIfNotExist(dir); err != nil {
return err
}
for k, v := range templates {
if err := createTemplate(filepath.Join(dir, k), v, false); err != nil {
return err
}
}
return nil
}
func CreateTemplate(category, name, content string) error {
dir, err := GetTemplateDir(category)
if err != nil {
return err
}
return createTemplate(filepath.Join(dir, name), content, true)
}
func Clean(category string) error {
dir, err := GetTemplateDir(category)
if err != nil {
return err
}
return os.RemoveAll(dir)
}
func LoadTemplate(category, file, builtin string) (string, error) {
dir, err := GetTemplateDir(category)
if err != nil {
return "", err
}
file = filepath.Join(dir, file)
if !FileExists(file) {
return builtin, nil
}
content, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return string(content), nil
}
func createTemplate(file, content string, force bool) error {
if FileExists(file) && !force {
return nil
}
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(content)
return err
}