-
Notifications
You must be signed in to change notification settings - Fork 0
/
gentmpl.go
72 lines (59 loc) · 1.6 KB
/
gentmpl.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
package gen
import (
"strings"
"github.com/clipperhouse/typewriter"
)
var templates = typewriter.TemplateSlice{
wrapper,
register,
}
// this is the template for generating the go-data wrappers of an interface
var wrapper = &typewriter.Template{
Name: "Wrapper",
TypeConstraint: typewriter.Constraint{},
FuncMap: fmap,
Text: `
type {{.Wrapper}} struct {
{{.Inner}} "json:\"unwrap\""
}
var {{.Wrapper}}Mapper = data.NewMapper({{.Wrapper}}{})
func (h {{.Wrapper}}) MarshalJSON() ([]byte, error) {
return {{.Wrapper}}Mapper.ToJSON(h.{{.Inner}})
}
func (h *{{.Wrapper}}) UnmarshalJSON(data []byte) (err error) {
parsed, err := {{.Wrapper}}Mapper.FromJSON(data)
if err == nil && parsed != nil {
h.{{.Inner}} = parsed.({{.Inner}})
}
return err
}
// Unwrap recovers the concrete interface safely (regardless of levels of embeds)
func (h {{.Wrapper}}) Unwrap() {{.Inner}} {
hi := h.{{.Inner}}
for wrap, ok := hi.({{.Wrapper}}); ok; wrap, ok = hi.({{.Wrapper}}) {
hi = wrap.{{.Inner}}
}
return hi
}
func (h {{.Wrapper}}) Empty() bool {
return h.{{.Inner}} == nil
}
/*** below are bindings for each implementation ***/
`,
}
var register = &typewriter.Template{
Name: "Register",
TypeConstraint: typewriter.Constraint{},
FuncMap: fmap,
Text: `
func init() {
{{.Wrapper}}Mapper.RegisterImplementation({{ if .Impl.Pointer }}&{{ end }}{{.Impl.Name}}{}, "{{.ImplType }}", 0x{{.Count}})
}
func (hi {{ if .Impl.Pointer }}*{{ end }}{{.Impl.Name}}) Wrap() {{.Wrapper}} {
return {{.Wrapper}}{hi}
}
`,
}
var fmap = map[string]interface{}{
"ToLower": strings.ToLower,
}