You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.1 KiB
Go
73 lines
1.1 KiB
Go
4 years ago
|
package util
|
||
4 years ago
|
|
||
|
import (
|
||
|
"io/ioutil"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
)
|
||
|
|
||
|
const goctlDir = ".goctl"
|
||
|
|
||
4 years ago
|
func GetTemplateDir(category string) (string, error) {
|
||
|
home, err := os.UserHomeDir()
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return filepath.Join(home, goctlDir, category), nil
|
||
|
}
|
||
|
|
||
4 years ago
|
func InitTemplates(category string, templates map[string]string) error {
|
||
4 years ago
|
dir, err := GetTemplateDir(category)
|
||
4 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
4 years ago
|
if err := MkdirIfNotExist(dir); err != nil {
|
||
4 years ago
|
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) {
|
||
4 years ago
|
dir, err := GetTemplateDir(category)
|
||
4 years ago
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
file = filepath.Join(dir, file)
|
||
4 years ago
|
if !FileExists(file) {
|
||
4 years ago
|
return builtin, nil
|
||
|
}
|
||
|
|
||
|
content, err := ioutil.ReadFile(file)
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return string(content), nil
|
||
|
}
|
||
|
|
||
|
func createTemplate(file, content string) error {
|
||
4 years ago
|
if FileExists(file) {
|
||
4 years ago
|
println(1)
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
f, err := os.Create(file)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
_, err = f.WriteString(content)
|
||
|
return err
|
||
|
}
|