This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
forked from kazu/ifacemaker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathifacemaker.go
98 lines (85 loc) · 2.58 KB
/
ifacemaker.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
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/kazu/ifacemaker/maker"
"github.com/mkideal/cli"
)
type cmdlineArgs struct {
cli.Helper
Files []string `cli:"*f,file" usage:"Go source file to read"`
StructType string `cli:"*s,struct" usage:"Generate an interface for this structure name"`
IfaceName string `cli:"*i,iface" usage:"Name of the generated interface"`
PkgName string `cli:"*p,pkg" usage:"Package name for the generated interface"`
ExcludeMethods []string `cli:"e,exclude" usage:"Method name for not generation " `
CopyDocs bool `cli:"d,doc" usage:"Copy docs from methods" dft:"true"`
Output string `cli:"o,output" usage:"Output file name. If not provided, result will be printed to stdout."`
}
func run(args *cmdlineArgs) {
allMethods := []string{}
allImports := []string{}
mset := make(map[string]struct{})
iset := make(map[string]struct{})
parseds := make(map[string]*maker.StructData)
for _, f := range args.Files {
src, err := ioutil.ReadFile(f)
if err != nil {
log.Fatal(err.Error())
}
sparsed := maker.ParseStruct(src, args.CopyDocs, args.ExcludeMethods)
for s, parsed := range sparsed {
//parseds[s] = parsed
if parseds[s] != nil {
if parseds[s].Embedded != nil {
parseds[s].Embedded = append(parseds[s].Embedded, parsed.Embedded...)
}
parseds[s].Methods = append(parseds[s].Methods, parsed.Methods...)
parseds[s].Imports = append(parseds[s].Imports, parsed.Imports...)
} else {
parseds[s] = parsed
}
}
}
var methods []maker.Method
var imports []string
if parseds[args.StructType] != nil {
methods = append(methods, parseds[args.StructType].Methods...)
imports = parseds[args.StructType].Imports
if len(parseds[args.StructType].Embedded) > 0 {
for _, embed := range parseds[args.StructType].Embedded {
if parseds[embed] != nil {
methods = append(methods, parseds[embed].Methods...)
}
}
}
}
for _, m := range methods {
if _, ok := mset[m.Code]; !ok {
allMethods = append(allMethods, m.Lines()...)
mset[m.Code] = struct{}{}
}
}
for _, i := range imports {
if _, ok := iset[i]; !ok {
allImports = append(allImports, i)
iset[i] = struct{}{}
}
}
result, err := maker.MakeInterface(args.PkgName, args.IfaceName, allMethods, allImports)
if err != nil {
log.Fatal(err.Error())
}
if args.Output == "" {
fmt.Println(string(result))
} else {
ioutil.WriteFile(args.Output, result, 0644)
}
}
func main() {
cli.Run(&cmdlineArgs{}, func(ctx *cli.Context) error {
argv := ctx.Argv().(*cmdlineArgs)
run(argv)
return nil
})
}