-
Notifications
You must be signed in to change notification settings - Fork 249
/
funcs.go
385 lines (363 loc) · 10.5 KB
/
funcs.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
package astutils
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
"github.com/unionj-cloud/go-doudou/toolkit/constants"
"github.com/unionj-cloud/go-doudou/toolkit/stringutils"
"go/ast"
"go/format"
"golang.org/x/tools/imports"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"unicode"
)
func GetImportStatements(input []byte) []byte {
reg := regexp.MustCompile("(?s)import \\((.*?)\\)")
if !reg.Match(input) {
return nil
}
matches := reg.FindSubmatch(input)
return matches[1]
}
func AppendImportStatements(src []byte, appendImports []byte) []byte {
reg := regexp.MustCompile("(?s)import \\((.*?)\\)")
if !reg.Match(src) {
return src
}
matches := reg.FindSubmatch(src)
old := matches[1]
re := regexp.MustCompile(`[\r\n]+`)
splits := re.Split(string(old), -1)
oldmap := make(map[string]struct{})
for _, item := range splits {
oldmap[strings.TrimSpace(item)] = struct{}{}
}
splits = re.Split(string(appendImports), -1)
var newimps []string
for _, item := range splits {
key := strings.TrimSpace(item)
if _, ok := oldmap[key]; !ok {
newimps = append(newimps, "\t"+key)
}
}
if len(newimps) == 0 {
return src
}
appendImports = []byte(constants.LineBreak + strings.Join(newimps, constants.LineBreak) + constants.LineBreak)
return reg.ReplaceAllFunc(src, func(i []byte) []byte {
old = append([]byte("import ("), old...)
old = append(old, appendImports...)
old = append(old, []byte(")")...)
return old
})
}
// FixImport format source code and add missing import syntax automatically
func FixImport(src []byte, file string) {
var (
res []byte
err error
)
if res, err = imports.Process(file, src, &imports.Options{
TabWidth: 8,
TabIndent: true,
Comments: true,
Fragment: true,
}); err != nil {
panic(err)
}
_ = ioutil.WriteFile(file, res, os.ModePerm)
}
// GetMethodMeta get method name then new MethodMeta struct from *ast.FuncDecl
func GetMethodMeta(spec *ast.FuncDecl) MethodMeta {
methodName := ExprString(spec.Name)
mm := NewMethodMeta(spec.Type, ExprString)
mm.Name = methodName
return mm
}
// NewMethodMeta new MethodMeta struct from *ast.FuncDecl
func NewMethodMeta(ft *ast.FuncType, exprString func(ast.Expr) string) MethodMeta {
var params, results []FieldMeta
for _, param := range ft.Params.List {
pt := exprString(param.Type)
if len(param.Names) > 0 {
for _, name := range param.Names {
params = append(params, FieldMeta{
Name: name.Name,
Type: pt,
Tag: "",
})
}
continue
}
params = append(params, FieldMeta{
Name: "",
Type: pt,
Tag: "",
})
}
if ft.Results != nil {
for _, result := range ft.Results.List {
rt := exprString(result.Type)
if len(result.Names) > 0 {
for _, name := range result.Names {
results = append(results, FieldMeta{
Name: name.Name,
Type: rt,
Tag: "",
})
}
continue
}
results = append(results, FieldMeta{
Name: "",
Type: rt,
Tag: "",
})
}
}
return MethodMeta{
Params: params,
Results: results,
}
}
// NewStructMeta new StructMeta from *ast.StructType
func NewStructMeta(structType *ast.StructType, exprString func(ast.Expr) string) StructMeta {
var fields []FieldMeta
re := regexp.MustCompile(`json:"(.*?)"`)
for _, field := range structType.Fields.List {
var fieldComments []string
if field.Doc != nil {
for _, comment := range field.Doc.List {
fieldComments = append(fieldComments, strings.TrimSpace(strings.TrimPrefix(comment.Text, "//")))
}
}
fieldType := exprString(field.Type)
var tag string
var docName string
if field.Tag != nil {
tag = strings.Trim(field.Tag.Value, "`")
if re.MatchString(tag) {
docName = strings.TrimSuffix(re.FindStringSubmatch(tag)[1], ",omitempty")
}
}
if len(field.Names) > 0 {
for _, name := range field.Names {
_docName := docName
if stringutils.IsEmpty(_docName) {
_docName = name.Name
}
fields = append(fields, FieldMeta{
Name: name.Name,
Type: fieldType,
Tag: tag,
Comments: fieldComments,
IsExport: unicode.IsUpper(rune(name.Name[0])),
DocName: _docName,
})
}
} else {
splits := strings.Split(fieldType, ".")
name := splits[len(splits)-1]
fieldType = "embed:" + fieldType
_docName := docName
if stringutils.IsEmpty(_docName) {
_docName = name
}
fields = append(fields, FieldMeta{
Name: name,
Type: fieldType,
Tag: tag,
Comments: fieldComments,
IsExport: unicode.IsUpper(rune(name[0])),
DocName: _docName,
})
}
}
return StructMeta{
Fields: fields,
}
}
// PackageMeta wraps package info
type PackageMeta struct {
Name string
}
// FieldMeta wraps field info
type FieldMeta struct {
Name string
Type string
Tag string
Comments []string
IsExport bool
// used in OpenAPI 3.0 spec as property name
DocName string
}
// StructMeta wraps struct info
type StructMeta struct {
Name string
Fields []FieldMeta
Comments []string
Methods []MethodMeta
IsExport bool
}
// EnumMeta wraps struct info
type EnumMeta struct {
Name string
Values []string
}
// ExprString return string representation from ast.Expr
func ExprString(expr ast.Expr) string {
switch _expr := expr.(type) {
case *ast.Ident:
return _expr.Name
case *ast.StarExpr:
return "*" + ExprString(_expr.X)
case *ast.SelectorExpr:
return ExprString(_expr.X) + "." + _expr.Sel.Name
case *ast.InterfaceType:
return "interface{}"
case *ast.ArrayType:
if _expr.Len == nil {
return "[]" + ExprString(_expr.Elt)
}
return "[" + ExprString(_expr.Len) + "]" + ExprString(_expr.Elt)
case *ast.BasicLit:
return _expr.Value
case *ast.MapType:
return "map[" + ExprString(_expr.Key) + "]" + ExprString(_expr.Value)
case *ast.StructType:
structmeta := NewStructMeta(_expr, ExprString)
b, _ := json.Marshal(structmeta)
return "anonystruct«" + string(b) + "»"
case *ast.FuncType:
return NewMethodMeta(_expr, ExprString).String()
case *ast.ChanType:
var result string
if _expr.Dir == ast.SEND {
result += "chan<- "
} else if _expr.Dir == ast.RECV {
result += "<-chan "
} else {
result += "chan "
}
return result + ExprString(_expr.Value)
case *ast.Ellipsis:
if _expr.Ellipsis.IsValid() {
return "..." + ExprString(_expr.Elt)
}
panic(fmt.Sprintf("invalid ellipsis expression: %+v\n", expr))
default:
panic(fmt.Sprintf("not support expression: %+v\n", expr))
}
}
// MethodMeta represents an api
type MethodMeta struct {
// Recv method receiver
Recv string
// Name method name
Name string
// Params when generate client code from openapi3 spec json file, Params holds all method input parameters.
// when generate client code from service interface in svc.go file, if there is struct type param, this struct type param will put into request body,
// then others will be put into url as query string. if there is no struct type param and the api is a get request, all will be put into url as query string.
// if there is no struct type param and the api is Not a get request, all will be put into request body as application/x-www-form-urlencoded data.
// specially, if there is one or more v3.FileModel or []v3.FileModel params,
// all will be put into request body as multipart/form-data data.
Params []FieldMeta
// Results response
Results []FieldMeta
// PathVars not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, PathVars is parameters in url as path variable.
PathVars []FieldMeta
// HeaderVars not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, HeaderVars is parameters in header.
HeaderVars []FieldMeta
// BodyParams not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, BodyParams is parameters in request body as query string.
BodyParams *FieldMeta
// BodyJSON not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, BodyJSON is parameters in request body as json.
BodyJSON *FieldMeta
// Files not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, Files is parameters in request body as multipart file.
Files []FieldMeta
// Comments of the method
Comments []string
// Path api path
// not support when generate client code from service interface in svc.go file
Path string
// QueryParams not support when generate client code from service interface in svc.go file
// when generate client code from openapi3 spec json file, QueryParams is parameters in url as query string.
QueryParams *FieldMeta
}
const methodTmpl = `func {{ if .Recv }}(receiver {{.Recv}}){{ end }} {{.Name}}({{- range $i, $p := .Params}}
{{- if $i}},{{end}}
{{- $p.Name}} {{$p.Type}}
{{- end }}) ({{- range $i, $r := .Results}}
{{- if $i}},{{end}}
{{- $r.Name}} {{$r.Type}}
{{- end }})`
func (mm MethodMeta) String() string {
if stringutils.IsNotEmpty(mm.Recv) && stringutils.IsEmpty(mm.Name) {
panic("not valid code")
}
var isAnony bool
if stringutils.IsEmpty(mm.Name) {
isAnony = true
mm.Name = "placeholder"
}
t, _ := template.New("method.tmpl").Parse(methodTmpl)
var buf bytes.Buffer
_ = t.Execute(&buf, mm)
var res []byte
res, _ = format.Source(buf.Bytes())
result := string(res)
if isAnony {
return strings.Replace(result, "func placeholder(", "func(", 1)
}
return result
}
// InterfaceMeta wraps interface info
type InterfaceMeta struct {
Name string
Methods []MethodMeta
Comments []string
}
// Visit visit each files
func Visit(files *[]string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
logrus.Panicln(err)
}
if !info.IsDir() {
*files = append(*files, path)
}
return nil
}
}
// GetMod get module name from go.mod file
func GetMod() string {
var (
f *os.File
err error
firstLine string
)
dir, _ := os.Getwd()
mod := filepath.Join(dir, "go.mod")
if f, err = os.Open(mod); err != nil {
panic(err)
}
reader := bufio.NewReader(f)
firstLine, _ = reader.ReadString('\n')
return strings.TrimSpace(strings.TrimPrefix(firstLine, "module"))
}
// GetImportPath get import path of pkg from dir
func GetImportPath(dir string) string {
wd, _ := os.Getwd()
return GetMod() + strings.ReplaceAll(strings.TrimPrefix(dir, wd), `\`, `/`)
}