-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
477 lines (423 loc) · 12.4 KB
/
generator.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
package decorate
import (
"bytes"
"encoding/json"
"fmt"
"go/token"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"unicode"
"github.com/chengyumeng/igen/pkg/consts"
"github.com/chengyumeng/igen/pkg/decorate/model"
"github.com/rogpeppe/go-internal/modfile"
toolsimports "golang.org/x/tools/imports"
)
type generator struct {
buf bytes.Buffer
indent string
auditNames map[string]string // may be empty
filename string // may be empty
destination string // may be empty
srcPackage string
copyrightHeader string
functions map[string]string
imports []string
logger string
prom string
packageMap map[string]string // map from import path to package name
}
func (g *generator) p(format string, args ...interface{}) {
fmt.Fprintf(&g.buf, g.indent+format+"\n", args...)
}
func (g *generator) in() {
g.indent += "\t"
}
func (g *generator) out() {
if len(g.indent) > 0 {
g.indent = g.indent[0 : len(g.indent)-1]
}
}
// Output returns the generator's output, formatted in the standard Go style.
func (g *generator) Output() []byte {
src, err := toolsimports.Process(g.destination, g.buf.Bytes(), nil)
if err != nil {
log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String())
}
return src
}
func (g *generator) Generate(pkg *model.Package, outputPackagePath string) error {
g.srcPackage = pkg.Name
if g.copyrightHeader != "" {
lines := strings.Split(g.copyrightHeader, "\n")
for _, line := range lines {
g.p("// %s", line)
}
g.p("")
}
g.p("// Code generated by GoInterface. DO NOT EDIT. design by 792400644@qq.com")
g.p("// Repo:https://github.com/chengyumeng/igen")
g.p("// Gen Version:" + consts.Version)
g.p("// " + strings.Join(os.Args, " "))
g.p("")
// Get all required imports, and generate unique names for them all.
im := pkg.Imports()
for _, v := range g.imports {
im[v] = true
}
// Only import reflect if it's used. We only use reflect in audit methods
// so only import if any of the audited interfaces have methods.
for _, intf := range pkg.Interfaces {
if len(intf.Methods) > 0 {
im["reflect"] = true
break
}
}
// Sort keys to make import alias generation predictable
sortedPaths := make([]string, len(im))
x := 0
for pth := range im {
sortedPaths[x] = pth
x++
}
sort.Strings(sortedPaths)
packagesName := createPackageMap(sortedPaths)
g.packageMap = make(map[string]string, len(im))
localNames := make(map[string]bool, len(im))
for _, pth := range sortedPaths {
base, ok := packagesName[pth]
if !ok {
base = sanitize(path.Base(pth))
}
// Local names for an imported package can usually be the basename of the import path.
// A couple of situations don't permit that, such as duplicate local names
// (e.g. importing "html/template" and "text/template"), or where the basename is
// a keyword (e.g. "foo/case").
// try base0, base1, ...
pkgName := base
i := 0
for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() {
pkgName = base + strconv.Itoa(i)
i++
}
// Avoid importing package if source pkg == output pkg
if pth == pkg.PkgPath && outputPackagePath == pkg.PkgPath {
continue
}
g.packageMap[pth] = pkgName
localNames[pkgName] = true
}
g.p("package %v", pkg.Name)
g.p("")
g.p("import (")
g.in()
for pkgPath, pkgName := range g.packageMap {
if pkgPath == outputPackagePath {
continue
}
g.p("%v %q", pkgName, pkgPath)
}
for _, pkgPath := range pkg.DotImports {
g.p(". %q", pkgPath)
}
g.out()
g.p(")")
for _, intf := range pkg.Interfaces {
if err := g.GenerateAuditInterface(intf, outputPackagePath, pkg.Skip); err != nil {
return err
}
}
return nil
}
// The name of the audit type to use for the given interface identifier.
func (g *generator) auditName(typeName string) string {
if auditName, ok := g.auditNames[typeName]; ok {
return auditName
}
return "Audit" + typeName
}
func (g *generator) GenerateAuditInterface(intf *model.Interface, outputPackagePath string, skip map[string]bool) error {
auditType := g.auditName(intf.Name)
g.p("")
g.p("// %v is a audit of %v interface.", auditType, intf.Name)
g.p("type %v struct {", auditType)
g.in()
g.p("client %v", intf.Name)
g.out()
g.p("}")
g.p("")
g.p("// New%v creates a new Gen instance.", auditType)
g.p("func New%v(client %v) %v {", auditType, intf.Name, intf.Name)
g.in()
g.p("audit := &%v{client: client}", auditType)
g.p("return audit")
g.out()
g.p("}")
g.p("")
g.GenerateAuditMethods(auditType, intf, outputPackagePath, skip)
return nil
}
// GenerateMethod generates a method implementation.
// If non-empty, pkgOverride is the package in which unqualified types reside.
func (g *generator) GenerateMethod(auditType string, m *model.Method, pkgOverride string, skip map[string]bool) error {
argNames := g.getArgNames(m)
argTypes := g.getArgTypes(m, pkgOverride)
argString := makeArgString(argNames, argTypes)
rets := make([]string, len(m.Out))
for i, p := range m.Out {
rets[i] = p.Type.String(g.packageMap, pkgOverride)
}
retString := strings.Join(rets, ", ")
if len(rets) > 1 {
retString = "(" + retString + ")"
}
if retString != "" {
retString = " " + retString
}
ia := newIdentifierAllocator(argNames)
idRecv := ia.allocateIdentifier("m")
g.p("// %v audit base method.", m.Name)
g.p("func (%v *%v) %v(%v)%v {", idRecv, auditType, m.Name, argString, retString)
g.in()
if m.Variadic != nil {
argNames[len(argNames)-1] = argNames[len(argNames)-1] + "..."
}
if skip[m.Name] {
if len(m.Out) == 0 {
g.p("%s.client.%s(%s)", idRecv, m.Name, strings.Join(argNames, ","))
} else {
retNames := make([]string, len(rets))
for i, v := range rets {
if v == "error" {
retNames[i] = ia.allocateIdentifier("err")
} else {
retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i))
}
}
g.p("%s := %s.client.%s(%s)", strings.Join(retNames, ", "), idRecv, m.Name, strings.Join(argNames, ","))
g.p("return " + strings.Join(retNames, ", "))
}
g.p("}")
return nil
}
bg := ia.allocateIdentifier("begin")
g.p("%s := time.Now()", bg)
if len(m.Out) == 0 {
g.p("%s.client.%s(%s)", idRecv, m.Name, strings.Join(argNames, ","))
g.generateFunction(argTypes, argNames, nil, nil, false, ia, m, bg)
} else {
retNames := make([]string, len(rets))
hasError := false
for i, v := range rets {
if v == "error" {
hasError = true
retNames[i] = ia.allocateIdentifier("err")
} else {
retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i))
}
}
g.p("%s := %s.client.%s(%s)", strings.Join(retNames, ", "), idRecv, m.Name, strings.Join(argNames, ","))
g.generateFunction(argTypes, argNames, rets, retNames, hasError, ia, m, bg)
g.p("return " + strings.Join(retNames, ", "))
}
g.out()
g.p("}")
return nil
}
func (g *generator) generateFunction(argTypes, argNames []string, rets, retNames []string, hasError bool, ia identifierAllocator, m *model.Method, bg string) {
req, reqArgv := g.fmt(argTypes, argNames, ia)
rsp, rspArgv := g.fmt(rets, retNames, ia)
if g.prom != "" {
if hasError {
g.p(g.prom+`("%s","%s",err)`, g.srcPackage, m.Name)
} else {
g.p(g.prom+`("%s","%s",nil)`, g.srcPackage, m.Name)
}
}
g.p(`%s("function: %s, time: %s req: %s rsp: %s",time.Since(%s),%s,%s)`, g.logger, m.Name, "%s", req, rsp, bg, strings.Join(reqArgv, ","), strings.Join(rspArgv, ","))
}
func (g *generator) fmt(arr, names []string, ia identifierAllocator) (layout string, args []string) {
for idx, v := range arr {
if fn, ok := g.functions[v]; ok {
layout += " %v"
if strings.HasPrefix(fn, ".") {
args = append(args, names[idx]+fn+"()")
} else if fn == "" {
args = append(args, names[idx])
} else if fn == "#json" {
k := ia.allocateIdentifier(names[idx])
g.p("%s,_ := json.Marshal(%s)", k, names[idx])
args = append(args, "string("+k+")")
} else {
args = append(args, fn+"("+names[idx]+")")
}
}
}
if len(args) == 0 {
layout += " %v"
args = append(args, `"Empty"`)
}
return
}
func (g *generator) getArgNames(m *model.Method) []string {
argNames := make([]string, len(m.In))
for i, p := range m.In {
name := p.Name
if name == "" || name == "_" {
name = fmt.Sprintf("arg%d", i)
}
argNames[i] = name
}
if m.Variadic != nil {
name := m.Variadic.Name
if name == "" {
name = fmt.Sprintf("arg%d", len(m.In))
}
argNames = append(argNames, name)
}
return argNames
}
func (g *generator) getArgTypes(m *model.Method, pkgOverride string) []string {
argTypes := make([]string, len(m.In))
for i, p := range m.In {
argTypes[i] = p.Type.String(g.packageMap, pkgOverride)
}
if m.Variadic != nil {
argTypes = append(argTypes, "..."+m.Variadic.Type.String(g.packageMap, pkgOverride))
}
return argTypes
}
func (g *generator) GenerateAuditMethods(auditType string, intf *model.Interface, pkgOverride string, skip map[string]bool) {
sort.Sort(byMethodName(intf.Methods))
for _, m := range intf.Methods {
g.p("")
_ = g.GenerateMethod(auditType, m, pkgOverride, skip)
}
}
func makeArgString(argNames, argTypes []string) string {
args := make([]string, len(argNames))
for i, name := range argNames {
// specify the type only once for consecutive args of the same type
if i+1 < len(argTypes) && argTypes[i] == argTypes[i+1] {
args[i] = name
} else {
args[i] = name + " " + argTypes[i]
}
}
return strings.Join(args, ", ")
}
// sanitize cleans up a string to make a suitable package name.
func sanitize(s string) string {
t := ""
for _, r := range s {
if t == "" {
if unicode.IsLetter(r) || r == '_' {
t += string(r)
continue
}
} else {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
t += string(r)
continue
}
}
t += "_"
}
if t == "_" {
t = "x"
}
return t
}
type byMethodName []*model.Method
func (b byMethodName) Len() int { return len(b) }
func (b byMethodName) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name }
type identifierAllocator map[string]struct{}
func newIdentifierAllocator(taken []string) identifierAllocator {
a := make(identifierAllocator, len(taken))
for _, s := range taken {
a[s] = struct{}{}
}
return a
}
func (o identifierAllocator) allocateIdentifier(want string) string {
id := want
for i := 2; ; i++ {
if _, ok := o[id]; !ok {
o[id] = struct{}{}
return id
}
id = want + "_" + strconv.Itoa(i)
}
}
// createPackageMap returns a map of import path to package name
// for specified importPaths.
func createPackageMap(importPaths []string) map[string]string {
var pkg struct {
Name string
ImportPath string
}
pkgMap := make(map[string]string)
b := bytes.NewBuffer(nil)
args := []string{"list", "-json"}
args = append(args, importPaths...)
cmd := exec.Command("go", args...)
cmd.Stdout = b
cmd.Run()
dec := json.NewDecoder(b)
for dec.More() {
err := dec.Decode(&pkg)
if err != nil {
log.Printf("failed to decode 'go list' output: %v", err)
continue
}
pkgMap[pkg.ImportPath] = pkg.Name
}
return pkgMap
}
// parseImportPackage get package import path via source file
// an alternative implementation is to use:
// cfg := &packages.Config{Mode: packages.NeedName, Tests: true, Dir: srcDir}
// pkgs, err := packages.Load(cfg, "file="+source)
// However, it will call "go list" and slow down the performance
func parsePackageImport(srcDir string) (string, error) {
moduleMode := os.Getenv("GO111MODULE")
// trying to find the module
if moduleMode != "off" {
currentDir := srcDir
for {
dat, err := ioutil.ReadFile(filepath.Join(currentDir, "go.mod"))
if os.IsNotExist(err) {
if currentDir == filepath.Dir(currentDir) {
// at the root
break
}
currentDir = filepath.Dir(currentDir)
continue
} else if err != nil {
return "", err
}
modulePath := modfile.ModulePath(dat)
return filepath.ToSlash(filepath.Join(modulePath, strings.TrimPrefix(srcDir, currentDir))), nil
}
}
// fall back to GOPATH mode
goPaths := os.Getenv("GOPATH")
if goPaths == "" {
return "", fmt.Errorf("GOPATH is not set")
}
goPathList := strings.Split(goPaths, string(os.PathListSeparator))
for _, goPath := range goPathList {
sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator)
if strings.HasPrefix(srcDir, sourceRoot) {
return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil
}
}
return "", errOutsideGoPath
}