-
Notifications
You must be signed in to change notification settings - Fork 14
/
generate-rest.go
350 lines (315 loc) · 8.85 KB
/
generate-rest.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"text/template"
"sort"
)
var schema struct {
Paths map[string]map[string]struct {
Summary string
OperationId string
Responses struct {
Ok struct {
Schema struct {
Ref string `json:"$ref"`
}
} `json:"200"`
}
Parameters []struct {
Name string
Description string
In string
Required bool
Type string // used with primitives
Items struct { // used with type "array"
Type string
}
Schema struct { // used with http body
Type string
Ref string `json:"$ref"`
}
Format string // used with type "boolean"
}
Security []map[string][]struct {
}
}
Definitions map[string]struct {
Properties map[string]struct {
Type string
Ref string `json:"$ref"` // used with object
Items struct { // used with type "array"
Type string
Ref string `json:"$ref"`
}
AdditionalProperties struct {
Type string // used with type "map"
}
Format string // used with type "boolean"
Description string
}
Enum []string
Description string
// used only by enums
Title string
}
}
func convertRefToClassName(input string) (className string) {
cleanRef := strings.TrimPrefix(input, "#/definitions/")
className = strings.Title(cleanRef)
return
}
func stripNewlines(input string) (output string) {
output = strings.Replace(input, "\n", "\n--", -1)
return
}
func pascalToSnake(input string) (output string) {
output = ""
prev_low := false
for _, v := range input {
is_cap := v >= 'A' && v <= 'Z'
is_low := v >= 'a' && v <= 'z'
if is_cap && prev_low {
output = output + "_"
}
output += strings.ToLower(string(v))
prev_low = is_low
}
return
}
// camelToPascal converts a string from camel case to Pascal case.
func camelToPascal(camelCase string) (pascalCase string) {
if len(camelCase) <= 0 {
return ""
}
pascalCase = strings.ToUpper(string(camelCase[0])) + camelCase[1:]
return
}
// pascalToCamel converts a Pascal case string to a camel case string.
func pascalToCamel(input string) (camelCase string) {
if input == "" {
return ""
}
camelCase = strings.ToLower(string(input[0]))
camelCase += string(input[1:])
return camelCase
}
func removePrefix(input string) (output string) {
output = strings.Replace(input, "nakama_", "", -1)
output = strings.Replace(output, "satori_", "", -1)
return
}
func isEnum(ref string) bool {
// swagger schema definition keys have inconsistent casing
var camelOk bool
var pascalOk bool
var enums []string
cleanedRef := convertRefToClassName(ref)
asCamel := pascalToCamel(cleanedRef)
if _, camelOk = schema.Definitions[asCamel]; camelOk {
enums = schema.Definitions[asCamel].Enum
}
asPascal := camelToPascal(cleanedRef)
if _, pascalOk = schema.Definitions[asPascal]; pascalOk {
enums = schema.Definitions[asPascal].Enum
}
if !pascalOk && !camelOk {
return false
}
return len(enums) > 0
}
// Parameter type to Lua type
func luaType(p_type string, p_ref string) (out string) {
if isEnum(p_ref) {
out = "string"
return
}
switch p_type {
case "integer": out = "number"
case "string": out = "string"
case "boolean": out = "boolean"
case "array": out = "table"
case "object": out = "table"
default: out = "table"
}
return
}
// Default value for Lua types
func luaDef(p_type string, p_ref string) (out string) {
switch(p_type) {
case "integer": out = "0"
case "string": out = "\"\""
case "boolean": out = "false"
case "array": out = "{}"
case "object": out = "{ _ = '' }"
default: out = "M.create_" + pascalToSnake(convertRefToClassName(p_ref)) + "()"
}
return
}
// Lua variable name from name, type and ref
func varName(p_name string, p_type string, p_ref string) (out string) {
p_name = strings.Replace(p_name, "@", "", -1)
switch(p_type) {
case "integer": out = p_name + "_int"
case "string": out = p_name + "_str"
case "boolean": out = p_name + "_bool"
case "array": out = p_name + "_arr"
case "object": out = p_name + "_obj"
default: out = p_name + "_" + pascalToSnake(convertRefToClassName(p_ref))
}
return
}
func varComment(p_name string, p_type string, p_ref string, p_item_type string) (out string) {
switch(p_type) {
case "integer": out = "number"
case "string": out = "string"
case "boolean": out = "boolean"
case "array": out = "table (" + luaType(p_item_type, p_ref) + ")"
case "object": out = "table (object)"
default: out = "table (" + pascalToSnake(convertRefToClassName(p_ref)) + ")"
}
return
}
func isAuthenticateMethod(input string) (output bool) {
output = strings.HasPrefix(input, "Nakama_Authenticate")
return
}
func main() {
// Argument flags
var output = flag.String("output", "", "The output for generated code.")
flag.Parse()
inputs := flag.Args()
if len(inputs) < 1 {
fmt.Printf("No input file found: %s\n\n", inputs)
fmt.Println("openapi-gen [flags] inputs...")
flag.PrintDefaults()
return
}
input := inputs[0]
content, err := ioutil.ReadFile(input)
if err != nil {
fmt.Printf("Unable to read file: %s\n", err)
return
}
if err := json.Unmarshal(content, &schema); err != nil {
fmt.Printf("Unable to decode input %s : %s\n", input, err)
return
}
// expand the body argument to individual function arguments
bodyFunctionArgs := func(ref string) (output string) {
ref = strings.Replace(ref, "#/definitions/", "", -1)
props := schema.Definitions[ref].Properties
keys := make([]string, 0, len(props))
for prop := range props {
keys = append(keys, prop)
}
sort.Strings(keys)
for _,key := range keys {
output = output + ", " + key
}
return
}
// expand the body argument to individual function argument docs
bodyFunctionArgsDocs := func(ref string) (output string) {
ref = strings.Replace(ref, "#/definitions/", "", -1)
output = "\n"
props := schema.Definitions[ref].Properties
keys := make([]string, 0, len(props))
for prop := range props {
keys = append(keys, prop)
}
sort.Strings(keys)
for _,key := range keys {
info := props[key]
output = output + "-- @param " + key + " (" + info.Type + ") " + stripNewlines(info.Description) + "\n"
}
return
}
// expand the body argument to individual asserts for the call args
bodyFunctionArgsAssert := func(ref string) (output string) {
ref = strings.Replace(ref, "#/definitions/", "", -1)
output = "\n"
props := schema.Definitions[ref].Properties
keys := make([]string, 0, len(props))
for prop := range props {
keys = append(keys, prop)
}
sort.Strings(keys)
for _,key := range keys {
info := props[key]
luaType := luaType(info.Type, info.Ref)
output = output + "\tassert(not " + key + " or type(" + key + ") == \"" + luaType + "\", \"Argument '" + key + "' must be 'nil' or of type '" + luaType + "'\")\n"
}
return
}
// expand the body argument to individual asserts for the message body table
bodyFunctionArgsTable := func(ref string) (output string) {
ref = strings.Replace(ref, "#/definitions/", "", -1)
output = "\n"
props := schema.Definitions[ref].Properties
keys := make([]string, 0, len(props))
for prop := range props {
keys = append(keys, prop)
}
sort.Strings(keys)
for _,key := range keys {
output = output + "\t" + key + " = " + key + ",\n"
}
return
}
fmap := template.FuncMap {
"cleanRef": convertRefToClassName,
"stripNewlines": stripNewlines,
"title": strings.Title,
"uppercase": strings.ToUpper,
"pascalToSnake": pascalToSnake,
"luaType": luaType,
"luaDef": luaDef,
"varName": varName,
"varComment": varComment,
"bodyFunctionArgsDocs": bodyFunctionArgsDocs,
"bodyFunctionArgs": bodyFunctionArgs,
"bodyFunctionArgsAssert": bodyFunctionArgsAssert,
"bodyFunctionArgsTable": bodyFunctionArgsTable,
"isEnum": isEnum,
"isAuthenticateMethod": isAuthenticateMethod,
"removePrefix": removePrefix,
}
MAIN_TEMPLATE := strings.Replace(MAIN_TEMPLATE, "%%COMMON_TEMPLATE%%", COMMON_TEMPLATE, 1)
tmpl, err := template.New(input).Funcs(fmap).Parse(MAIN_TEMPLATE)
if err != nil {
fmt.Printf("Template parse error: %s\n", err)
return
}
if len(*output) < 1 {
tmpl.Execute(os.Stdout, schema)
return
}
f, err := os.Create(*output)
if err != nil {
fmt.Printf("Unable to create file: %s\n", err)
return
}
defer f.Close()
writer := bufio.NewWriter(f)
tmpl.Execute(writer, schema)
writer.Flush()
}