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

73 lines
1.1 KiB
Go
Raw Normal View History

package util
2020-10-15 16:36:49 +08:00
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
}
2020-10-15 16:36:49 +08:00
func InitTemplates(category string, templates map[string]string) error {
dir, err := GetTemplateDir(category)
2020-10-15 16:36:49 +08:00
if err != nil {
return err
}
if err := MkdirIfNotExist(dir); err != nil {
2020-10-15 16:36:49 +08:00
return err
}
for k, v := range templates {
if err := createTemplate(filepath.Join(dir, k), v); err != nil {
return err
}
}
return nil
}
func LoadTemplate(category, file, builtin string) (string, error) {
dir, err := GetTemplateDir(category)
2020-10-15 16:36:49 +08:00
if err != nil {
return "", err
}
file = filepath.Join(dir, file)
if !FileExists(file) {
2020-10-15 16:36:49 +08:00
return builtin, nil
}
content, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return string(content), nil
}
func createTemplate(file, content string) error {
if FileExists(file) {
2020-10-15 16:36:49 +08:00
println(1)
return nil
}
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(content)
return err
}