-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
141 lines (105 loc) · 2.43 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"bytes"
"html/template"
)
var (
tplBaseDir = "templates/"
fileTpl = "file.tpl"
funcsTplMap = map[string][]string{
typePersist: {},
typeExpire: {},
typeHash: {},
}
)
type FileGenerator struct {
sheetConfigs []*SheetConfig
sheetData *SheetTplData
funcGen *FuncGenerator
}
type SheetTplData struct {
SheetConfigs map[string][]SheetConfig
Sheets map[string]string
LoadFuncs []*LoadFunc
}
type LoadFunc struct {
SheetName string
FuncName string
FuncBody string
}
func NewGenerator(root string, sheetConfigs []*SheetConfig) *FileGenerator {
if len(root) != 0 {
tplBaseDir = root + tplBaseDir
}
return &FileGenerator{
sheetConfigs: sheetConfigs,
sheetData: &SheetTplData{},
}
}
func (g *FileGenerator) Dump() (buff []byte, err error) {
err = g.fileConfigs()
if err != nil {
return
}
err = g.loadFuncs()
if err != nil {
return
}
tmpl := template.Must(template.New("file").Funcs(template.FuncMap{
"unescaped": g.unescaped,
}).ParseFiles(tplBaseDir + fileTpl))
b := bytes.NewBufferString("")
err = tmpl.Execute(b, g.sheetData)
if err != nil {
return
}
buff = b.Bytes()
return
}
func (g *FileGenerator) fileConfigs() (err error) {
sheetConfigs := make(map[string][]SheetConfig)
for _, config := range g.sheetConfigs {
if sheetConfigs[config.VarType] == nil {
sheetConfigs[config.VarType] = make([]SheetConfig, 0, 50)
}
v := *config
sheetConfigs[config.VarType] = append(sheetConfigs[config.VarType], v)
}
g.sheetData.SheetConfigs = sheetConfigs
return
}
func (g *FileGenerator) loadFuncs() (err error) {
funcs := make([]*LoadFunc, 0, len(g.sheetConfigs))
g.sheetData.LoadFuncs = funcs
return
}
func (g *FileGenerator) unescaped(x string) interface{} {
return template.HTML(x)
}
type FuncGenerator struct {
tmpl map[string]*template.Template
}
func (fg *FuncGenerator) Init(tplDir string) (err error) {
tmpl := make(map[string]*template.Template)
for typ, tplsName := range funcsTplMap {
tplsFile := make([]string, 0, 3)
for _, tn := range tplsName {
tplsFile = append(tplsFile, tplDir+tn)
}
tmpl[typ] = template.Must(template.ParseFiles(tplsFile...))
}
fg.tmpl = tmpl
return
}
func (fg *FuncGenerator) Dump(config *SheetConfig) (funcStr string, err error) {
t, ok := fg.tmpl[config.VarType]
if ok {
buff := bytes.NewBufferString("")
err = t.Execute(buff, config)
if err != nil {
return
}
funcStr = buff.String()
}
return
}