-
Notifications
You must be signed in to change notification settings - Fork 23
/
ifacer.go
391 lines (308 loc) · 7.53 KB
/
ifacer.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 ifacer
import (
"errors"
"fmt"
"go/types"
"path/filepath"
"strconv"
"strings"
"github.com/jukylin/esim/log"
"github.com/jukylin/esim/pkg"
filedir "github.com/jukylin/esim/pkg/file-dir"
"github.com/jukylin/esim/pkg/templates"
"github.com/spf13/viper"
"github.com/vektra/mockery/mockery"
"golang.org/x/tools/imports"
)
type Ifacer struct {
logger log.Logger
parser *mockery.Parser
IfaceName string
StructName string
IfacePath string
PackageName string
Methods []Method
Content string
Star string
OutFile string
// import from interface file.
pkgNoConflictImport map[string]pkg.Import
// import in the interface.
ifaceUsingIngImport map[string]string
writer filedir.IfaceWriter
tpl templates.Tpl
UsingImportStr string
}
type Option func(*Ifacer)
func NewIfacer(options ...Option) *Ifacer {
ifacer := &Ifacer{}
for _, option := range options {
option(ifacer)
}
ifacer.parser = mockery.NewParser([]string{})
ifacer.pkgNoConflictImport = make(map[string]pkg.Import)
ifacer.ifaceUsingIngImport = make(map[string]string)
return ifacer
}
func WithIfacerLogger(logger log.Logger) Option {
return func(f *Ifacer) {
f.logger = logger
}
}
func WithIfacerWriter(writer filedir.IfaceWriter) Option {
return func(f *Ifacer) {
f.writer = writer
}
}
func WithIfacerTpl(tpl templates.Tpl) Option {
return func(f *Ifacer) {
f.tpl = tpl
}
}
type Method struct {
FuncName string
ArgStr string
ReturnTypeStr string
ReturnStr string
InitReturnVarStr string
ReturnVar []string
}
func (f *Ifacer) Run(v *viper.Viper) error {
err := f.bindInput(v)
if err != nil {
return err
}
err = f.parser.Parse(f.IfacePath)
if err != nil {
return err
}
err = f.parser.Load()
if err != nil {
return err
}
ifacer, err := f.parser.Find(f.IfaceName)
if err != nil {
return err
}
f.PackageName = ifacer.Pkg.Name()
f.setNoConflictImport(ifacer.Pkg.Name(), ifacer.Pkg.Path())
f.ManageNoConflictImport(ifacer.Pkg.Imports())
f.GenMethods(ifacer.Type)
f.getUsingImportStr()
err = f.Process()
if err != nil {
return err
}
err = f.writer.Write(f.OutFile, f.Content)
if err != nil {
return err
}
return nil
}
func (f *Ifacer) bindInput(v *viper.Viper) error {
name := v.GetString("iname")
if name == "" {
return errors.New("iname is empty")
}
f.IfaceName = name
outPath := v.GetString("out")
if outPath == "" {
outPath = "./dummy_" + strings.ToLower(f.IfaceName) + ".go"
}
f.OutFile = outPath
structName := v.GetString("stname")
if structName == "" {
structName = "Dummy" + f.IfaceName
}
f.StructName = structName
star := v.GetBool("star")
if star {
f.Star = "*"
}
f.IfacePath = v.GetString("ipath")
return nil
}
func (f *Ifacer) GenMethods(interacer *types.Interface) {
for i := 0; i < interacer.NumMethods(); i++ {
fn := interacer.Method(i)
ftype := fn.Type().(*types.Signature)
m := &Method{}
m.ReturnStr = "return "
m.FuncName = fn.Name()
f.getArgStr(ftype.Params(), m, ftype.Variadic())
f.getReturnStr(ftype.Results(), m)
f.Methods = append(f.Methods, *m)
}
}
func (f *Ifacer) getUsingImportStr() {
imps := pkg.Imports{}
for _, imp := range f.pkgNoConflictImport {
imps = append(imps, imp)
}
f.UsingImportStr = imps.String()
}
func (f *Ifacer) ManageNoConflictImport(imps []*types.Package) bool {
for _, imp := range imps {
f.setNoConflictImport(imp.Name(), imp.Path())
}
return true
}
func (f *Ifacer) setNoConflictImport(importName, importPath string) {
if impPath, ok := f.pkgNoConflictImport[importName]; ok {
if impPath.Path == importPath {
return
}
// package name repeat
level := 1
flag := true
for flag {
uniqueImportName := f.getUniqueImportName(importPath, level)
if _, ok := f.pkgNoConflictImport[uniqueImportName]; !ok {
imp := pkg.Import{}
imp.Name = uniqueImportName
imp.Path = importPath
f.pkgNoConflictImport[uniqueImportName] = imp
flag = false
}
level++
}
} else {
imp := pkg.Import{}
imp.Name = importName
imp.Path = importPath
f.pkgNoConflictImport[importName] = imp
}
}
// Example:
// github.com/jukylin/esim/redis
// level
// 0 redis
// 1 esimredis
// 2 jukylinesimredis
// 3 githubcomjukylinesimredis
func (f *Ifacer) getUniqueImportName(pkgName string, level int) string {
strs := strings.Split(pkgName, string(filepath.Separator))
lenStr := len(strs)
if lenStr-1 < level {
f.logger.Panicf("%d out of range", level)
}
var importName string
for _, str := range strs[lenStr-level-1:] {
if strings.Contains(str, ".") {
str = strings.Replace(str, ".", "", -1)
}
importName += str
}
return importName
}
func (f *Ifacer) getArgStr(tuple *types.Tuple, m *Method, variadic bool) {
for i := 0; i < tuple.Len(); i++ {
ArgVar := tuple.At(i)
if ArgVar.Name() != "" {
m.ArgStr += ArgVar.Name() + " "
} else {
m.ArgStr += "arg" + strconv.Itoa(i) + " "
}
if i == tuple.Len()-1 {
m.ArgStr += f.parseVar(ArgVar, variadic)
} else {
m.ArgStr += f.parseVar(ArgVar, false)
}
if i < tuple.Len()-1 {
m.ArgStr += ", "
}
}
}
func (f *Ifacer) parseVar(varObj *types.Var, variadic bool) string {
return f.parseVarType(varObj.Type(), variadic)
}
func (f *Ifacer) parseVarType(typ types.Type, variadic bool) string {
var varType string
switch t := typ.(type) {
case *types.Named:
if t.Obj().Pkg() != nil {
if t.Obj().Pkg().Name() != f.PackageName {
varType += t.Obj().Pkg().Name() + "."
f.ifaceUsingIngImport[t.Obj().Pkg().Name()] = t.Obj().Pkg().Path()
}
}
varType += t.Obj().Name()
case *types.Pointer:
varType = "*"
varType += f.parseVarType(t.Elem(), false)
case *types.Slice:
if variadic {
varType = "..."
} else {
varType = "[]"
}
varType += f.parseVarType(t.Elem(), false)
case *types.Array:
varType = fmt.Sprintf("[%d]", t.Len())
varType += f.parseVarType(t.Elem(), false)
case *types.Chan:
switch t.Dir() {
case types.SendRecv:
varType += "chan "
case types.RecvOnly:
varType += "<-chan "
default:
varType += "chan<- "
}
varType += f.parseVarType(t.Elem(), false)
case *types.Map:
key := f.parseVarType(t.Key(), false)
val := f.parseVarType(t.Elem(), false)
varType = fmt.Sprintf("map[%s]%s", key, val)
case *types.Signature:
varType = fmt.Sprintf(
"func (%s) (%s)",
f.parseTypeTuple(t.Params()),
f.parseTypeTuple(t.Results()),
)
default:
varType = t.String()
}
return varType
}
func (f *Ifacer) parseTypeTuple(tup *types.Tuple) string {
var parts []string
for i := 0; i < tup.Len(); i++ {
v := tup.At(i)
parts = append(parts, f.parseVar(v, false))
}
return strings.Join(parts, " , ")
}
func (f *Ifacer) getReturnStr(tuple *types.Tuple, m *Method) {
if tuple.Len() > 0 {
m.ReturnTypeStr += "("
for i := 0; i < tuple.Len(); i++ {
ArgVar := tuple.At(i)
m.ReturnTypeStr += ArgVar.Name() + " " + f.parseVar(ArgVar, false)
var returnVarName string
if ArgVar.Name() == "" {
returnVarName = "r" + strconv.Itoa(i)
m.InitReturnVarStr += " var " + returnVarName + " "
m.InitReturnVarStr += f.parseVar(ArgVar, false) + " \r\n"
}
m.ReturnStr += returnVarName + ","
m.ReturnTypeStr += ","
}
m.ReturnTypeStr = strings.Trim(m.ReturnTypeStr, ",")
m.ReturnTypeStr += ")"
m.ReturnStr = strings.Trim(m.ReturnStr, ",")
}
}
// Process parsed template and formats and adjusts imports for the parsed content.
func (f *Ifacer) Process() error {
content, err := f.tpl.Execute("ifacer", ifacerTemplate, f)
if err != nil {
return err
}
src, err := imports.Process("", []byte(content), nil)
if err != nil {
return err
}
f.Content = string(src)
return nil
}