/
api.go
314 lines (265 loc) · 7.48 KB
/
api.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
/*
* Copyright (c) 2023 Maple Wu <justmaplewu@gmail.com>
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package plugins
import (
_ "embed"
"fmt"
"go/ast"
"sort"
"strings"
zcore "github.com/go-zing/gozz-core"
)
//go:embed api.go.tmpl
var apiTemplateText string
const (
apiDefaultFilename = "zzgen.api.go"
paramDecode = "var in {{ .Param }};if err:=dec(&in);err!=nil{return nil,err};"
invokeBaseTemplate = `func(ctx context.Context, dec func(interface{}) error) (interface{},error) {
%s%s t.{{ .Name }}(%s)%s}`
)
func init() {
zcore.RegisterPlugin(Api{})
}
type (
Api struct {
Imports []zcore.Import
Interfaces []ApiInterface
}
ApiHandler struct {
Name string
Resource string
Options map[string]string
Invoke string
}
ApiInterface struct {
Package string
Name string
Handlers []ApiHandler
}
)
func (i ApiInterface) FieldName() string {
s := i.Name
if len(i.Package) > 0 {
s = i.Package + "_" + s
}
return strings.Title(s)
}
func (i ApiInterface) TypeName() string {
if len(i.Package) > 0 {
return i.Package + "." + i.Name
}
return i.Name
}
func (a Api) Name() string { return "api" }
func (a Api) Args() ([]string, map[string]string) {
return []string{"filename:specify filename to generate api stubs and template files"}, nil
}
func (a Api) Description() string {
return "generate api specification stubs from interface declarations with template."
}
func (a Api) Run(entities zcore.DeclEntities) (err error) {
group, err := a.group(entities)
if err != nil {
return
}
eg := new(zcore.ErrGroup)
for key := range group {
filename := key
eg.Go(func() error { return a.generateApi(filename, group[filename]) })
}
return eg.Wait()
}
func (a Api) group(entities zcore.DeclEntities) (group map[string]map[*zcore.AnnotatedDecl]zcore.FieldEntities, err error) {
group = make(map[string]map[*zcore.AnnotatedDecl]zcore.FieldEntities)
for _, entity := range entities {
if entity.Type != zcore.DeclTypeInterface {
continue
}
filename := entity.RelFilename(entity.Args[0], apiDefaultFilename)
if group[filename] == nil {
group[filename] = make(map[*zcore.AnnotatedDecl]zcore.FieldEntities)
}
group[filename][entity.AnnotatedDecl] = append(group[filename][entity.AnnotatedDecl], entity.ParseFields(1, entity.Options)...)
}
return
}
func (Api) generateApi(filename string, typeMap map[*zcore.AnnotatedDecl]zcore.FieldEntities) (err error) {
var (
imports = zcore.Imports{"context": "context"}
dstImportPath = zcore.GetImportPath(filename)
interfaces = make([]ApiInterface, 0)
)
for typ, fields := range typeMap {
api := ApiInterface{Name: typ.Name()}
for i, field := range fields {
if i == 0 {
if srcImportPath := zcore.GetImportPath(field.Decl.File.Path); srcImportPath != dstImportPath {
api.Package = imports.Add(srcImportPath)
}
}
funcName, ft, ok := zcore.AssertFuncType(field.Field)
if !ok {
continue
}
executeTemplate := func(v string) string {
zcore.TryExecuteTemplate(struct {
Name, FieldName, Package string
}{
FieldName: funcName,
Name: api.Name,
Package: typ.Package(),
}, v, &v)
return v
}
handler := ApiHandler{
Name: funcName,
Resource: executeTemplate(field.Args[0]),
Options: make(map[string]string),
}
for k, v := range field.Options {
handler.Options[k] = executeTemplate(v)
}
// try parse method invoke function
if pt, tmpl := (*funcType)(ft).InvokeTemplate(); len(tmpl) > 0 {
// render invoke template
zcore.TryExecuteTemplate(struct{ Name, Param string }{
Name: funcName,
Param: zcore.UnsafeBytes2String(field.Decl.File.ReplacePackages(pt, filename, imports)),
}, tmpl, &handler.Invoke)
}
api.Handlers = append(api.Handlers, handler)
}
interfaces = append(interfaces, api)
}
if len(interfaces) == 0 {
return
}
sort.Slice(interfaces, func(i, j int) bool {
return interfaces[i].Package+"."+interfaces[i].Name < interfaces[j].Package+"."+interfaces[j].Name
})
return zcore.RenderWithDefaultTemplate(&Api{
Imports: imports.List(),
Interfaces: interfaces,
}, apiTemplateText, filename, zcore.GetImportName(filename), false)
}
type funcType ast.FuncType
func (ft *funcType) InvokeTemplate() (paramType ast.Node, template string) {
// params/results values count must equal to params/results types count
// because valid multi params/results must in different types
// example: func(context.Context, types.Query) (types.Response, error)
if (ft.Params != nil && ft.Params.NumFields() != len(ft.Params.List)) ||
(ft.Results != nil && ft.Results.NumFields() != len(ft.Results.List)) {
return
}
// alloc param / call decode / invoke method with params
param, decode, paramType, ok := ft.params()
if !ok {
return
}
// assign result values / return values
ret, ret2, ok := ft.returns()
if !ok {
return
}
template = fmt.Sprintf(invokeBaseTemplate, decode, ret, param, ret2)
return
}
func (ft *funcType) returns() (ret, ret2 string, valid bool) {
isError := func(e ast.Expr) bool { i, ok := e.(*ast.Ident); return ok && i.Name == "error" }
// no results value
// func (...)
if ft.Results == nil || ft.Results.NumFields() == 0 {
ret2 = ";return nil,nil"
valid = true
return
}
switch len(ft.Results.List) {
case 1:
if isError(ft.Results.List[0].Type) {
// func (...) (error)
ret = "return nil,"
} else {
// func (...) (types.Response)
ret = "return"
ret2 = ",nil"
}
case 2:
if !isError(ft.Results.List[1].Type) {
// invalid second results type
// func (...) (types.Response, types.Other)
return
}
// func (...) (types.Response, error)
ret = "return"
default:
// more than 2 results
// func (...) (types.Response, types.Response2, error)
return
}
valid = true
return
}
func (ft *funcType) params() (param, decode string, paramType ast.Node, valid bool) {
isContext := func(e ast.Expr) bool {
s, ok := e.(*ast.SelectorExpr)
return ok && fmt.Sprintf("%s.%s", s.X, s.Sel) == "context.Context"
}
// no params
// func () ...
if ft.Params == nil || ft.Params.NumFields() == 0 {
valid = true
return
}
switch len(ft.Params.List) {
case 1:
if isContext(ft.Params.List[0].Type) {
// func (context.Context) ...
param = "ctx"
} else {
// func (types.Param) ...
decode = paramDecode
paramType = ft.Params.List[0].Type
if se, ok := paramType.(*ast.StarExpr); ok {
paramType = se.X
param = "&in"
} else {
param = "in"
}
}
case 2:
if !isContext(ft.Params.List[0].Type) {
// invalid first params type
// func (types.Other, types.Query) ...
return
}
// func (context.Context, types.Param) ...
decode = paramDecode
paramType = ft.Params.List[1].Type
if se, ok := paramType.(*ast.StarExpr); ok {
paramType = se.X
param = "ctx,&in"
} else {
param = "ctx,in"
}
default:
// more than 2 params
// func (context.Context, types.Param, types.Param2) ...
return
}
valid = true
return
}