-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.go
584 lines (506 loc) · 17 KB
/
util.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package main
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"runtime"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"errors"
"time"
"os/exec"
"github.com/revel/revel"
)
// if os.env DEBUG set, debug is on
func Debugf(format string, a ...interface{}) {
if os.Getenv("DEBUG") != "" {
_, file, line, ok := runtime.Caller(1)
if !ok {
file = "<unknown>"
line = -1
} else {
file = filepath.Base(file)
}
fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
}
}
const (
Gray = uint8(iota + 90)
Red
Green
Yellow
Blue
Magenta
//NRed = uint8(31) // Normal
EndColor = "\033[0m"
INFO = "INFO"
TRAC = "TRAC"
ERRO = "ERRO"
WARN = "WARN"
SUCC = "SUCC"
)
// Use a wrapper to differentiate logged panics from unexpected ones.
type LoggedError struct{ error }
func panicOnError(err error, msg string) {
if revErr, ok := err.(*revel.Error); (ok && revErr != nil) || (!ok && err != nil) {
fmt.Fprintf(os.Stderr, "Abort: %s: %s\n", msg, err)
panic(LoggedError{err})
}
}
func mustCopyFile(destFilename, srcFilename string) {
destFile, err := os.Create(destFilename)
panicOnError(err, "Failed to create file "+destFilename)
srcFile, err := os.Open(srcFilename)
panicOnError(err, "Failed to open file "+srcFilename)
_, err = io.Copy(destFile, srcFile)
panicOnError(err,
fmt.Sprintf("Failed to copy data from %s to %s", srcFile.Name(), destFile.Name()))
err = destFile.Close()
panicOnError(err, "Failed to close file "+destFile.Name())
err = srcFile.Close()
panicOnError(err, "Failed to close file "+srcFile.Name())
}
func mustRenderTemplate(destPath, srcPath string, data map[string]interface{}) {
tmpl, err := template.ParseFiles(srcPath)
panicOnError(err, "Failed to parse template "+srcPath)
f, err := os.Create(destPath)
panicOnError(err, "Failed to create "+destPath)
err = tmpl.Execute(f, data)
panicOnError(err, "Failed to render template "+srcPath)
err = f.Close()
panicOnError(err, "Failed to close "+f.Name())
}
func mustChmod(filename string, mode os.FileMode) {
err := os.Chmod(filename, mode)
panicOnError(err, fmt.Sprintf("Failed to chmod %d %q", mode, filename))
}
// copyDir copies a directory tree over to a new directory. Any files ending in
// ".template" are treated as a Go template and rendered using the given data.
// Additionally, the trailing ".template" is stripped from the file name.
// Also, dot files and dot directories are skipped.
func mustCopyDir(destDir, srcDir string, data map[string]interface{}) error {
var fullSrcDir string
// Handle symlinked directories.
f, err := os.Lstat(srcDir)
if err == nil && f.Mode()&os.ModeSymlink == os.ModeSymlink {
fullSrcDir, err = os.Readlink(srcDir)
if err != nil {
panic(err)
}
} else {
fullSrcDir = srcDir
}
return filepath.Walk(fullSrcDir, func(srcPath string, info os.FileInfo, err error) error {
// Get the relative path from the source base, and the corresponding path in
// the dest directory.
relSrcPath := strings.TrimLeft(srcPath[len(fullSrcDir):], string(os.PathSeparator))
destPath := path.Join(destDir, relSrcPath)
// Skip dot files and dot directories.
if strings.HasPrefix(relSrcPath, ".") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
// Create a subdirectory if necessary.
if info.IsDir() {
err := os.MkdirAll(path.Join(destDir, relSrcPath), 0777)
if !os.IsExist(err) {
panicOnError(err, "Failed to create directory")
}
return nil
}
// If this file ends in ".template", render it as a template.
if strings.HasSuffix(relSrcPath, ".template") {
mustRenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data)
return nil
}
// Else, just copy it over.
mustCopyFile(destPath, srcPath)
return nil
})
}
func mustTarGzDir(destFilename, srcDir string) string {
zipFile, err := os.Create(destFilename)
panicOnError(err, "Failed to create archive")
defer zipFile.Close()
gzipWriter := gzip.NewWriter(zipFile)
defer gzipWriter.Close()
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close()
filepath.Walk(srcDir, func(srcPath string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
srcFile, err := os.Open(srcPath)
panicOnError(err, "Failed to read source file")
defer srcFile.Close()
err = tarWriter.WriteHeader(&tar.Header{
Name: strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)),
Size: info.Size(),
Mode: int64(info.Mode()),
ModTime: info.ModTime(),
})
panicOnError(err, "Failed to write tar entry header")
_, err = io.Copy(tarWriter, srcFile)
panicOnError(err, "Failed to copy")
return nil
})
return zipFile.Name()
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return true, err
}
// empty returns true if the given directory is empty.
// the directory must exist.
func empty(dirname string) bool {
dir, err := os.Open(dirname)
if err != nil {
ColorLog("[ERRO]error opening directory: %s", err)
}
defer dir.Close()
results, _ := dir.Readdir(1)
return len(results) == 0
}
func GetRestControllerStruct(p ,controllerName string) (string, error){
controllerStr := "type " +camelString(p) + "_"+ controllerName + " struct{\n"
controllerStr += " *revel.Controller\n"
controllerStr += "}\n"
return controllerStr, nil
}
func GetControllerStruct(controllerName string) (string, error){
controllerStr := "type " + controllerName + " struct{\n"
controllerStr += " *revel.Controller\n"
controllerStr += "}\n"
return controllerStr, nil
}
func GetStruct(structname, fields string) (string, bool, error) {
var hastime = false
if fields == "" {
return "", hastime, errors.New("fields can't empty")
}
structStr := "type " + structname + " struct{\n"
structStr += "gorm.Model\n"
fds := strings.Split(fields, ",")
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", hastime, errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ, timePackage := getAttrType(kv[1])
if timePackage {
hastime = true
}
if typ == "" {
return "", hastime, errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr = structStr + camelString(kv[0]) + " " + typ + " " + "`json:\"" + strings.ToLower(kv[0]) + "\" gorm:\"column:" + kv[0]+ "\"`\n"
}
structStr += "}\n"
return structStr, hastime, nil
}
func GetFormAttributes(structname, fields string) (string, error){
if fields == "" {
return "", errors.New("fields can't empty")
}
fds := strings.Split(fields, ",")
structStr := ""
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr += "<div class=\"form-group\">\n"
structStr += "{{with $field := field \""+ strings.ToLower(structname) + "." + camelString(kv[0]) + "\" .}}\n"
structStr += GetInputType(kv[1],kv[0]) +"\n"
structStr += "{{end}}\n</div>\n"
}
return structStr, nil
}
func GetUpdateFormAttributes(structname, fields string) (string, error){
if fields == "" {
return "", errors.New("fields can't empty")
}
fds := strings.Split(fields, ",")
structStr := ""
structStr += "{{with $field := field \"post.ID\" .}}\n"
structStr += "<input type=\"hidden\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\">\n"
structStr += "{{end}}\n"
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr += "<div class=\"form-group\">\n"
structStr += "{{with $field := field \""+ strings.ToLower(structname) + "." + camelString(kv[0]) + "\" .}}\n"
structStr += GetInputType(kv[1],kv[0]) +"\n"
structStr += "{{end}}\n</div>\n"
}
return structStr, nil
}
func GetInputType(attrType string,s string) string{
kv := strings.SplitN(attrType, ":", 2)
switch kv[0] {
case "string":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n"+ "<input type=\"text\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\" class=\"{{$field.ErrorClass}}\">\n" + "<span class=\"error\">{{$field.Error}}</span>\n"
case "datetime":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n" + "<input type=\"text\" size=\"10\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\" class=\"{{$field.ErrorClass}}\">\n" + "<span class=\"error\">{{$field.Error}}</span>\n"
case "int", "int8", "int16", "int32", "int64":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n" + "<input type=\"number\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\" class=\"{{$field.ErrorClass}}\">\n" + "<span class=\"error\">{{$field.Error}}</span>\n"
case "uint", "uint8", "uint16", "uint32", "uint64":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n" + "<input type=\"number\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\" class=\"datepicker {{$field.ErrorClass}}\">\n" + "<span class=\"error\">{{$field.Error}}</span>\n"
case "float","float32", "float64":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n" + "<input type=\"number\" id=\"{{$field.Id}}\" name=\"{{$field.Name}}\" value=\"{{$field.Value}}\" class=\"{{$field.ErrorClass}}\">\n" + "<span class=\"error\">{{$field.Error}}</span>\n"
case "bool":
return "<label for=\"{{$field.Id}}\">" + camelString(s) +" * </label>\n" + "{{checkbox $field \"true\"}}" + "<span class=\"error\">{{$field.Error}}</span>\n"
}
return ""
}
func GetTableHeaders(structname, fields string) (string, error) {
if fields == "" {
return "", errors.New("fields can't empty")
}
fds := strings.Split(fields, ",")
structStr := "<th>#</th>\n"
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr += "<th> " + camelString(kv[0]) + "</th>\n"
}
structStr += "<th colspan=\"3\"></th>\n<th></th>\n<th></th>"
return structStr, nil
}
func GetIndexTableBody(structname, fields string) (string, error) {
if fields == "" {
return "", errors.New("fields can't empty")
}
fds := strings.Split(fields, ",")
structStr := "{{range ." + strings.ToLower(structname) + "s}}\n<tr>\n<td>#</td>\n"
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr += "<td> {{." + camelString(kv[0]) + "}} </td>\n"
}
structStr += "<td><a href=\"{{url \"" + camelString(structname) + ".Show\" .ID}}\"> Show </a></td>\n"
structStr += "<td><a href=\"{{url \"" + camelString(structname) + ".Edit\" .ID}}\"> Edit </a></td>\n"
structStr += "<td>\n" + "<form method=\"POST\" action=\"{{ url \"" + camelString(structname) + ".Delete\" .ID}}\">\n" + "<input type=\"submit\" class=\"btn btn-danger\" value=\"Delete\"></input>\n" +"</form>\n" +"</td>\n<tr>\n{{end}}\n"
return structStr, nil
}
func GetShowTableBody(structname, fields string) (string, error) {
if fields == "" {
return "", errors.New("fields can't empty")
}
fds := strings.Split(fields, ",")
structStr := "{{with ." + strings.ToLower(structname) + "}}\n"
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type,key:type " + v)
}
structStr += "<tr><td> <label>" + camelString(kv[0]) + ": </lable></td><td> {{." + camelString(kv[0]) + "}} </td></tr>\n"
}
structStr += "{{end}}"
return structStr, nil
}
func GetAttrs(fields string) (string, error) {
if fields == "" {
return "", errors.New("fields can't empty")
}
//bson.M{"location": outlet.Location}
structStr := "bson.M{\n"
fds := strings.Split(fields, ",")
for _, v := range fds {
kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 {
return "", errors.New("the filds format is wrong. should key:type;key:type " + v)
}
typ := getType(kv[1])
if typ == "" {
return "", errors.New("the filds format is wrong. should key:type;key:type " + v)
}
structStr = structStr + "\"" + kv[0] + "\": " + "m." + camelString(kv[0]) + ","
}
structStr += "\"updatedAt\": " + "time.Now(),"
structStr += "},\n"
return structStr, nil
}
func camelString(s string) string {
data := make([]byte, 0, len(s))
j := false
k := false
num := len(s) - 1
for i := 0; i <= num; i++ {
d := s[i]
if k == false && d >= 'A' && d <= 'Z' {
k = true
}
if d >= 'a' && d <= 'z' && (j || k == false) {
d = d - 32
j = false
k = true
}
if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
j = true
continue
}
data = append(data, d)
}
return string(data[:len(data)])
}
// fields support type
func getType(ktype string) string {
kv := strings.SplitN(ktype, ":", 2)
switch kv[0] {
case "string":
if len(kv) == 2 {
return "string"
} else {
return "string"
}
case "datetime":
return "time.Time"
case "int", "int8", "int16", "int32", "int64":
fallthrough
case "uint", "uint8", "uint16", "uint32", "uint64":
fallthrough
case "bool":
fallthrough
case "float32", "float64":
return kv[0]
case "float":
return "float64"
}
return ""
}
// fields support type
func getAttrType(ktype string) (string, bool){
kv := strings.SplitN(ktype, ":", 2)
switch kv[0] {
case "string":
return "string", false
case "datetime":
return "time.Time", true
case "int", "int8", "int16", "int32", "int64":
fallthrough
case "uint", "uint8", "uint16", "uint32", "uint64":
fallthrough
case "bool":
fallthrough
case "float32", "float64":
return kv[0], false
case "float":
return "float64", false
}
return "", false
}
// ColorLog colors log and print to stdout.
// See color rules in function 'ColorLogS'.
func ColorLog(format string, a ...interface{}) {
fmt.Print(ColorLogS(format, a...))
}
// ColorLogS colors log and return colored content.
// Log format: <level> <content [highlight][path]> [ error ].
// Level: TRAC -> blue; ERRO -> red; WARN -> Magenta; SUCC -> green; others -> default.
// Content: default; path: yellow; error -> red.
// Level has to be surrounded by "[" and "]".
// Highlights have to be surrounded by "# " and " #"(space), "#" will be deleted.
// Paths have to be surrounded by "( " and " )"(space).
// Errors have to be surrounded by "[ " and " ]"(space).
// Note: it hasn't support windows yet, contribute is welcome.
func ColorLogS(format string, a ...interface{}) string {
log := fmt.Sprintf(format, a...)
var clog string
if runtime.GOOS != "windows" {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + getColorLevel(log[1:i]) + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", fmt.Sprintf("[\033[%dm", Red), -1)
log = strings.Replace(log, " ]", EndColor+"]", -1)
// Path.
log = strings.Replace(log, "( ", fmt.Sprintf("(\033[%dm", Yellow), -1)
log = strings.Replace(log, " )", EndColor+")", -1)
// Highlights.
log = strings.Replace(log, "# ", fmt.Sprintf("\033[%dm", Gray), -1)
log = strings.Replace(log, " #", EndColor, -1)
log = clog + log
} else {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + log[1:i] + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", "[", -1)
log = strings.Replace(log, " ]", "]", -1)
// Path.
log = strings.Replace(log, "( ", "(", -1)
log = strings.Replace(log, " )", ")", -1)
// Highlights.
log = strings.Replace(log, "# ", "", -1)
log = strings.Replace(log, " #", "", -1)
log = clog + log
}
return time.Now().Format("2006/01/02 15:04:05 ") + log
}
// getColorLevel returns colored level string by given level.
func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case INFO:
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case TRAC:
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case ERRO:
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case WARN:
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case SUCC:
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
return level
}
// formatSourceCode formats source files
func FormatSourceCode(filename string) {
cmd := exec.Command("gofmt", "-w", filename)
if err := cmd.Run(); err != nil {
ColorLog("[WARN] gofmt err: %s\n", err)
}
}