/
template.go
144 lines (135 loc) · 2.51 KB
/
template.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
package gen
import (
"fmt"
"go/ast"
"go/token"
"strings"
)
type StructField struct {
Name string
Type string
Tag string
Comment string
}
type StructCreator struct {
PackageName string
TableName string
Pk string
Fields []StructField
HasTime bool
}
func exportName(s string) string {
if strings.Index(s, "_") > 0 {
arr := strings.Split(s, "_")
for i, item := range arr {
if len(item) > 0 {
arr[i] = strings.ToUpper(item[0:1]) + item[1:]
}
}
return strings.Join(arr, "")
}
return strings.ToUpper(s[0:1]) + s[1:]
}
func (c *StructCreator) StructName() string {
if len(c.TableName) == 1 {
return strings.ToUpper(c.TableName)
}
return exportName(c.TableName)
}
func (c *StructCreator) Create() *ast.GenDecl {
fields := make([]*ast.Field, 0, len(c.Fields))
for _, field := range c.Fields {
fields = append(fields, &ast.Field{
Names: []*ast.Ident{
&ast.Ident{
Name: field.Name,
},
},
Type: &ast.Ident{
Name: field.Type,
},
Tag: &ast.BasicLit{
Kind: token.STRING,
Value: field.Tag, // "`json:\"id\"`",
},
Comment: &ast.CommentGroup{
List: []*ast.Comment{
&ast.Comment{
Text: field.Comment,
},
},
},
})
}
ret := &ast.GenDecl{
Tok: token.TYPE,
Specs: []ast.Spec{
&ast.TypeSpec{
Name: &ast.Ident{
Name: c.StructName(),
},
Type: &ast.StructType{
Fields: &ast.FieldList{
List: fields,
},
},
},
},
}
return ret
}
func (c *StructCreator) makeFunc(funcName, ret string) *ast.FuncDecl {
return &ast.FuncDecl{
Recv: &ast.FieldList{
List: []*ast.Field{
&ast.Field{
Names: []*ast.Ident{
&ast.Ident{
Name: strings.ToLower(c.TableName[0:1]),
},
},
Type: &ast.StarExpr{
X: &ast.Ident{
Name: c.StructName(),
},
},
},
},
},
Name: &ast.Ident{
Name: funcName,
},
Type: &ast.FuncType{
Params: &ast.FieldList{
List: []*ast.Field{},
},
Results: &ast.FieldList{
List: []*ast.Field{
&ast.Field{
Type: &ast.Ident{
Name: "string",
},
},
},
},
},
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.ReturnStmt{
Results: []ast.Expr{
&ast.BasicLit{
Kind: token.STRING,
Value: fmt.Sprintf("\"%s\"", ret),
},
},
},
},
},
}
}
func (c *StructCreator) PkFunc() *ast.FuncDecl {
return c.makeFunc("Pk", c.Pk)
}
func (c *StructCreator) TableFunc() *ast.FuncDecl {
return c.makeFunc("TableName", c.TableName)
}