-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.go
93 lines (79 loc) · 1.84 KB
/
codegen.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
package main
import (
"bytes"
"fmt"
"go/format"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/serenize/snaker"
)
const codeTemplate = `// Code generated by github.com/go-joe/gen-reactions DO NOT EDIT.
// Package reactions contains a list of generated reactions that are widely used
// in different chat applications on the internet.
package reactions
// A Reaction is an emoji that is attached to chat messages.
type Reaction struct {
Raw string
Shortcode string
}
{{ range .Groups }}
// {{ .Name }} emojis.
var (
{{- range .Emojis }}
{{ camel_case .Name }} = Reaction{Raw: "{{ .Code }}", Shortcode: "{{ .Name }}"}
{{- end }}
)
{{ end }}
// String returns the UTF string value of the Reaction (e.g. 👍).
func (r Reaction) String() string {
if r.Raw != "" {
return r.Raw
}
return r.Shortcode
}
`
func generateCode(emojis []*EmojiGroup) error {
replacer := strings.NewReplacer(
"+", "Plus",
"-", "Minus",
"0", "Zero",
"1", "One",
"2", "Two",
"3", "Three",
"4", "Four",
"5", "Five",
"6", "Six",
"7", "Seven",
"8", "Eight",
"9", "Nine",
)
tmpl := template.New("reactions.go")
tmpl.Funcs(template.FuncMap{
"camel_case": func(name string) string {
name = replacer.Replace(name)
return snaker.SnakeToCamel(name)
},
})
tmpl, err := tmpl.Parse(codeTemplate)
if err != nil {
return errors.Wrap(err, "failed to parse template")
}
type vars struct {
Groups []*EmojiGroup
}
generated := new(bytes.Buffer)
err = tmpl.Execute(generated, vars{Groups: emojis})
if err != nil {
return errors.Wrap(err, "failed to execute template")
}
formatted, err := format.Source(generated.Bytes())
if err != nil {
return errors.Wrap(err, "failed to format generated code")
}
_, err = fmt.Println(string(formatted))
if err != nil {
return errors.Wrap(err, "failed to print output")
}
return nil
}