-
Notifications
You must be signed in to change notification settings - Fork 42
/
writer.go
367 lines (322 loc) · 9.02 KB
/
writer.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package importer
import (
"bufio"
"fmt"
"io"
"net/url"
"regexp"
"sort"
"strings"
"github.com/go-openapi/swag"
"github.com/sirupsen/logrus"
)
type OutputData struct {
AppName string
Package string
SwaggerRoot string
Mode string
}
type SyslInfo struct {
OutputData
Title string
Description string
OtherFields []string // Ordered key, val pair
}
type MethodEndpoints struct {
Method string // one of GET, POST, PUT, OPTION, etc
Endpoints []Endpoint
}
type writer struct {
io.Writer
ind *IndentWriter
logger *logrus.Logger
DisableJSONTags bool
}
const CommentLineLength = 80
func newWriter(out io.Writer, logger *logrus.Logger) *writer {
return &writer{
Writer: out,
ind: NewIndentWriter(" ", out),
logger: logger,
}
}
func (w *writer) Write(info SyslInfo, types TypeList, endpoints ...MethodEndpoints) error {
if err := w.writeHeader(info); err != nil {
return err
}
for _, method := range endpoints {
for _, ep := range method.Endpoints {
w.writeEndpoint(method.Method, ep)
w.writeLines(BlankLine)
}
}
w.writeDefinitions(types)
return nil
}
func (w *writer) writeHeader(info SyslInfo) error {
w.mustWrite(`##########################################
## ##
## AUTOGENERATED CODE -- DO NOT EDIT! ##
## ##
##########################################
`)
title := info.Title
pkg := ""
if info.Package != "" {
pkg = fmt.Sprintf("[package=%s]", quote(info.Package))
}
w.writeLines(spaceSeparate(info.AppName, quote(title), pkg)+":", PushIndent)
for i := 0; i < len(info.OtherFields); i += 2 {
key := info.OtherFields[i]
val := info.OtherFields[i+1]
if val != "" {
w.writeLines(fmt.Sprintf("@%s = %s", key, quote(val)))
}
}
w.writeLines("@description =:", PushIndent)
desc := getDescription(info.Description)
w.writeLines(buildDescriptionLines("| ", desc, CommentLineLength-w.ind.CurrentIndentLen())...)
w.writeLines(PopIndent, BlankLine)
return nil
}
func buildDescriptionLines(prefix, description string, wrapAt int) []string {
var result []string
scanner := bufio.NewScanner(strings.NewReader(description))
for scanner.Scan() {
line := scanner.Text()
if len(prefix)+len(line) <= wrapAt {
result = append(result, prefix+line)
} else {
words := bufio.NewScanner(strings.NewReader(line))
words.Split(bufio.ScanWords)
temp := strings.Builder{}
temp.WriteString(prefix)
for words.Scan() {
w := words.Text()
if temp.Len()+len(w) > wrapAt {
result = append(result, strings.TrimSpace(temp.String()))
temp.Reset()
temp.WriteString(prefix)
}
temp.WriteString(w + " ")
}
result = append(result, strings.TrimSpace(temp.String()))
}
}
return result
}
func appendAttributesString(prefix string, attrs []string) string {
if len(attrs) == 0 {
return prefix
}
return prefix + " [" + strings.Join(attrs, ", ") + "]"
}
func appendSizeSpec(prefix string, spec *sizeSpec) string {
if spec == nil {
return prefix
}
switch spec.MaxType {
case MaxSpecified:
return fmt.Sprintf("%s(%d..%d)", prefix, spec.Min, spec.Max)
case OpenEnded:
return fmt.Sprintf("%s(%d..)", prefix, spec.Min)
case MinOnly:
return fmt.Sprintf("%s(%d)", prefix, spec.Min)
}
return prefix
}
func buildQueryString(params []Param) string {
query := ""
if len(params) > 0 {
var parts []string
for _, p := range params {
optional := ""
if p.Optional {
optional = "?"
}
typeString := getSyslTypeName(p.Type)
if !IsBuiltIn(typeString) {
typeString = "{" + typeString + "}"
}
parts = append(parts, fmt.Sprintf("%s=%s%s", url.QueryEscape(p.Name), typeString, optional))
}
query = " ?" + strings.Join(parts, "&")
}
return query
}
func buildRequestBodyString(params []Param) string {
body := ""
if len(params) > 0 {
sort.SliceStable(params, func(i, j int) bool {
return strings.Compare(params[i].Name, params[j].Name) < 0
})
var parts []string
for _, p := range params {
attrs := appendAttributesString("", append(p.Field.Attributes, "~body"))
parts = append(parts, fmt.Sprintf("%s <: %s%s", p.Name, getSyslTypeName(p.Type), attrs))
}
body = strings.Join(parts, ", ")
}
return body
}
func buildRequestHeadersString(params []Param) string {
headers := ""
if len(params) > 0 {
var parts []string
for _, p := range params {
optional := map[bool]string{true: "~optional", false: "~required"}[p.Optional]
safeName := regexp.MustCompile("( |-)+").ReplaceAll([]byte(p.Name), []byte("_"))
text := fmt.Sprintf("%s <: %s", strings.ToLower(string(safeName)),
appendAttributesString(getSyslTypeName(p.Type), []string{"~header", optional, "name=" + quote(p.Name)}))
parts = append(parts, text)
}
headers = strings.Join(parts, ", ")
}
return headers
}
func buildPathString(path string, params []Param) string {
result := path
for _, p := range params {
replacement := fmt.Sprintf("{%s<:%s}", p.Name, getSyslTypeName(p.Type))
result = strings.ReplaceAll(result, fmt.Sprintf("{%s}", p.Name), replacement)
}
return result
}
func (w *writer) writeEndpoint(method string, endpoint Endpoint) {
header := buildRequestHeadersString(endpoint.Params.HeaderParams())
body := buildRequestBodyString(endpoint.Params.BodyParams())
reqStr := ""
if len(header) > 0 && len(body) > 0 {
reqStr = fmt.Sprintf(" (%s)", strings.Join([]string{body, header}, ", "))
} else if len(header) > 0 || len(body) > 0 {
reqStr = fmt.Sprintf(" (%s)", body+header)
}
pathStr := strings.TrimSuffix(buildPathString(endpoint.Path, endpoint.Params.PathParams()), "/")
desc := getDescription(endpoint.Description)
w.writeLines(fmt.Sprintf("%s:", pathStr), PushIndent,
fmt.Sprintf("%s%s%s:", method, reqStr, buildQueryString(endpoint.Params.QueryParams())), PushIndent)
w.writeLines(buildDescriptionLines("| ", desc, CommentLineLength-w.ind.CurrentIndentLen())...)
if len(endpoint.Responses) > 0 {
var outs []string
for _, resp := range endpoint.Responses {
var newline string
switch {
case resp.Type != nil && resp.Text != "":
newline = fmt.Sprintf("return %s <: %s", resp.Text, getSyslTypeName(resp.Type))
case resp.Type != nil:
newline = "return " + getSyslTypeName(resp.Type)
default:
newline = "return " + resp.Text
}
if !swag.ContainsStrings(outs, newline) {
outs = append(outs, newline)
}
}
sort.Strings(outs)
w.writeLines(outs...)
}
w.writeLines(PopIndent, PopIndent)
}
func (w *writer) writeDefinitions(types TypeList) {
w.writeLines("#" + strings.Repeat("-", 75))
w.writeLines("# definitions")
var others []Type
for _, t := range types.Items() {
_, isEnum := t.(*Enum)
switch {
case isBuiltInType(t):
// do nothing
case isUnionType(t):
w.writeLines(BlankLine)
w.writeUnion(t)
case isEnum:
// We want the enum aliases listed with the real types
w.writeLines(BlankLine)
w.writeExternalAlias(t)
case !isExternalAlias(t):
w.writeLines(BlankLine)
w.writeDefinition(t.(*StandardType))
default:
others = append(others, t)
}
}
for _, t := range others {
w.writeLines(BlankLine)
w.writeExternalAlias(t)
}
}
func (w *writer) writeDefinition(t *StandardType) {
bangName := "type"
w.writeLines(fmt.Sprintf("!%s %s:", bangName, appendAttributesString(getSyslTypeName(t), t.Attributes)))
for _, prop := range t.Properties {
suffix := ""
if prop.Optional {
suffix = "?"
}
suffix = appendAttributesString(suffix, prop.Attributes)
name := prop.Name
if IsBuiltIn(name) {
name += "_"
}
if !w.DisableJSONTags {
suffix += ":"
}
w.writeLines(PushIndent, fmt.Sprintf("%s <: %s%s", appendSizeSpec(name, prop.SizeSpec),
getSyslTypeName(prop.Type), suffix))
if !w.DisableJSONTags {
w.writeLines(PushIndent, fmt.Sprintf("@json_tag = %s", quote(prop.Name)), PopIndent)
}
w.writeLines(PopIndent)
}
}
func (w *writer) writeExternalAlias(item Type) {
aliasType := "string"
aliasName := getSyslTypeName(item)
switch t := item.(type) {
case *StandardType:
if len(t.Properties) > 0 {
aliasType = getSyslTypeName(t.Properties[0].Type)
}
case *ExternalAlias:
aliasType = getSyslTypeName(t.Target)
case *Alias:
aliasType = getSyslTypeName(t.Target)
case *Array:
aliasType = getSyslTypeName(item)
aliasName = t.name
}
w.writeLines(fmt.Sprintf("!alias %s:", aliasName),
PushIndent, aliasType, PopIndent)
}
func (w *writer) writeUnion(item Type) {
unionName := getSyslTypeName(item)
t := item.(*Union)
w.writeLines(fmt.Sprintf("!union %s:", unionName), PushIndent)
for _, option := range t.Options {
w.writeLines(option.Name)
}
w.writeLines(PopIndent)
}
func (w *writer) mustWrite(s string) {
if _, err := w.Writer.Write([]byte(s)); err != nil {
w.logger.Fatalf("failed to complete write: %s", err.Error())
}
}
const PushIndent = "&& >>"
const PopIndent = "&& <<"
const BlankLine = "&& !!"
func (w *writer) writeLines(lines ...string) {
for _, l := range lines {
switch l {
case PushIndent:
w.ind.Push()
case PopIndent:
w.ind.Pop()
case BlankLine:
w.mustWrite("\n")
default:
_ = w.ind.Write() // nolint: errcheck
w.mustWrite(l + "\n")
}
}
}