生成代码,逐步进行优化

This commit is contained in:
2021-06-04 10:04:37 +08:00
parent d6c11a5d93
commit a003612810
5 changed files with 117 additions and 9 deletions
+36 -5
View File
@@ -6,10 +6,12 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
type MakeCode struct {
@@ -56,6 +58,8 @@ func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) {
}
myInit := strings.Replace(InitTpt, "{{name}}", name, -1)
ctrList := ""
if db.Type == "sqlite" {
tables := db.Select("sqlite_sequence", "name")
@@ -104,7 +108,23 @@ func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) {
}
//创建模块文件
//判断文件是否存在
_, err := os.OpenFile(name+"/"+v.GetString("name"), os.O_RDONLY, os.ModePerm)
if err != nil { //文件不存在,则根据模板创建
myCtr := strings.Replace(CtrTpt, "{{name}}", name, -1)
myCtr = strings.Replace(myCtr, "{{table}}", v.GetString("name"), -1)
_ = os.MkdirAll(name, os.ModeDir)
err = ioutil.WriteFile(name+"/"+v.GetString("name")+".go", []byte(myCtr), os.ModeAppend)
if err != nil {
that.Error.SetError(err)
}
}
ctrList = ctrList + `"` + v.GetString("name") + `":` + v.GetString("name") + `Ctr,`
}
newTables := []Map{}
for k, _ := range that.TableConfig {
newTable := that.TableConfig.GetMap(k)
@@ -116,21 +136,32 @@ func (that *MakeCode) Db2JSON(name string, path string, db db.HoTimeDB) {
newTable["columns"] = columns
}
that.Config["tables"] = newTables
}
id := Md5(ObjToStr(that.Config["tables"]))
if id == that.Config.GetString("id") {
return
}
that.Config["id"] = id
//init文件初始化
myInit = strings.Replace(myInit, "{{id}}", id, -1)
myInit = strings.Replace(myInit, "{{tablesCtr}}", ctrList, -1)
_ = os.MkdirAll(name, os.ModeDir)
err = ioutil.WriteFile(name+"/init.go", []byte(myInit), os.ModeAppend)
if err != nil {
that.Error.SetError(err)
}
//写入配置文件
var configByte bytes.Buffer
err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t")
//判断配置文件是否序列有变化,有则修改配置,无则不变
//fmt.Println(len(btes))
if len(btes) != 0 && configByte.String() == string(btes) {
return
}
_ = os.MkdirAll(filepath.Dir(path), os.ModeDir)
err = ioutil.WriteFile(path, configByte.Bytes(), os.ModeAppend)
if err != nil {
that.Error.SetError(err)
}
fmt.Println("有新的代码生成,请重新运行")
os.Exit(-1)
}
func (that *MakeCode) Info(table string) string {
reStr := ""