-
Notifications
You must be signed in to change notification settings - Fork 54
/
keywords_standard.go
287 lines (249 loc) · 6.77 KB
/
keywords_standard.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
package jsonschema
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
jptr "github.com/qri-io/jsonpointer"
)
// Const defines the const JSON Schema keyword
type Const json.RawMessage
// NewConst allocates a new Const keyword
func NewConst() Keyword {
return &Const{}
}
// Register implements the Keyword interface for Const
func (c *Const) Register(uri string, registry *SchemaRegistry) {}
// Resolve implements the Keyword interface for Const
func (c *Const) Resolve(pointer jptr.Pointer, uri string) *Schema {
return nil
}
// ValidateKeyword implements the Keyword interface for Const
func (c Const) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
schemaDebug("[Const] Validating")
var con interface{}
if err := json.Unmarshal(c, &con); err != nil {
currentState.AddError(data, err.Error())
return
}
if !reflect.DeepEqual(con, data) {
currentState.AddError(data, fmt.Sprintf(`must equal %s`, InvalidValueString(con)))
}
}
// JSONProp implements the JSONPather for Const
func (c Const) JSONProp(name string) interface{} {
return nil
}
// String implements the Stringer for Const
func (c Const) String() string {
return string(c)
}
// UnmarshalJSON implements the json.Unmarshaler interface for Const
func (c *Const) UnmarshalJSON(data []byte) error {
*c = data
return nil
}
// MarshalJSON implements the json.Marshaler interface for Const
func (c Const) MarshalJSON() ([]byte, error) {
return json.Marshal(json.RawMessage(c))
}
// Enum defines the enum JSON Schema keyword
type Enum []Const
// NewEnum allocates a new Enum keyword
func NewEnum() Keyword {
return &Enum{}
}
// Register implements the Keyword interface for Enum
func (e *Enum) Register(uri string, registry *SchemaRegistry) {}
// Resolve implements the Keyword interface for Enum
func (e *Enum) Resolve(pointer jptr.Pointer, uri string) *Schema {
return nil
}
// ValidateKeyword implements the Keyword interface for Enum
func (e Enum) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
schemaDebug("[Enum] Validating")
subState := currentState.NewSubState()
subState.ClearState()
for _, v := range e {
subState.Errs = &[]KeyError{}
v.ValidateKeyword(ctx, subState, data)
if subState.IsValid() {
return
}
}
currentState.AddError(data, fmt.Sprintf("should be one of %s", e.String()))
}
// JSONProp implements the JSONPather for Enum
func (e Enum) JSONProp(name string) interface{} {
idx, err := strconv.Atoi(name)
if err != nil {
return nil
}
if idx > len(e) || idx < 0 {
return nil
}
return e[idx]
}
// JSONChildren implements the JSONContainer interface for Enum
func (e Enum) JSONChildren() (res map[string]JSONPather) {
res = map[string]JSONPather{}
for i, bs := range e {
res[strconv.Itoa(i)] = bs
}
return
}
// String implements the Stringer for Enum
func (e Enum) String() string {
str := "["
for _, c := range e {
str += c.String() + ", "
}
return str[:len(str)-2] + "]"
}
// List of primitive types supported and used by JSON Schema
var primitiveTypes = map[string]bool{
"null": true,
"boolean": true,
"object": true,
"array": true,
"number": true,
"string": true,
"integer": true,
}
// DataType attempts to parse the underlying data type
// from the raw data interface
func DataType(data interface{}) string {
if data == nil {
return "null"
}
switch reflect.TypeOf(data).Kind() {
case reflect.Bool:
return "boolean"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uintptr:
return "integer"
case reflect.Float32, reflect.Float64:
number := reflect.ValueOf(data).Float()
if float64(int(number)) == number {
return "integer"
}
return "number"
case reflect.String:
return "string"
case reflect.Array, reflect.Slice:
return "array"
case reflect.Map, reflect.Struct:
return "object"
default:
return "unknown"
}
}
// DataTypeWithHint attempts to parse the underlying data type
// by leveraging the schema expectations for better results
func DataTypeWithHint(data interface{}, hint string) string {
dt := DataType(data)
if dt == "string" {
if hint == "boolean" {
_, err := strconv.ParseBool(data.(string))
if err == nil {
return "boolean"
}
}
}
// deals with traling 0 floats
if dt == "integer" && hint == "number" {
return "number"
}
return dt
}
// Type defines the type JSON Schema keyword
type Type struct {
strVal bool
vals []string
}
// NewType allocates a new Type keyword
func NewType() Keyword {
return &Type{}
}
// Register implements the Keyword interface for Type
func (t *Type) Register(uri string, registry *SchemaRegistry) {}
// Resolve implements the Keyword interface for Type
func (t *Type) Resolve(pointer jptr.Pointer, uri string) *Schema {
return nil
}
// ValidateKeyword implements the Keyword interface for Type
func (t Type) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
schemaDebug("[Type] Validating")
jt := DataType(data)
for _, typestr := range t.vals {
if jt == typestr || jt == "integer" && typestr == "number" {
return
}
if jt == "string" && (typestr == "boolean" || typestr == "number" || typestr == "integer") {
if DataTypeWithHint(data, typestr) == typestr {
return
}
}
if jt == "null" && (typestr == "string") {
if DataTypeWithHint(data, typestr) == typestr {
return
}
}
}
if len(t.vals) == 1 {
currentState.AddError(data, fmt.Sprintf(`type should be %s, got %s`, t.vals[0], jt))
return
}
str := ""
for _, ts := range t.vals {
str += ts + ","
}
currentState.AddError(data, fmt.Sprintf(`type should be one of: %s, got %s`, str[:len(str)-1], jt))
}
// String implements the Stringer for Type
func (t Type) String() string {
if len(t.vals) == 0 {
return "unknown"
}
return strings.Join(t.vals, ",")
}
// JSONProp implements the JSONPather for Type
func (t Type) JSONProp(name string) interface{} {
idx, err := strconv.Atoi(name)
if err != nil {
return nil
}
if idx > len(t.vals) || idx < 0 {
return nil
}
return t.vals[idx]
}
// UnmarshalJSON implements the json.Unmarshaler interface for Type
func (t *Type) UnmarshalJSON(data []byte) error {
var single string
if err := json.Unmarshal(data, &single); err == nil {
*t = Type{strVal: true, vals: []string{single}}
} else {
var set []string
if err := json.Unmarshal(data, &set); err == nil {
*t = Type{vals: set}
} else {
return err
}
}
for _, pr := range t.vals {
if !primitiveTypes[pr] {
return fmt.Errorf(`"%s" is not a valid type`, pr)
}
}
return nil
}
// MarshalJSON implements the json.Marshaler interface for Type
func (t Type) MarshalJSON() ([]byte, error) {
if t.strVal {
return json.Marshal(t.vals[0])
}
return json.Marshal(t.vals)
}