-
Notifications
You must be signed in to change notification settings - Fork 1
/
render.go
335 lines (290 loc) · 9.25 KB
/
render.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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os/exec"
"regexp"
"strings"
"text/template"
"unicode"
"unicode/utf8"
)
func Render(writer io.Writer, packageName string, renderMethod func(io.Writer, *WadlMethod) error, methods ...*WadlMethod) error {
fmt.Fprintf(writer, "package %s", packageName)
// We need a function to make request.
fmt.Fprintln(writer, "\n\ntype RequestHandlerFn func(*http.Request) (*http.Response, error)")
for _, method := range methods {
if err := renderMethod(writer, method); err != nil {
return err
}
}
return nil
}
func RenderMethodWithBulkTypes(writer io.Writer, method *WadlMethod) error {
const funBodyTmpl = `
{{if .Documentation}}{{renderDocumentation .Documentation}}{{end}}
func {{.FunName}}(request RequestHandlerFn, args {{.ArgType}}) ({{if .ResponseType}}*{{.ResponseType}},{{end}} error) {
argsAsJson, err := json.Marshal(args)
if err != nil {
return nil, err
}
url := "{{.Url}}"
{{.ReplaceTemplateVarsCode}}
var req *http.Request
if string(argsAsJson) != "{}" {
req, err = http.NewRequest("{{.MethodType}}", url, bytes.NewBuffer(argsAsJson))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
} else {
req, err = http.NewRequest("{{.MethodType}}", url, nil)
if err != nil {
return nil, err
}
}
{{if .ReplaceQueryVarsCode}}
query := req.URL.Query()
{{.ReplaceQueryVarsCode}}
req.URL.RawQuery = query.Encode()
{{end}}
resp, err := request(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
{{if .AcceptableStatusCodesCsv}}
switch resp.StatusCode {
default:
return nil, fmt.Errorf("invalid status (%d): %s", resp.StatusCode, body)
case {{.AcceptableStatusCodesCsv}}:
break;
}
{{end}}
var results {{.ResponseType}}
json.Unmarshal(body, &results)
{{/* TODO(katco-): Don't ignore error here; look at num of items in response collection */}}
return &results, nil
}`
methName := renderIdentifiers(method.Name, false)
debug.Printf("methName: %s\n", methName)
RenderParameterType(writer, methName, method.Arguments)
returnStruct := exampleToStruct(method.ResultsExample, renderMethodResultsName(methName))
if returnStruct != "" {
fmt.Fprintf(writer, "\n\n%s\n", returnStruct)
} else {
// We Always want to return something.
RenderResultsType(writer, methName, method.Results)
}
const templateVarReplaceTmpl = `
url = strings.Replace(url, "%7B<!.Name!>%7D", args.<!renderIdentifiers .Name true!>, -1)`
const queryVarReplaceTmpl = `
query.Add("{{.Name}}", fmt.Sprintf("%v", args.{{renderIdentifiers .Name true}}))`
var replaceTemplateVarsCode bytes.Buffer
var replaceQueryVarsCode bytes.Buffer
var bodyParams []*WadlVariable
for _, param := range method.Arguments {
debug.Printf("param type: %s", param.RequestType)
switch param.RequestType {
case "template":
var codeSnippet bytes.Buffer
if err := template.Must(template.New("").Funcs(template.FuncMap{
"renderIdentifiers": renderIdentifiers,
}).Delims("<!", "!>").Parse(templateVarReplaceTmpl)).Execute(&codeSnippet, param); err != nil {
panic(err)
}
if _, err := replaceTemplateVarsCode.Write(codeSnippet.Bytes()); err != nil {
panic(err)
}
case "query":
var codeSnippet bytes.Buffer
if err := template.Must(template.New("").Funcs(template.FuncMap{
"renderIdentifiers": renderIdentifiers,
}).Parse(queryVarReplaceTmpl)).Execute(&codeSnippet, param); err != nil {
panic(err)
}
if _, err := replaceQueryVarsCode.Write(codeSnippet.Bytes()); err != nil {
panic(err)
}
case "plain":
bodyParams = append(bodyParams, param)
}
}
var funBody bytes.Buffer
if err := template.Must(template.New("").Funcs(template.FuncMap{
"renderDocumentation": renderDocumentation,
}).Parse(funBodyTmpl)).Execute(&funBody, &struct {
Documentation string
FunName string
ArgType string
ResponseType string
MethodType string
Url string
ReplaceTemplateVarsCode string
ReplaceQueryVarsCode string
AcceptableStatusCodesCsv string
}{
method.Documentation,
methName,
renderMethodParamName(methName),
renderMethodResultsName(methName),
method.Type,
method.Url,
replaceTemplateVarsCode.String(),
replaceQueryVarsCode.String(),
strings.Join(method.AcceptableStatus, ","),
}); err != nil {
panic(err)
}
fmt.Fprint(writer, funBody.String())
return nil
}
func exampleToStruct(example string, typeName string) string {
cmd := exec.Command("gojson", "-name", typeName)
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
if err := cmd.Start(); err != nil {
panic(err)
}
if _, err := stdin.Write([]byte(example)); err != nil {
panic(err.Error())
}
stdin.Close()
stdoutReader := bufio.NewReader(stdout)
stdoutReader.ReadLine()
stdoutReader.ReadLine()
output, err := ioutil.ReadAll(stdoutReader)
if err != nil {
panic(err)
}
cmd.Wait()
return string(output)
}
func RenderParameterType(writer io.Writer, methName string, params []*WadlVariable) {
renderVariableCollection(writer, methName, params, renderMethodParamName)
}
func RenderResultsType(writer io.Writer, methName string, params []*WadlVariable) {
renderVariableCollection(writer, methName, params, renderMethodResultsName)
}
func renderDocumentation(doc string) string {
var docBlock bytes.Buffer
r := bufio.NewReader(strings.NewReader(doc))
for lineLen := 0; ; {
lineBytes, _, err := r.ReadLine()
if err != nil {
if err == io.EOF {
break
}
log.Fatalf("error reading documentation: %s", err)
}
lineLen += len(lineBytes)
fmt.Fprintf(&docBlock, " %s", strings.TrimSpace(string(lineBytes)))
}
// Start scrubbing.
line := string(docBlock.String())
line = regexp.MustCompile("<para[^>]*>").ReplaceAllString(line, "\n// ")
line = regexp.MustCompile("</para>").ReplaceAllString(line, "")
line = regexp.MustCompile("<code[^>]*>").ReplaceAllString(line, "")
line = regexp.MustCompile("</code>").ReplaceAllString(line, "")
line = regexp.MustCompile("<itemizedlist[^>]*>").ReplaceAllString(line, "\n// ")
line = regexp.MustCompile("</itemizedlist>").ReplaceAllString(line, ":")
line = regexp.MustCompile("<listitem[^>]*>").ReplaceAllString(line, "")
line = regexp.MustCompile("</listitem>").ReplaceAllString(line, "")
line = regexp.MustCompile("//\\s*$").ReplaceAllString(line, "")
debug.Printf("New doc:\n%s", line) //docBlock.String())
return "// " + line //docBlock.String()
}
func renderVariableCollection(writer io.Writer, methName string, params []*WadlVariable, renderCollectionName func(string) string) {
const collectionType = `
type {{.CollectionName}} struct {
{{range .Variables}}
{{if .Required}}// {{renderIdentifiers .Name true}} is required.{{end}}
{{if .Documentation}}{{renderDocumentation .Documentation}}{{end}}
{{renderIdentifiers .Name true}} {{renderType .Type}} ` + "`json:\"{{if eq .RequestType \"plain\"}}{{.Name}}{{if not .Required}},omitempty{{end}}{{else}}-{{end}}\"`" + `
{{end}}
}`
// Create sub-types for variables with embedded objects.
for _, p := range params {
if len(p.EmbeddedVar) <= 0 {
continue
}
typeName := renderIdentifiers(methName+caseFirstChar(p.Name, true), true)
renderVariableCollection(writer, typeName, p.EmbeddedVar, renderCollectionName)
p.Type = renderCollectionName(typeName)
}
var typeBody bytes.Buffer
if err := template.Must(template.New("collection").Funcs(template.FuncMap{
"renderIdentifiers": renderIdentifiers,
"renderType": renderType,
"renderDocumentation": renderDocumentation,
}).Parse(collectionType)).Execute(&typeBody, struct {
CollectionName string
Variables []*WadlVariable
FormatName func(string, bool) string
}{
CollectionName: renderCollectionName(methName),
Variables: params,
FormatName: renderIdentifiers,
}); err != nil {
panic(err)
}
fmt.Fprintf(writer, typeBody.String())
}
func renderIdentifiers(name string, isPublic bool) string {
for _, camelCaseSentinel := range []string{"_", "-"} {
for {
sntlIdx := strings.Index(name, camelCaseSentinel)
if sntlIdx < 0 {
break
}
name = name[:sntlIdx] + caseFirstChar(name[sntlIdx+1:], true)
}
}
return caseFirstChar(name, isPublic)
}
func renderMethodParamName(methName string) string {
return renderIdentifiers(fmt.Sprintf("%sParams", methName), true)
}
func renderMethodResultsName(methName string) string {
return renderIdentifiers(fmt.Sprintf("%sResults", methName), true)
}
func renderType(wadlType string) string {
switch strings.ToLower(wadlType) {
default:
log.Printf("WARNING: unknown WADL type: %s", wadlType)
return wadlType
case "object", "xsd:dict":
// TODO(katco-): Correctly reference the auto-generated structure type.
return "interface{}"
case "xsd:datetime":
return "time.Time"
case "string", "xsd:string", "xsd:uuid", "csapi:uuid", "csapi:string":
return "string"
case "xsd:int", "integer":
return "int"
case "xsd:boolean", "boolean":
return "bool"
}
}
func caseFirstChar(str string, toUpper bool) string {
r, n := utf8.DecodeRuneInString(str)
if toUpper {
str = string(unicode.ToUpper(r)) + str[n:]
} else {
str = string(unicode.ToLower(r)) + str[n:]
}
return str
}