-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
283 lines (246 loc) · 6.51 KB
/
main.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"bufio"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"os"
"strings"
)
// Each template defines generic code block
var builder = []string{pkgTemplate, BuildTemplate, BuildVarTemplate, ValidateTemplate, BuildFuncTemplate}
var predicate = []string{pkgTemplate, PredicateTemplate, PredicateVarTemplate}
var utils = []string{pkgTemplate, SetVarTemplate, GetVarTemplate}
// if template is using structure's variable then add it here also
var vartemplate = map[string]string{
BuildVarTemplate: "",
PredicateVarTemplate: "",
SetVarTemplate: "",
GetVarTemplate: "",
}
const (
Builder = iota
Predicate
Utils
All
)
type generator struct {
file *string
genType int
dir *string
headerFile *string
}
func newGenerator(file, dir, headerFile *string, gentype int) *generator {
return &generator{
file: file,
genType: gentype,
dir: dir,
headerFile: headerFile,
}
}
func (g *generator) newParser() *ast.File {
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, *g.file, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
return nil
}
return f
}
func (g *generator) copyHeaderText(df *os.File) {
sf, err := os.Open(*g.headerFile)
if err != nil {
log.Fatalf("Failed to open header file : %v", err)
}
if _, err := io.Copy(df, sf); err != nil {
log.Fatalf("Failed to copy header file : %v", err)
}
sf.Close()
}
func (g *generator) generatePackage(template []string, file string) {
fs := g.newParser()
if fs == nil {
log.Fatalf("Error occurred creating a new parser")
}
f, err := os.Create(*g.dir + "/" + file)
if err != nil {
log.Fatalf("Failed to create new file : %v", err)
}
g.copyHeaderText(f)
for _, t := range template {
if err := parseTemplate(t, fs, bufio.NewWriter(f)); err != nil {
log.Fatalf("Failed to parse template : %v", err)
}
}
err = f.Close()
if err != nil {
log.Fatalf("Failed to close a file : %v", err)
}
return
}
func (g *generator) generateBuilder() {
g.generatePackage(builder, "builder.go")
}
func (g *generator) generatePredicate() {
g.generatePackage(predicate, "predicate.go")
}
func (g *generator) generateUtils() {
g.generatePackage(utils, "utils.go")
}
func (g *generator) Execute() {
switch g.genType {
case Builder:
g.generateBuilder()
case Predicate:
g.generatePredicate()
case Utils:
g.generateUtils()
case All:
for i := Builder; i < All; i++ {
g.genType = i
g.Execute()
}
}
}
func main() {
dir, _ := os.Getwd()
filename := flag.String("file", "", "file name")
outputpath := flag.String("dir", dir, "output directory name")
bfile := flag.String("boilerplate", "", "boilerplate file path")
flag.Parse()
if len(*filename) == 0 || len(*bfile) == 0 {
log.Fatalf("File name is missing")
}
generator := newGenerator(filename, outputpath, bfile, All)
generator.Execute()
return
}
func parseTemplate(template string, fs *ast.File, w *bufio.Writer) error {
var objname string
var pkgname string
shouldParseVar := false
predicateGenertor := false
if _, ok := vartemplate[template]; ok {
shouldParseVar = true
}
if template == PredicateVarTemplate {
predicateGenertor = true
}
// fs is a parsed, type-checked *ast.File.
ast.Inspect(fs, func(n ast.Node) bool {
switch b := n.(type) {
case *ast.GenDecl:
if b.Tok != token.TYPE {
break
}
objname = b.Specs[0].(*ast.TypeSpec).Name.Name
case *ast.File:
pkgname = b.Name.Name
}
return true
})
if template == pkgTemplate {
template = strings.Replace(template, "$package", pkgname, -1)
goto exit
}
// copy strcture if it is builder template
if template == BuildTemplate {
copyStructFile(fs, w)
}
template = strings.Replace(template, "$NewObj", objname, -1)
template = strings.Replace(template, "$newobj", objname, -1)
template = strings.Replace(template, "$obj", string(strings.ToLower(objname)[0]), -1)
template = strings.Replace(template, "$Struct", objname, -1)
// fs is a parsed, type-checked *ast.File.
ast.Inspect(fs, func(n ast.Node) bool {
if expr, ok := n.(*ast.StructType); ok && shouldParseVar {
for _, field := range expr.Fields.List {
template := strings.Replace(template, "$Var", field.Names[0].Name, -1)
template = strings.Replace(template, "$var", field.Names[0].Name, -1)
ntype := fmt.Sprintf("%s", field.Type)
template = strings.Replace(template, "$iType", ntype, -1)
if predicateGenertor {
fcond := ""
switch ntype {
case "string":
fcond = "len(%s.%s) == 0"
case "bool":
fcond = "%s.%s == true"
case "int":
fcond = "%s.%s == 0"
}
cond := fmt.Sprintf(fcond, string(strings.ToLower(objname)[0]), field.Names[0].Name)
template = strings.Replace(template, "$cond", cond, -1)
}
_, err := w.WriteString(template)
if err != nil {
log.Fatalf("Failed to write modified template : %v", err)
}
}
}
return true
})
exit:
if !shouldParseVar {
_, err := w.WriteString(template)
if err != nil {
log.Fatalf("Failed to write modified template : %v", err)
}
}
if err := w.Flush(); err != nil {
log.Fatalf("Failed to flush data to file : %v", err)
}
return nil
}
func copyStructFile(fs *ast.File, w *bufio.Writer) {
// import error package
_, err := fmt.Fprintf(w, "\nimport \"github.com/pkg/errors\"\n")
if err != nil {
log.Fatalf("Failed to write struct : %v", err)
}
// fs is a parsed, type-checked *ast.File.
ast.Inspect(fs, func(n ast.Node) bool {
switch b := n.(type) {
case *ast.GenDecl:
if b.Tok != token.TYPE {
break
}
_, err := fmt.Fprintf(w, "\ntype %s struct {\n", b.Specs[0].(*ast.TypeSpec).Name.Name)
if err != nil {
log.Fatalf("Failed to write struct : %v", err)
}
}
return true
})
// fs is a parsed, type-checked *ast.File.
ast.Inspect(fs, func(n ast.Node) bool {
if expr, ok := n.(*ast.StructType); ok {
for _, field := range expr.Fields.List {
_, err := fmt.Fprintf(w, "\t%s\n", field.Comment.List[0].Text)
if err != nil {
log.Fatalf("Failed to write struct : %v", err)
}
_, err = fmt.Fprintf(w, "\t%s %s\n", field.Names[0].Name, field.Type)
if err != nil {
log.Fatalf("Failed to write struct : %v", err)
}
}
}
return true
})
// Add predicatelist variable
if _, err := w.WriteString(BuilderFieldTemplate); err != nil {
log.Fatalf("Failed to add predicate and error filed : %v", err)
}
_, err = fmt.Fprintf(w, "}\n")
if err != nil {
log.Fatalf("Failed to write struct : %v", err)
}
if err := w.Flush(); err != nil {
log.Fatalf("Failed to flush data to file : %v", err)
}
}