-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterfacegen.go
402 lines (324 loc) · 8.12 KB
/
interfacegen.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
package main
import (
"bytes"
"context"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"path/filepath"
"regexp"
"runtime/debug"
"strings"
"github.com/spf13/cobra"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/imports"
)
var (
skip = regexp.MustCompile(`//\s*interfacegen:skip`)
)
func main() {
var types []string
app := application{}
cmd := &cobra.Command{
Use: "interfacegen",
Short: "interfacegen generates interfaces from concrete types",
Version: buildVersionString(),
Run: func(cmd *cobra.Command, args []string) {
for _, t := range types {
components := strings.Split(t, ":")
wl := typeWhitelist{in: components[0]}
if len(components) > 1 {
wl.out = components[1]
}
app.TypeWhitelist = append(app.TypeWhitelist, wl)
}
err := app.Run(context.Background())
if err != nil {
log.Fatal(err)
}
},
}
cmd.Flags().StringVarP(&app.Output, "output", "o", "-", "output file for generated code")
cmd.Flags().StringVarP(&app.SrcPackage, "src", "s", "", "source package path")
cmd.Flags().StringVarP(&app.DstPackage, "dst", "d", "interfaces", "destination package name")
cmd.Flags().StringVarP(&app.Comment, "comment", "c", "Code generated by interfacegen. DO NOT EDIT.", "comment for generated packages")
cmd.Flags().BoolVar(&app.IncludeDocs, "doc", true, "whether to include method comments")
cmd.Flags().BoolVarP(&app.IncludePrivate, "private", "p", false, "include private methods")
cmd.Flags().StringSliceVarP(&types, "types", "t", nil, "whitelist of types to include in concreteName:interfaceName format (can repeat)")
cmd.Flags().BoolVarP(&app.IncludeAllPackages, "all", "a", true, "include all types")
err := cmd.MarkFlagRequired("src")
if err != nil {
log.Fatal(err)
}
err = cmd.Execute()
if err != nil {
log.Fatal(err)
}
}
type typeWhitelist struct {
in string
out string
}
type application struct {
IncludePrivate bool
SrcPackage string
DstPackage string
TypeWhitelist []typeWhitelist
IncludeAllPackages bool
Output string
Comment string
IncludeDocs bool
BuildFlags []string `flag:"buildflag" help:"pass argument to underlying build system (may be repeated)"`
}
// Run takes the args after flag processing and performs the specified query.
func (app *application) Run(ctx context.Context) error {
// Load, parse, and type-check the packages named on the command line.
mode := (packages.NeedName | packages.NeedFiles | packages.NeedImports |
packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedModule)
cfg := &packages.Config{
Mode: mode,
Tests: false,
BuildFlags: app.BuildFlags,
}
lpkgs, err := packages.Load(cfg, app.SrcPackage)
if err != nil {
return err
}
return app.parse(lpkgs)
}
func (app *application) parse(lpkgs []*packages.Package) error {
imports := map[string]bool{}
var interfaceDefs []interfaceDef
for _, lpkg := range lpkgs {
comments := populateDocs(lpkg)
var target *types.Package
if app.DstPackage != "" {
target = types.NewPackage(app.DstPackage, app.DstPackage)
} else {
target = lpkg.Types
}
qualifier := func(other *types.Package) string {
if target == other {
return ""
}
return other.Name()
}
scope := lpkg.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() && !app.IncludePrivate {
continue
}
if _, ok := obj.(*types.TypeName); ok {
name := obj.Name()
if len(app.TypeWhitelist) > 0 {
var found bool
for _, t := range app.TypeWhitelist {
if t.in == obj.Name() {
found = true
if t.out != "" {
name = t.out
}
break
}
}
if !found && !app.IncludeAllPackages {
continue
}
}
var methods []methodDef
for _, meth := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
if !meth.Obj().Exported() && !app.IncludePrivate {
continue
}
b := bytes.NewBuffer(nil)
sig := meth.Obj().Type().(*types.Signature)
types.WriteSignature(b, sig, qualifier)
slug := strings.Join([]string{lpkg.ID, obj.Name(), meth.Obj().Name()}, ".")
if shouldSkip(comments[slug]) {
continue
}
doc := comments[slug]
if !app.IncludeDocs {
doc = nil
}
methods = append(methods, methodDef{
Method: meth.Obj().Name() + b.String(),
Slug: slug,
Doc: doc,
})
}
if len(methods) == 0 {
continue
}
slug := strings.Join([]string{lpkg.ID, name}, ".")
if shouldSkip(comments[slug]) {
continue
}
doc := comments[slug]
if !app.IncludeDocs {
doc = nil
}
interfaceDefs = append(interfaceDefs, interfaceDef{
Name: name,
Doc: doc,
Methods: methods,
})
}
}
if len(interfaceDefs) == 0 {
continue
}
for _, imp := range lpkg.Imports {
imports[imp.ID] = true
}
if target != lpkg.Types {
imports[lpkg.ID] = true
}
}
if len(interfaceDefs) == 0 {
return fmt.Errorf("package %s contained no matching interfaces", app.SrcPackage)
}
var distinctImports []string
for path := range imports {
distinctImports = append(distinctImports, path)
}
code, err := app.generatePackage(distinctImports, interfaceDefs)
if err != nil {
return err
}
var formatted []byte
// Continue formatting the output until it stabilizes, as goimports
// can't currently remove duplicate unused imports in one shot.
for {
formatted, err = format([]byte(code))
if err != nil {
return err
}
if string(formatted) == code {
break
}
code = string(formatted)
}
switch app.Output {
case "", "-":
fmt.Println(string(formatted))
default:
return app.writeFile(formatted)
}
return nil
}
func (app *application) writeFile(data []byte) (err error) {
err = os.MkdirAll(filepath.Dir(app.Output), 0755)
if err != nil {
return err
}
w, err := os.OpenFile(app.Output, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer w.Close()
_, err = w.Write(data)
if err != nil {
return err
}
return nil
}
func format(code []byte) (formatted []byte, err error) {
opts := &imports.Options{
TabIndent: true,
TabWidth: 2,
Fragment: true,
Comments: true,
}
return imports.Process("", code, opts)
}
func populateDocs(p *packages.Package) map[string][]string {
ret := map[string][]string{}
for _, f := range p.Syntax {
for _, decl := range f.Decls {
switch v := decl.(type) {
case *ast.FuncDecl:
if v.Recv == nil || v.Doc == nil {
continue
}
se, ok := v.Recv.List[0].Type.(*ast.StarExpr)
if !ok {
continue
}
ident, ok := se.X.(*ast.Ident)
if !ok {
continue
}
var docs []string
for _, d := range v.Doc.List {
docs = append(docs, d.Text)
}
if len(docs) == 0 {
continue
}
slug := strings.Join([]string{p.ID, ident.Name, v.Name.String()}, ".")
ret[slug] = docs
case *ast.GenDecl:
if v.Tok != token.TYPE {
continue
}
spec := v.Specs[0].(*ast.TypeSpec)
var docs []string
if v.Doc == nil {
continue
}
for _, d := range v.Doc.List {
docs = append(docs, d.Text)
}
if len(docs) == 0 {
continue
}
slug := strings.Join([]string{p.ID, spec.Name.String()}, ".")
ret[slug] = docs
}
}
}
return ret
}
func shouldSkip(comments []string) bool {
for _, comment := range comments {
m := skip.MatchString(comment)
if m {
return true
}
}
return false
}
func buildVersionString() string {
var s string
info, ok := debug.ReadBuildInfo()
if !ok {
return "\nunknown"
}
if info.Main.Path != "" {
s += "\nmodule: " + info.Main.Path
}
if info.GoVersion != "" {
s += "\ncompiler: " + info.GoVersion
}
if info.Main.Version != "" {
s += "\nsemver: " + info.Main.Version
}
for _, buildSetting := range info.Settings {
if buildSetting.Value == "" {
continue
}
switch buildSetting.Key {
case "vcs.revision":
s += "\nvcs.revision: " + buildSetting.Value
case "vcs.time":
s += "\nvcs.revision.time: " + buildSetting.Value
}
}
return s
}