/
generate.go
391 lines (344 loc) · 8.19 KB
/
generate.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
package generate
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
"os"
"sort"
"strings"
"text/template"
"github.com/panagiotisptr/proxygen/templates"
"golang.org/x/tools/go/packages"
)
type ImportData struct {
Path string
Name string
Alias string
Used bool
}
func (id ImportData) Selector() string {
if id.Alias != "" {
return id.Alias
}
return id.Name
}
type MethodParam string
func (m MethodParam) IsVariadic() bool {
return strings.HasPrefix(string(m), "...")
}
func (m MethodParam) Type() string {
if m.IsVariadic() {
return "[]" + strings.TrimPrefix(string(m), "...")
}
return string(m)
}
type MethodData struct {
Name string
Params []MethodParam
Rets []string
}
type InterfaceData struct {
InterfacePackage string
InterfaceName string
Imports []*ImportData
Methods []*MethodData
ImplementationType string
OriginalPackageName string
}
const mode packages.LoadMode = packages.NeedName |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedTypesInfo |
packages.NeedImports
type Generator struct {
cfg *packages.Config
}
func NewGenerator() *Generator {
return &Generator{
cfg: &packages.Config{
Fset: token.NewFileSet(),
Mode: mode,
Dir: ".",
},
}
}
func (g *Generator) GenerateProxy(
interfacePath string,
packageName string,
name string,
output string,
) error {
sections := strings.Split(interfacePath, ".")
packagePath := strings.Join(sections[:len(sections)-1], ".")
interfaceName := sections[len(sections)-1]
data, err := g.getInterfaceData(packagePath, interfaceName, packageName)
if err != nil {
return err
}
// fix the imports for the main package
if data.OriginalPackageName != packageName {
for _, m := range data.Imports {
if m.Path == packagePath {
m.Used = true
break
}
}
}
//render template
tmpl := template.Must(template.New("proxy").Parse(templates.ProxyTemplate))
var generatedProxy bytes.Buffer
err = tmpl.Execute(&generatedProxy, struct {
PackageName string
Name string
InterfaceData
}{
PackageName: packageName,
Name: name,
InterfaceData: data,
})
if err != nil {
return err
}
// foramt generated proxy
formattedContent, formatErr := format.Source(generatedProxy.Bytes())
if formatErr != nil {
return fmt.Errorf("error formatting generated proxy: %w", formatErr)
}
// write file
f, err := os.Create(output)
if err != nil {
return fmt.Errorf("error creating file: %w", err)
}
defer f.Close()
_, err = f.Write(formattedContent)
if err != nil {
return fmt.Errorf("error writing file: %w", err)
}
return nil
}
func (g *Generator) getInterfaceData(
interfacePackage string,
interfaceName string,
outputPkgName string,
) (InterfaceData, error) {
data := InterfaceData{
InterfacePackage: interfacePackage,
InterfaceName: interfaceName,
Imports: []*ImportData{},
}
existingImports := []*ImportData{}
newImports := []*ImportData{}
pkg, err := g.getPackage(interfacePackage)
if err != nil {
return data, err
}
// load imports
newImports = append(newImports, &ImportData{
Path: interfacePackage,
Name: pkg.Name,
})
keys := make([]string, len(pkg.Imports))
i := 0
for k := range pkg.Imports {
keys[i] = k
i++
}
// sort imports to ensure that generated code is deterministic
sort.Strings(keys)
for i := range keys {
imp := pkg.Imports[keys[i]]
existingImports = append(existingImports, &ImportData{
Path: imp.PkgPath,
Name: imp.Name,
})
newImports = append(newImports, &ImportData{
Path: imp.PkgPath,
Name: imp.Name,
})
}
// useful later to determine wether or not this package was used
for i := range newImports {
// alias all new imports so that they won't conflict with anything we might add
// later - which could be from merging embedded interface imports
newImports[i].Alias = fmt.Sprintf("import%s%s%d", pkg.Name, interfaceName, i)
}
var interfaceFile *ast.File
for _, fileAst := range pkg.Syntax {
interfaceFile = fileAst
ifaceTypeSpec, ifaceErr := g.getInterface(fileAst, interfaceName)
if ifaceErr != nil {
continue
}
iface := ifaceTypeSpec.Type.(*ast.InterfaceType)
ifaceIdent := ifaceTypeSpec.Name
// update aliases of existing imports
ast.Inspect(fileAst, func(n ast.Node) bool {
switch t := n.(type) {
case *ast.ImportSpec:
// check if it's import
if t.Name != nil {
for i, imp := range existingImports {
p := strings.ReplaceAll(t.Path.Value, "\"", "")
if imp.Path == p {
existingImports[i].Alias = t.Name.Name
}
}
}
return false
}
return true
})
data.Imports = newImports
fset := g.cfg.Fset
filename := fset.Position(interfaceFile.Package).Filename
content, _ := os.ReadFile(filename)
tp, err := NewTypeProcessor(pkg, g.cfg.Fset, filename)
if err != nil {
return data, err
}
addSelectorToLocals := pkg.Name != outputPkgName
for _, m := range iface.Methods.List {
if m.Names == nil {
continue
}
methodData := &MethodData{
Name: m.Names[0].Name,
}
if m.Type != nil {
switch t := m.Type.(type) {
case *ast.FuncType:
if t.Params != nil {
for _, param := range t.Params.List {
for i := 0; i < max(1, len(param.Names)); i++ {
methodData.Params = append(
methodData.Params,
MethodParam(tp.correctType(
param.Type,
existingImports,
newImports,
interfacePackage,
addSelectorToLocals,
)),
)
}
}
}
if t.Results != nil {
for _, result := range t.Results.List {
for i := 0; i < max(1, len(result.Names)); i++ {
methodData.Rets = append(
methodData.Rets,
tp.correctType(
result.Type,
existingImports,
newImports,
interfacePackage,
addSelectorToLocals,
),
)
}
}
}
}
}
data.Methods = append(data.Methods, methodData)
}
data.ImplementationType = tp.correctType(
ifaceIdent,
existingImports,
newImports,
interfacePackage,
addSelectorToLocals,
)
// used later to make sure it's imported if needed
data.OriginalPackageName = pkg.Name
queue := [][2]string{}
ast.Inspect(iface, func(n ast.Node) bool {
switch t := n.(type) {
case *ast.Field:
// we know that all embedded interfaces don't have names
if len(t.Names) == 0 {
return true
}
return false
case *ast.Ident:
queue = append(queue, [2]string{interfacePackage, t.Name})
return false
case *ast.SelectorExpr:
selectorStart := fset.Position(t.X.Pos())
selectorEnd := fset.Position(t.X.End())
selectorPkg := string(content[selectorStart.Offset:selectorEnd.Offset])
for _, i := range existingImports {
if i.Selector() == selectorPkg {
for idx := range newImports {
if newImports[idx].Path == i.Path {
queue = append(queue, [2]string{newImports[idx].Path, t.Sel.Name})
return false
}
}
}
}
return false
}
return true
})
for _, embeddedIface := range queue {
embeddedData, embeddedErr := g.getInterfaceData(
embeddedIface[0],
embeddedIface[1],
outputPkgName,
)
if embeddedErr != nil {
continue
}
data.Imports = append(data.Imports, embeddedData.Imports...)
data.Methods = append(data.Methods, embeddedData.Methods...)
}
}
return data, nil
}
func (g *Generator) getPackage(pkgPath string) (
*packages.Package,
error,
) {
pkgs, err := packages.Load(g.cfg, pkgPath)
if err != nil {
return nil, err
}
var pkg *packages.Package
for _, p := range pkgs {
if p.PkgPath == pkgPath {
pkg = p
break
}
}
if pkg == nil {
return nil, fmt.Errorf("package %s not found", pkgPath)
}
return pkg, nil
}
func (g *Generator) getInterface(fileAst *ast.File, name string) (*ast.TypeSpec, error) {
var rv *ast.TypeSpec
ast.Inspect(fileAst, func(n ast.Node) bool {
switch t := n.(type) {
case *ast.TypeSpec:
if !t.Name.IsExported() {
return false
}
if t.Name.Name != name {
return false
}
if _, ok := t.Type.(*ast.InterfaceType); ok {
rv = t
return false
}
}
return true
})
if rv == nil {
return nil, fmt.Errorf("interface %s not found", name)
}
return rv, nil
}