forked from ezbuy/tgen
/
data.go
363 lines (275 loc) · 7.43 KB
/
data.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
package gogen
import (
"bytes"
"fmt"
"go/format"
"io"
"os"
"path/filepath"
"strings"
"github.com/seaWind0112/tgen/global"
"github.com/samuel/go-thrift/parser"
)
type Package struct {
PkgName string
ImportPath string
includes map[string]*Package
thrift *parser.Thrift
TplUtils
ValidateParams bool
}
func newPackage(thrift *parser.Thrift) *Package {
pkg := &Package{}
pkg.setup(thrift)
return pkg
}
func (this *Package) setup(thrift *parser.Thrift) {
namespace := thrift.Namespaces[langName]
this.PkgName, this.ImportPath = this.GenNamespace(namespace)
this.thrift = thrift
this.ValidateParams = global.ValidateParams
}
func (this *Package) setupIncludes(packages map[string]*Package) {
pkgMap := map[string]*Package{}
for includeName, filename := range this.thrift.Includes {
pkg, ok := packages[filename]
if !ok {
exitWithError("include thrift %q ( %s ) not found", includeName, filename)
}
pkgMap[includeName] = pkg
}
this.includes = pkgMap
}
func (this *Package) Includes() map[string]*Package {
return this.includes
}
func (this *Package) Enums() map[string]*parser.Enum {
return this.thrift.Enums
}
func (this *Package) Structs() map[string]*parser.Struct {
return this.thrift.Structs
}
func (this *Package) Services() map[string]*parser.Service {
return this.thrift.Services
}
func (this *Package) Constants() map[string]*parser.Constant {
return this.thrift.Constants
}
func (this *Package) Typedefs() map[string]*parser.Typedef {
return this.thrift.Typedefs
}
func (this *Package) Exceptions() map[string]*parser.Struct {
return this.thrift.Exceptions
}
func (this *Package) Unions() map[string]*parser.Struct {
return this.thrift.Unions
}
func (this *Package) Namespaces() map[string]string {
return this.thrift.Namespaces
}
func (this *Package) FullImportPath() string {
if global.NamespacePrefix != "" {
return global.NamespacePrefix + "/" + this.ImportPath
}
return this.ImportPath
}
func (this *Package) Namespace() string {
return this.thrift.Namespaces[langName]
}
func (this *Package) WebApiPrefix() string {
namespace := this.thrift.Namespaces["webapi"]
if namespace != "" {
namespace = slash + strings.Replace(namespace, dot, slash, -1)
}
return namespace
}
func (this *Package) GenTypeString(fieldName string, typ, parent *parser.Type, optional bool) string {
if typ == nil {
panicWithErr("field %s with nil type", fieldName)
}
var str string
switch typ.Name {
case TypeBool, TypeByte, TypeI16, TypeI32, TypeI64, TypeDouble, TypeString:
if optional {
str = "*"
}
str += typeStrs[typ.Name]
case TypeBinary:
if parent != nil && typ == parent.KeyType {
panicWithErr("map field %s with binary key", fieldName)
}
str = typeStrs[TypeBinary]
case TypeList:
if parent != nil && typ == parent.KeyType {
panicWithErr("map field %s with list key", fieldName)
}
if typ.ValueType == nil {
panicWithErr("list field %s with nil value type", fieldName)
}
str = fmt.Sprintf("[]%s", this.GenTypeString(fieldName, typ.ValueType, typ, false))
case TypeMap:
if parent != nil && typ == parent.KeyType {
panicWithErr("map field %s with map key", fieldName)
}
if typ.KeyType == nil {
panicWithErr("map field %s with nil key type", fieldName)
}
if typ.ValueType == nil {
panicWithErr("map field %s with nil value type", fieldName)
}
str = fmt.Sprintf("map[%s]%s",
this.GenTypeString(fieldName, typ.KeyType, typ, false),
this.GenTypeString(fieldName, typ.ValueType, typ, false),
)
case TypeSet:
// TODO: support set
default:
if typ.Name == "" {
panicWithErr("field %s without type name", fieldName)
}
// 非必选的 field, 使用指针
usePtr := optional
include := ""
name := typ.Name
pkg := this
// 形为 <include>.<typeName>
pieces := strings.Split(name, dot)
if len(pieces) > 1 {
name = pieces[1]
// 找到指定的 package
if pkg, _ = this.includes[pieces[0]]; pkg == nil {
panicWithErr("include package %q not found", include)
}
include = pkg.PkgName
}
// 对于实际是 Struct 的类型, 统一使用指针
if pkg.isStructType(name) {
usePtr = true
}
if usePtr {
str += "*"
}
if include != "" {
str += include + "."
}
str += this.UpperHead(name)
}
return str
}
func (this *Package) GenServiceMethodArguments(fields []*parser.Field) string {
var str string
maxIdx := len(fields) - 1
for idx, field := range fields {
argName := this.renameInvalidArgumentName(field.Name)
str += fmt.Sprintf("%s %s", argName, this.GenTypeString(field.Name, field.Type, nil, field.Optional))
if idx != maxIdx {
str += ", "
}
}
return str
}
func (this *Package) renameInvalidArgumentName(n string) string {
if n == "type" || n == "case" || n == "struct" || n == "if" || n == "switch" || n == "map" ||
n == "go" || n == "func" || n == "var" || n == "range" || n == "for" || n == "append" ||
n == "default" || n == "return" {
return "a" + this.UpperHead(n)
}
return n
}
func (this *Package) GenServiceMethodReturn(method *parser.Method) string {
if method.ReturnType == nil {
return "error"
}
return fmt.Sprintf("(%s, error)", this.GenTypeString("method return value", method.ReturnType, nil, false))
}
func (this *Package) GenWebApiServiceParams(fields []*parser.Field) string {
var str string
maxIdx := len(fields) - 1
for idx, field := range fields {
str += fmt.Sprintf("params.%s", this.UpperHead(field.Name))
if idx != maxIdx {
str += ", "
}
}
return str
}
func (this *Package) GenConstants(constant *parser.Constant) string {
format, ok := constantValueFormat[constant.Type.Name]
if !ok {
return ""
}
return fmt.Sprintf("%s %s = "+format, constant.Name, typeStrs[constant.Type.Name], constant.Value)
}
func (this *Package) IsStruct(typ *parser.Type) bool {
name := typ.Name
switch name {
case TypeBool,
TypeByte,
TypeI16,
TypeI32,
TypeI64,
TypeDouble,
TypeString,
TypeBinary,
TypeList,
TypeMap,
TypeSet:
return false
}
pkg := this
// 形为 <include>.<typeName>
pieces := strings.Split(name, dot)
if len(pieces) > 1 {
name = pieces[1]
// 找到指定的 package
pkg, _ = this.includes[pieces[0]]
}
if pkg == nil {
return false
}
return pkg.isStructType(name)
}
func (this *Package) isStructType(name string) bool {
if _, ok := this.thrift.Structs[name]; ok {
return true
}
if _, ok := this.thrift.Exceptions[name]; ok {
return true
}
if _, ok := this.thrift.Unions[name]; ok {
return true
}
// TODO Typedefs
return false
}
func (this *Package) MethodRequestName(service, method string) string {
return fmt.Sprintf("%s%sRequest", service, method)
}
func (this *Package) MethodResponseName(service, method string) string {
return fmt.Sprintf("%s%sResponse", service, method)
}
func (this *Package) genOutputFilename(typ string) string {
return fmt.Sprintf("gen_%s_%s.go", this.PkgName, typ)
}
func (this *Package) render(tplName string, wr io.Writer) error {
buf := new(bytes.Buffer)
if err := tpl.ExecuteTemplate(buf, tplName, this); err != nil {
return err
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
return err
}
_, err = io.Copy(wr, bytes.NewBuffer(formatted))
return err
}
func (this *Package) renderToFile(dir, typ, tplName string) error {
filename := this.genOutputFilename(typ)
path := filepath.Join(dir, filename)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
return this.render(tplName, file)
}