-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathschema.go
More file actions
286 lines (241 loc) · 6.53 KB
/
schema.go
File metadata and controls
286 lines (241 loc) · 6.53 KB
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"sort"
"strings"
"github.com/bitly/go-simplejson"
"github.com/olekukonko/tablewriter"
)
type schema struct {
ID string `json:"$id,omitempty"`
Ref string `json:"$ref,omitempty"`
Schema string `json:"$schema,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Required []string `json:"required,omitempty"`
Type PropertyTypes `json:"type,omitempty"`
Properties map[string]*schema `json:"properties,omitempty"`
Items *schema `json:"items,omitempty"`
Definitions map[string]*schema `json:"definitions,omitempty"`
Enum []Any `json:"enum"`
}
func newSchema(r io.Reader, workingDir string) (*schema, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
var data schema
if err := json.Unmarshal(b, &data); err != nil {
return nil, err
}
// Needed for resolving in-schema references.
root, err := simplejson.NewJson(b)
if err != nil {
return nil, err
}
return resolveSchema(&data, workingDir, root)
}
// Markdown returns the Markdown representation of the schema.
//
// The level argument can be used to offset the heading levels. This can be
// useful if you want to add the schema under a subheading.
func (s schema) Markdown(level int) string {
if level < 1 {
level = 1
}
var buf bytes.Buffer
if s.Title != "" {
fmt.Fprintln(&buf, makeHeading(s.Title, level))
fmt.Fprintln(&buf)
}
if s.Description != "" {
fmt.Fprintln(&buf, s.Description)
fmt.Fprintln(&buf)
}
if len(s.Properties) > 0 {
fmt.Fprintln(&buf, makeHeading("Properties", level+1))
fmt.Fprintln(&buf)
}
printProperties(&buf, &s)
// Add padding.
fmt.Fprintln(&buf)
for _, obj := range findDefinitions(&s) {
fmt.Fprint(&buf, obj.Markdown(level+1))
}
return buf.String()
}
func makeHeading(heading string, level int) string {
if level < 0 {
return heading
}
if level <= 6 {
return strings.Repeat("#", level) + " " + heading
}
return fmt.Sprintf("**%s**", heading)
}
func findDefinitions(s *schema) []*schema {
// Gather all properties of object type so that we can generate the
// properties for them recursively.
var objs []*schema
for k, p := range s.Properties {
// Use the identifier as the title.
if p.Type.HasType(PropertyTypeObject) {
p.Title = k
objs = append(objs, p)
}
// If the property is an array of objects, use the name of the array
// property as the title.
if p.Type.HasType(PropertyTypeArray) {
if p.Items != nil {
if p.Items.Type.HasType(PropertyTypeObject) {
p.Items.Title = k
objs = append(objs, p.Items)
}
}
}
}
// Sort the object schemas.
sort.Slice(objs, func(i, j int) bool {
return objs[i].Title < objs[j].Title
})
return objs
}
func printProperties(w io.Writer, s *schema) {
table := tablewriter.NewWriter(w)
table.SetHeader([]string{"Property", "Type", "Required", "Description"})
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.SetAutoFormatHeaders(false)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
// Buffer all property rows so that we can sort them before printing them.
var rows [][]string
for k, p := range s.Properties {
// Generate relative links for objects and arrays of objects.
var propType []string
for _, pt := range p.Type {
switch pt {
case PropertyTypeObject:
propType = append(propType, fmt.Sprintf("[object](#%s)", strings.ToLower(k)))
case PropertyTypeArray:
if p.Items != nil {
for _, pi := range p.Items.Type {
if pi == PropertyTypeObject {
propType = append(propType, fmt.Sprintf("[%s](#%s)[]", pi, strings.ToLower(k)))
} else {
propType = append(propType, fmt.Sprintf("%s[]", pi))
}
}
} else {
propType = append(propType, string(pt))
}
default:
propType = append(propType, string(pt))
}
}
var propTypeStr string
if len(propType) == 1 {
propTypeStr = propType[0]
} else if len(propType) == 2 {
propTypeStr = strings.Join(propType, " or ")
} else if len(propType) > 2 {
propTypeStr = fmt.Sprintf("%s, or %s", strings.Join(propType[:len(propType)-1], ", "), propType[len(propType)-1])
}
// Emphasize required properties.
var required string
if in(s.Required, k) {
required = "**Yes**"
} else {
required = "No"
}
desc := p.Description
if len(p.Enum) > 0 {
var vals []string
for _, e := range p.Enum {
vals = append(vals, e.String())
}
desc += " Possible values are: `" + strings.Join(vals, "`, `") + "`."
}
rows = append(rows, []string{fmt.Sprintf("`%s`", k), propTypeStr, required, strings.TrimSpace(desc)})
}
// Sort by the required column, then by the name column.
sort.Slice(rows, func(i, j int) bool {
if rows[i][2] < rows[j][2] {
return true
}
if rows[i][2] > rows[j][2] {
return false
}
return rows[i][0] < rows[j][0]
})
table.AppendBulk(rows)
table.Render()
}
// in returns true if a string slice contains a specific string.
func in(strs []string, str string) bool {
for _, s := range strs {
if s == str {
return true
}
}
return false
}
type PropertyTypes []PropertyType
func (pts *PropertyTypes) HasType(pt PropertyType) bool {
for _, t := range *pts {
if t == pt {
return true
}
}
return false
}
func (pt *PropertyTypes) UnmarshalJSON(data []byte) error {
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return err
}
switch val := value.(type) {
case string:
*pt = []PropertyType{PropertyType(val)}
return nil
case []interface{}:
var pts []PropertyType
for _, t := range val {
s, ok := t.(string)
if !ok {
return errors.New("unsupported property type")
}
pts = append(pts, PropertyType(s))
}
*pt = pts
default:
return errors.New("unsupported property type")
}
return nil
}
type PropertyType string
const (
PropertyTypeString PropertyType = "string"
PropertyTypeNumber PropertyType = "number"
PropertyTypeBoolean PropertyType = "boolean"
PropertyTypeObject PropertyType = "object"
PropertyTypeArray PropertyType = "array"
PropertyTypeNull PropertyType = "null"
)
type Any struct {
value interface{}
}
func (u *Any) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &u.value); err != nil {
return err
}
return nil
}
func (u *Any) String() string {
return fmt.Sprintf("%v", u.value)
}