wujian_develop_tool/util/file.go

62 lines
1.2 KiB
Go

package util
import (
"bytes"
"os"
"text/template"
)
func TemplateToFile(desFile string, templateContent string, data interface{}) error {
file, err := os.OpenFile(desFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
if err != nil {
return err
}
defer file.Close()
tpl := template.New("template")
tpl, err = tpl.Parse(templateContent)
if err != nil {
return err
}
b := bytes.Buffer{}
err = tpl.Execute(&b, data)
if err != nil {
return err
}
_, err = file.Write(b.Bytes())
if err != nil {
return err
}
return nil
}
func WriteFile(filePath string, data []byte) error {
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
return err
}
func WriteFileWithNotEdit(filePath string, data []byte) error {
notEdit := "# Code generated by wujian-develop_tool. DO NOT EDIT.\n\n"
return WriteFile(filePath, []byte(notEdit+string(data)))
}
// ExistFile 文件是否存在
func ExistFile(filePath string) bool {
info, err := os.Stat(filePath)
return err == nil && !info.IsDir()
}
// ExistDir 目录是否存在
func ExistDir(dirPath string) bool {
info, err := os.Stat(dirPath)
return err == nil && info.IsDir()
}