-
Notifications
You must be signed in to change notification settings - Fork 10
/
generator.go
187 lines (166 loc) · 4.7 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package bel
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
"text/template"
"time"
)
const interfaceTemplate = `
{{ define "comment" -}}
{{- if .Comment }}
/**
* {{ .Comment }}
*/
{{ end -}}
{{ end -}}
{{ define "iface" -}}
{
{{ range .Members -}}
{{- template "comment" . -}}
{{ .Name }}{{ if .IsOptional }}?{{ end }}{{ if .IsFunction }}({{ template "args" . }}){{ end }}: {{ subt .Type | default "void" }}
{{ end }}
}
{{ end -}}
{{- define "args" }}{{ range $idx, $val := .Args }}{{ if eq $idx 0 }}{{ else }}, {{ end }}{{ .Name }}: {{ subt .Type }}{{ end }}{{ end -}}
{{- define "simple" }}{{ .Name }}{{ end -}}
{{- define "map" }}{ [key: {{ subt (mapKeyType .) }}]: {{ subt (mapValType .) }} }{{ end -}}
{{- define "array" }}{{ subt (arrType .) }}[]{{ end -}}
{{- define "root-enum" }}{{- template "comment" . -}}export enum {{ .Name }} {
{{ range .EnumMembers }}{{ .Name }} = {{ .Value }},
{{ end }}
}{{ end -}}
{{- define "root-st-enum" }}{{- template "comment" . -}}export type {{ .Name }} =
{{ range $idx, $val := .EnumMembers }}{{ if eq $idx 0 }}{{ else }} | {{ end }}{{ .Value }}{{ end }};
{{ end -}}
{{- define "root-iface" }}{{- template "comment" . -}}export interface {{ .Name }} {{ template "iface" . }} {{ end -}}
{{- .Preamble }}
{{ if .Namespace }}export namespace {{ .Namespace }} {
{{ end -}}
{{- range .Types }}
{{ subtroot . }}
{{ end -}}
{{ if .Namespace }} } {{ end }}
`
type generateOptions struct {
enumsAsSumTypes bool
out io.Writer
Namespace string
Types []TypescriptType
Preamble string
}
// GenerateOption is an option used with the Generate function
type GenerateOption func(*generateOptions)
// GenerateEnumAsSumType causes enums to be be rendered as sum types
func GenerateEnumAsSumType(opt *generateOptions) {
opt.enumsAsSumTypes = true
}
// GenerateOutputTo sets the writer to which we'll write the generated TS code
func GenerateOutputTo(out io.Writer) GenerateOption {
return func(opt *generateOptions) {
opt.out = out
}
}
// GenerateNamespace produces a namespace in which the generated types live
func GenerateNamespace(ns string) GenerateOption {
return func(opt *generateOptions) {
opt.Namespace = ns
}
}
// GenerateAdditionalPreamble produces additional output at the beginning of the Typescript code
func GenerateAdditionalPreamble(preamble string) GenerateOption {
return func(opt *generateOptions) {
opt.Preamble += preamble
}
}
// GeneratePreamble produces output at the beginning of the Typescript code
func GeneratePreamble(preamble string) GenerateOption {
return func(opt *generateOptions) {
opt.Preamble = preamble
}
}
// Render produces TypeScript code
func Render(types []TypescriptType, cfg ...GenerateOption) error {
opts := generateOptions{
out: os.Stdout,
Preamble: fmt.Sprintf("// generated using github.com/32leaves/bel on %s\n// DO NOT MODIFY\n", time.Now()),
}
for _, c := range cfg {
c(&opts)
}
getParam := func(nme string, idx, minlen int) func(t TypescriptType) (*TypescriptType, error) {
return func(t TypescriptType) (*TypescriptType, error) {
if len(t.Params) != minlen {
return nil, fmt.Errorf("map needs %d type params", minlen)
}
return &t.Params[idx], nil
}
}
var tpl *template.Template
executeTpl := func(selector func(t TypescriptType) string) func(t TypescriptType) (string, error) {
if selector == nil {
selector = func(t TypescriptType) string {
return string(t.Kind)
}
}
return func(t TypescriptType) (string, error) {
name := selector(t)
if name == "" {
return "", nil
}
var b bytes.Buffer
if err := tpl.ExecuteTemplate(&b, name, t); err != nil {
return "", err
}
return b.String(), nil
}
}
funcs := template.FuncMap{
"mapKeyType": getParam("map", 0, 2),
"mapValType": getParam("map", 1, 2),
"arrType": getParam("array", 0, 1),
"subt": executeTpl(nil),
"subtroot": executeTpl(func(t TypescriptType) string {
if t.Kind == TypescriptEnumKind && opts.enumsAsSumTypes {
return "root-st-" + string(t.Kind)
}
return "root-" + string(t.Kind)
}),
"default": func(def, val string) string {
if val == "" {
return def
}
return val
},
}
var err error
tpl, err = template.New("interface").Funcs(funcs).Parse(interfaceTemplate)
if err != nil {
return err
}
opts.Types = types
r, w := io.Pipe()
scanner := bufio.NewScanner(r)
go func() {
emptylines := 0
for scanner.Scan() {
line := scanner.Text()
trimline := strings.TrimSpace(line)
if trimline != "" {
if emptylines > 1 {
fmt.Fprintln(opts.out)
}
fmt.Fprintln(opts.out, line)
}
if trimline == "" {
emptylines++
} else {
emptylines = 0
}
}
}()
return tpl.Execute(w, opts)
}