-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathenum.go.tmpl
60 lines (50 loc) · 1.09 KB
/
enum.go.tmpl
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
{{- define "enum" -}}
{{- $name := .Name -}}
{{- $type := .Type -}}
{{- $fields := .Fields -}}
{{- $opts := .Opts -}}
{{- if $opts.types -}}
type {{$name}} {{$type}}
{{- end }}
const (
{{- range $_, $field := $fields }}
{{- if gt (len $field.Comments) 0 -}}
{{- range $_, $comment := $field.Comments }}
// {{ replaceAll $comment "\"" "'" }}
{{- end }}
{{- end }}
{{$name}}_{{.Name}} {{$name}} = {{$field.Value}}
{{- end}}
)
var {{$name}}_name = map[{{$type}}]string{
{{- range $fields}}
{{.Value}}: "{{.Name}}",
{{- end}}
}
var {{$name}}_value = map[string]{{$type}}{
{{- range $fields}}
"{{.Name}}": {{.Value}},
{{- end}}
}
func (x {{$name}}) String() string {
return {{$name}}_name[{{$type}}(x)]
}
func (x {{$name}}) MarshalText() ([]byte, error) {
return []byte({{$name}}_name[{{$type}}(x)]), nil
}
func (x *{{$name}}) UnmarshalText(b []byte) error {
*x = {{$name}}({{$name}}_value[string(b)])
return nil
}
func (x *{{$name}}) Is(values ...{{$name}}) bool {
if x == nil {
return false
}
for _, v := range values {
if *x == v {
return true
}
}
return false
}
{{- end -}}