-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcg.go
356 lines (328 loc) · 8.87 KB
/
gcg.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"bytes"
"encoding/json"
"fmt"
"go/format"
"gopkg.in/ffmt.v1"
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"text/template"
)
const (
version = "0.0.8"
helpText = "Using `gcg <json file>` to generate go file\nSuch as `gcg data.json`\n\nUsing `gcg -g <json file>` to generate a json file"
)
// CGO_ENABLED: 0
// GOOS: darwin、freebsd、linux、windows
// GOARCH: 386、amd64、arm
//
//go:generate bash -c "CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o bin/gcg gcg.go"
//go:generate bash -c "CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o bin/gcg.exe gcg.go"
//go:generate bash -c "CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -o bin/gcg_x86.exe gcg.go"
type config struct {
Variable map[string]interface{} `json:"variable"`
Files []goFile `json:"files"`
Root string
}
type goFile struct {
PackageName string `json:"package"`
ImportedPackage []interface{} `json:"import"`
Body []bodyArea `json:"body"`
Output string `json:"output"`
}
type bodyArea struct {
Template interface{} `json:"template"`
Args interface{} `json:"args"`
}
type jsonMap = map[string]interface{}
var funcMap = template.FuncMap{
"upperFirstChar": func(text string) string {
return fmt.Sprintf("%s%s", strings.ToUpper(text[0:1]), text[1:len(text)])
},
"upper": func(text string) string {
return strings.ToUpper(text)
},
"lower": func(text string) string {
return strings.ToLower(text)
},
"makeSlice": func(args ...interface{}) (slice []interface{}) {
for _, arg := range args {
slice = append(slice, arg)
}
return
},
"makeMap": func(args ...interface{}) (m map[interface{}]interface{}) {
m = make(map[interface{}]interface{})
for i := 0; i < len(args)/2; i++ {
m[args[i*2]] = args[i*2+1]
}
return
},
"isInt": func(i interface{}) bool {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint32, reflect.Uint64:
return true
default:
return false
}
},
"isString": func(i interface{}) bool {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.String:
return true
default:
return false
}
},
"isSlice": func(i interface{}) bool {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Slice:
return true
default:
return false
}
},
"isArray": func(i interface{}) bool {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Array:
return true
default:
return false
}
},
"isMap": func(i interface{}) bool {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Map:
return true
default:
return false
}
},
"isList": func(i interface{}) bool {
v := reflect.ValueOf(i).Kind()
return v == reflect.Array || v == reflect.Slice
},
"isNumber": func(i interface{}) bool {
v := reflect.ValueOf(i).Kind()
switch v {
case reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
return true
default:
return false
}
},
"isFloat": func(i interface{}) bool {
v := reflect.ValueOf(i).Kind()
return v == reflect.Float32 || v == reflect.Float64
},
}
// exitWhenError exit the program when error is not null
func exitWhenError(err error) {
if err != nil {
fmt.Printf("Can not solve json data: %v", err)
os.Exit(0)
}
}
// exitWhenFalse exit the program when value is false
func exitWhenFalse(b bool, errMsg ...interface{}) {
if !b {
fmt.Println(errMsg...)
os.Exit(0)
}
}
// readData read arguments from json
func readData(filename string) (cfg config) {
var err error
rawText, err := ioutil.ReadFile(filename)
exitWhenError(err)
err = json.Unmarshal(rawText, &cfg)
exitWhenError(err)
filenameSlice := strings.Split(filename, "/")
cfg.Root = strings.Join(filenameSlice[0:len(filenameSlice)-1], "/")
for fileIndex, file := range cfg.Files {
for bodyIndex, body := range file.Body {
cfg.Files[fileIndex].Body[bodyIndex].Args = modifyVariable(body.Args, cfg.Variable)
}
}
return
}
func modifyVariable(args interface{}, variable map[string]interface{}) interface{} {
switch reflect.TypeOf(args).Kind() {
case reflect.String:
s, ok := variable[args.(string)]
if ok {
return s
}
return args
case reflect.Slice:
s := make([]interface{}, 0)
for _, arg := range args.([]interface{}) {
s = append(s, modifyVariable(arg, variable))
}
return s
case reflect.Map:
m := make(map[string]interface{})
iter := reflect.ValueOf(args).MapRange()
for iter.Next() {
m[iter.Key().String()] = modifyVariable(iter.Value().Interface(), variable)
}
return m
default:
return args
}
}
// importPackage from a string or []string to generator import part
func importPackage(x interface{}) (s string) {
switch x.(type) {
case string:
str, _ := x.(string)
s = fmt.Sprintf("\"%s\"", str)
case []interface{}:
slice, _ := x.([]interface{})
switch len(slice) {
case 0:
s = ""
case 1:
s = fmt.Sprintf("\"%s\"", slice[0])
case 2:
s = fmt.Sprintf("%s \"%s\"", slice[0], slice[1])
default:
s = fmt.Sprintf("%s \"%s\" // %s", slice[0], slice[1], slice[2])
}
default:
exitWhenError(fmt.Errorf("Type of %v is %T, expected string or []interface{}", x, x))
}
return
}
// getFilename from a path (go template name can not be a path)
func getFileName(path string) (filename string) {
pathList := strings.Split(path, "/")
filename = pathList[len(pathList)-1]
return
}
// renderTemplate render the block template
func renderTemplate(buf io.Writer, templates []string, args interface{}, variable map[string]interface{}) {
templateName := getFileName(templates[0])
tpl, err := template.New(templateName).Funcs(funcMap).ParseFiles(templates...)
exitWhenError(err)
if reflect.TypeOf(args).Kind() == reflect.Slice {
argsSlice, _ := args.([]interface{})
for _, arg := range argsSlice {
// tpl.Execute(buf, arg)
err = tpl.ExecuteTemplate(buf, templateName, arg)
exitWhenError(err)
}
} else {
err = tpl.ExecuteTemplate(buf, templateName, args)
exitWhenError(err)
}
}
// renderContent render generated file content
func renderContent(cfg config, gf goFile) {
buf := bytes.NewBufferString(fmt.Sprintf("// Code generated by GCG. DO NOT EDIT.\n// Go Code Generator %v (https://github.com/OhYee/gcg)\n\n", version))
buf.WriteString(fmt.Sprintf("package %s\n\n", gf.PackageName))
buf.WriteString(fmt.Sprintf("import (\n%s\n)\n\n",
func(slice []interface{}) string {
s := ""
for idx, pkg := range slice {
s += fmt.Sprintf("%s\t%s", func(idx int) string {
if idx > 0 {
return "\n"
}
return ""
}(idx), importPackage(pkg))
}
return s
}(gf.ImportedPackage),
))
for _, block := range gf.Body {
var templates []string
switch block.Template.(type) {
case string:
temp, _ := block.Template.(string)
templates = []string{temp}
case []interface{}:
var isString bool
temp, _ := block.Template.([]interface{})
templates = make([]string, len(temp))
for idx, item := range temp {
templates[idx], isString = item.(string)
exitWhenFalse(isString, "template must be string or []string")
}
default:
exitWhenFalse(false, "template must be string or []string")
}
for idx := range templates {
templates[idx] = fmt.Sprintf("%s/%s", cfg.Root, templates[idx])
}
renderTemplate(buf, templates, block.Args, cfg.Variable)
}
// code format
b, err := format.Source(buf.Bytes())
if err != nil {
fmt.Printf("%s: goformat error\n%s\n", gf.Output, err)
b = buf.Bytes()
}
outputFile, err := os.Create(fmt.Sprintf("%s/%s", cfg.Root, gf.Output))
exitWhenError(err)
outputFile.Write(b)
outputFile.Close()
return
}
func generateFile(filename string) error {
content := `{
"variable": {},
"files": [
{
"package": "write your package name here",
"output": "pkg.go",
"import": [],
"body": [
{
"template": "template.tpl",
"args": []
}
]
}
]
}`
return ioutil.WriteFile(filename, []byte(content), 0777)
}
func main() {
var inputFile string
switch len(os.Args) {
case 1:
exitWhenFalse(false, helpText)
default:
if os.Args[1] == "-h" || os.Args[1] == "--help" {
exitWhenFalse(false, helpText)
} else if os.Args[1] == "-v" || os.Args[1] == "--version" {
exitWhenFalse(false, fmt.Sprintf("Go Code Generator version: %s\n", version))
} else if os.Args[1] == "-d" || os.Args[1] == "--debug" {
ffmt.P(readData(os.Args[2]))
exitWhenFalse(false, "\n")
} else if os.Args[1] == "-g" || os.Args[1] == "--generate" {
filename := "./data.json"
if len(os.Args) >= 3 {
filename = os.Args[2]
}
err := generateFile(filename)
exitWhenError(err)
exitWhenFalse(false, fmt.Sprintf("Generated json file %s", filename))
}
inputFile = os.Args[1]
}
cfg := readData(inputFile)
for _, gf := range cfg.Files {
renderContent(cfg, gf)
}
}