forked from a-h/generate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
291 lines (257 loc) · 7.08 KB
/
output.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package generate
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
)
func getOrderedFieldNames(m map[string]Field) []string {
keys := make([]string, len(m))
idx := 0
for k := range m {
keys[idx] = k
idx++
}
sort.Strings(keys)
return keys
}
func getOrderedStructNames(m map[string]Struct) []string {
keys := make([]string, len(m))
idx := 0
for k := range m {
keys[idx] = k
idx++
}
sort.Strings(keys)
return keys
}
// Output generates code and writes to w.
func Output(w io.Writer, g *Generator, pkg string) {
structs := g.Structs
aliases := g.Aliases
fmt.Fprintln(w)
fmt.Fprintf(w, "package %v\n", cleanPackageName(pkg))
// write all the code into a buffer, compiler functions will return list of imports
// write list of imports into main output stream, followed by the code
codeBuf := new(bytes.Buffer)
imports := make(map[string]bool)
for _, k := range getOrderedStructNames(structs) {
s := structs[k]
if s.GenerateCode {
emitMarshalCode(codeBuf, s, imports)
emitUnmarshalCode(codeBuf, s, imports)
}
}
if len(imports) > 0 {
fmt.Fprintf(w, "\nimport (\n")
for k := range imports {
fmt.Fprintf(w, " \"%s\"\n", k)
}
fmt.Fprintf(w, ")\n")
}
for _, k := range getOrderedFieldNames(aliases) {
a := aliases[k]
fmt.Fprintln(w, "")
fmt.Fprintf(w, "type %s %s\n", a.Name, a.Type)
}
for _, k := range getOrderedStructNames(structs) {
s := structs[k]
fmt.Fprintln(w, "")
fmt.Fprintf(w, "type %s struct {\n", s.Name)
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
// Only apply omitempty if the field is not required.
omitempty := ",omitempty"
if f.Required {
omitempty = ""
}
if f.Description != "" {
outputFieldDescriptionComment(f.Description, w)
}
fmt.Fprintf(w, " %s %s `json:\"%s%s\"`\n", f.Name, f.Type, f.JSONName, omitempty)
}
fmt.Fprintln(w, "}")
}
// write code after structs for clarity
w.Write(codeBuf.Bytes())
}
func emitMarshalCode(w io.Writer, s Struct, imports map[string]bool) {
imports["bytes"] = true
fmt.Fprintf(w,
`
func (strct *%s) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0))
buf.WriteString("{")
`, s.Name)
if len(s.Fields) > 0 {
fmt.Fprintf(w, " comma := false\n")
// Marshal all the defined fields
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.JSONName == "-" {
continue
}
if f.Required {
fmt.Fprintf(w, " // \"%s\" field is required\n", f.Name)
// currently only objects are supported
if strings.HasPrefix(f.Type, "*") {
imports["errors"] = true
fmt.Fprintf(w, ` if strct.%s == nil {
return nil, errors.New("%s is a required field")
}
`, f.Name, f.JSONName)
} else {
fmt.Fprintf(w, " // only required object types supported for marshal checking (for now)\n")
}
}
fmt.Fprintf(w,
` // Marshal the "%[1]s" field
if comma {
buf.WriteString(",")
}
buf.WriteString("\"%[1]s\": ")
if tmp, err := json.Marshal(strct.%[2]s); err != nil {
return nil, err
} else {
buf.Write(tmp)
}
comma = true
`, f.JSONName, f.Name)
}
}
if s.AdditionalType != "" {
if s.AdditionalType != "false" {
imports["fmt"] = true
if len(s.Fields) == 0 {
fmt.Fprintf(w, " comma := false\n")
}
fmt.Fprintf(w, " // Marshal any additional Properties\n")
// Marshal any additional Properties
fmt.Fprintf(w, ` for k, v := range strct.AdditionalProperties {
if comma {
buf.WriteString(",")
}
buf.WriteString(fmt.Sprintf("\"%%s\":", k))
if tmp, err := json.Marshal(v); err != nil {
return nil, err
} else {
buf.Write(tmp)
}
comma = true
}
`)
}
}
fmt.Fprintf(w, `
buf.WriteString("}")
rv := buf.Bytes()
return rv, nil
}
`)
}
func emitUnmarshalCode(w io.Writer, s Struct, imports map[string]bool) {
imports["encoding/json"] = true
// unmarshal code
fmt.Fprintf(w, `
func (strct *%s) UnmarshalJSON(b []byte) error {
`, s.Name)
// setup required bools
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.Required {
fmt.Fprintf(w, " %sReceived := false\n", f.JSONName)
}
}
// setup initial unmarshal
fmt.Fprintf(w, ` var jsonMap map[string]json.RawMessage
if err := json.Unmarshal(b, &jsonMap); err != nil {
return err
}`)
// figure out if we need the "v" output of the range keyword
needVal := "_"
if len(s.Fields) > 0 || s.AdditionalType != "false" {
needVal = "v"
}
// start the loop
fmt.Fprintf(w, `
// parse all the defined properties
for k, %s := range jsonMap {
switch k {
`, needVal)
// handle defined properties
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.JSONName == "-" {
continue
}
fmt.Fprintf(w, ` case "%s":
if err := json.Unmarshal([]byte(v), &strct.%s); err != nil {
return err
}
`, f.JSONName, f.Name)
if f.Required {
fmt.Fprintf(w, " %sReceived = true\n", f.JSONName)
}
}
// handle additional property
if s.AdditionalType != "" {
if s.AdditionalType == "false" {
// all unknown properties are not allowed
imports["fmt"] = true
fmt.Fprintf(w, ` default:
return fmt.Errorf("additional property not allowed: \"" + k + "\"")
`)
} else {
fmt.Fprintf(w, ` default:
// an additional "%s" value
var additionalValue %s
if err := json.Unmarshal([]byte(v), &additionalValue); err != nil {
return err // invalid additionalProperty
}
if strct.AdditionalProperties == nil {
strct.AdditionalProperties = make(map[string]%s, 0)
}
strct.AdditionalProperties[k]= additionalValue
`, s.AdditionalType, s.AdditionalType, s.AdditionalType)
}
}
fmt.Fprintf(w, " }\n") // switch
fmt.Fprintf(w, " }\n") // for
// check all Required fields were received
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.Required {
imports["errors"] = true
fmt.Fprintf(w, ` // check if %s (a required property) was received
if !%sReceived {
return errors.New("\"%s\" is required but was not present")
}
`, f.JSONName, f.JSONName, f.JSONName)
}
}
fmt.Fprintf(w, " return nil\n")
fmt.Fprintf(w, "}\n") // UnmarshalJSON
}
func outputNameAndDescriptionComment(name, description string, w io.Writer) {
if strings.Index(description, "\n") == -1 {
fmt.Fprintf(w, "// %s %s\n", name, description)
return
}
dl := strings.Split(description, "\n")
fmt.Fprintf(w, "// %s %s\n", name, strings.Join(dl, "\n// "))
}
func outputFieldDescriptionComment(description string, w io.Writer) {
if strings.Index(description, "\n") == -1 {
fmt.Fprintf(w, "\n // %s\n", description)
return
}
dl := strings.Split(description, "\n")
fmt.Fprintf(w, "\n // %s\n", strings.Join(dl, "\n // "))
}
func cleanPackageName(pkg string) string {
pkg = strings.Replace(pkg, ".", "", -1)
pkg = strings.Replace(pkg, "_", "", -1)
pkg = strings.Replace(pkg, "-", "", -1)
return pkg
}