-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
90 lines (83 loc) · 2.2 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
package main
import (
"fmt"
"io"
"strings"
"text/template"
)
//go:generate go-bindata ./templates/
func newTemplateWithFuncMaps(funcMaps template.FuncMap) *template.Template {
tpl := template.New("file").Funcs(funcMaps)
filenames := []string{
"templates/file.tgo",
"templates/publisher.tgo",
"templates/subscriber.tgo",
}
for _, filename := range filenames {
tpl = template.Must(tpl.Parse(string(MustAsset(filename))))
}
return tpl
}
func generate(w io.Writer, pkg string, typ string, buildTags string, args []string) error {
eventNames, argTypesMap, err := parseArgs(args)
if err != nil {
return err
}
tpl := newTemplateWithFuncMaps(template.FuncMap{
"printArgTypesOf": func(eventName string) string {
argTypes, ok := argTypesMap[eventName]
if !ok {
return ""
}
items := []string{}
for _, v := range argTypes {
items = append(items, fmt.Sprintf("%s %s", v.Name, v.TypeName))
}
return strings.Join(items, ", ")
},
"printArgsOf": func(eventName string) string {
argTypes, ok := argTypesMap[eventName]
if !ok {
return ""
}
items := []string{}
for _, v := range argTypes {
items = append(items, v.Name)
}
return strings.Join(items, ", ")
},
})
return tpl.Execute(w, map[string]interface{}{
"PackageName": pkg,
"PublisherTypeName": typ,
"EventNames": eventNames,
"BuildTags": buildTags,
})
}
type argType struct {
Name string
TypeName string
}
func parseArgs(args []string) (eventNames []string, argTypesMap map[string][]*argType, err error) {
eventNames = []string{}
argTypesMap = make(map[string][]*argType)
for _, arg := range args {
// Hoge|a:string,b:interface{}
if strings.ContainsRune(arg, '|') {
specs := strings.SplitN(arg, "|", 2)
eventName := strings.TrimSpace(specs[0])
eventNames = append(eventNames, eventName)
argsSpecs := strings.Split(specs[1], ",")
for _, argSpec := range argsSpecs {
nameAndType := strings.SplitN(argSpec, ":", 2)
argTypesMap[eventName] = append(argTypesMap[eventName], &argType{
Name: strings.TrimSpace(nameAndType[0]),
TypeName: strings.TrimSpace(nameAndType[1]),
})
}
} else {
eventNames = append(eventNames, arg)
}
}
return
}