-
Notifications
You must be signed in to change notification settings - Fork 46
/
yaml.go
481 lines (437 loc) · 11.5 KB
/
yaml.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright 2015 go-swagger maintainers
//
// 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 swag
import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"reflect"
"sort"
"strconv"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
yaml "gopkg.in/yaml.v3"
)
// YAMLMatcher matches yaml
func YAMLMatcher(path string) bool {
ext := filepath.Ext(path)
return ext == ".yaml" || ext == ".yml"
}
// YAMLToJSON converts YAML unmarshaled data into json compatible data
func YAMLToJSON(data interface{}) (json.RawMessage, error) {
jm, err := transformData(data)
if err != nil {
return nil, err
}
b, err := WriteJSON(jm)
return json.RawMessage(b), err
}
// BytesToYAMLDoc converts a byte slice into a YAML document
func BytesToYAMLDoc(data []byte) (interface{}, error) {
var document yaml.Node // preserve order that is present in the document
if err := yaml.Unmarshal(data, &document); err != nil {
return nil, err
}
if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode {
return nil, errors.New("only YAML documents that are objects are supported")
}
return &document, nil
}
func yamlNode(root *yaml.Node) (interface{}, error) {
switch root.Kind {
case yaml.DocumentNode:
return yamlDocument(root)
case yaml.SequenceNode:
return yamlSequence(root)
case yaml.MappingNode:
return yamlMapping(root)
case yaml.ScalarNode:
return yamlScalar(root)
case yaml.AliasNode:
return yamlNode(root.Alias)
default:
return nil, fmt.Errorf("unsupported YAML node type: %v", root.Kind)
}
}
func yamlDocument(node *yaml.Node) (interface{}, error) {
if len(node.Content) != 1 {
return nil, fmt.Errorf("unexpected YAML Document node content length: %d", len(node.Content))
}
return yamlNode(node.Content[0])
}
func yamlMapping(node *yaml.Node) (interface{}, error) {
m := make(JSONMapSlice, len(node.Content)/2)
var j int
for i := 0; i < len(node.Content); i += 2 {
var nmi JSONMapItem
k, err := yamlStringScalarC(node.Content[i])
if err != nil {
return nil, fmt.Errorf("unable to decode YAML map key: %w", err)
}
nmi.Key = k
v, err := yamlNode(node.Content[i+1])
if err != nil {
return nil, fmt.Errorf("unable to process YAML map value for key %q: %w", k, err)
}
nmi.Value = v
m[j] = nmi
j++
}
return m, nil
}
func yamlSequence(node *yaml.Node) (interface{}, error) {
s := make([]interface{}, 0)
for i := 0; i < len(node.Content); i++ {
v, err := yamlNode(node.Content[i])
if err != nil {
return nil, fmt.Errorf("unable to decode YAML sequence value: %w", err)
}
s = append(s, v)
}
return s, nil
}
const ( // See https://yaml.org/type/
yamlStringScalar = "tag:yaml.org,2002:str"
yamlIntScalar = "tag:yaml.org,2002:int"
yamlBoolScalar = "tag:yaml.org,2002:bool"
yamlFloatScalar = "tag:yaml.org,2002:float"
yamlTimestamp = "tag:yaml.org,2002:timestamp"
yamlNull = "tag:yaml.org,2002:null"
)
func yamlScalar(node *yaml.Node) (interface{}, error) {
switch node.LongTag() {
case yamlStringScalar:
return node.Value, nil
case yamlBoolScalar:
b, err := strconv.ParseBool(node.Value)
if err != nil {
return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w", node.Value, err)
}
return b, nil
case yamlIntScalar:
i, err := strconv.ParseInt(node.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w", node.Value, err)
}
return i, nil
case yamlFloatScalar:
f, err := strconv.ParseFloat(node.Value, 64)
if err != nil {
return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w", node.Value, err)
}
return f, nil
case yamlTimestamp:
return node.Value, nil
case yamlNull:
return nil, nil //nolint:nilnil
default:
return nil, fmt.Errorf("YAML tag %q is not supported", node.LongTag())
}
}
func yamlStringScalarC(node *yaml.Node) (string, error) {
if node.Kind != yaml.ScalarNode {
return "", fmt.Errorf("expecting a string scalar but got %q", node.Kind)
}
switch node.LongTag() {
case yamlStringScalar, yamlIntScalar, yamlFloatScalar:
return node.Value, nil
default:
return "", fmt.Errorf("YAML tag %q is not supported as map key", node.LongTag())
}
}
// JSONMapSlice represent a JSON object, with the order of keys maintained
type JSONMapSlice []JSONMapItem
// MarshalJSON renders a JSONMapSlice as JSON
func (s JSONMapSlice) MarshalJSON() ([]byte, error) {
w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty}
s.MarshalEasyJSON(w)
return w.BuildBytes()
}
// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON
func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) {
w.RawByte('{')
ln := len(s)
last := ln - 1
for i := 0; i < ln; i++ {
s[i].MarshalEasyJSON(w)
if i != last { // last item
w.RawByte(',')
}
}
w.RawByte('}')
}
// UnmarshalJSON makes a JSONMapSlice from JSON
func (s *JSONMapSlice) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
s.UnmarshalEasyJSON(&l)
return l.Error()
}
// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON
func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) {
if in.IsNull() {
in.Skip()
return
}
var result JSONMapSlice
in.Delim('{')
for !in.IsDelim('}') {
var mi JSONMapItem
mi.UnmarshalEasyJSON(in)
result = append(result, mi)
}
*s = result
}
func (s JSONMapSlice) MarshalYAML() (interface{}, error) {
var n yaml.Node
n.Kind = yaml.DocumentNode
var nodes []*yaml.Node
for _, item := range s {
nn, err := json2yaml(item.Value)
if err != nil {
return nil, err
}
ns := []*yaml.Node{
{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: item.Key,
},
nn,
}
nodes = append(nodes, ns...)
}
n.Content = []*yaml.Node{
{
Kind: yaml.MappingNode,
Content: nodes,
},
}
return yaml.Marshal(&n)
}
func isNil(input interface{}) bool {
if input == nil {
return true
}
kind := reflect.TypeOf(input).Kind()
switch kind { //nolint:exhaustive
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan:
return reflect.ValueOf(input).IsNil()
default:
return false
}
}
func json2yaml(item interface{}) (*yaml.Node, error) {
if isNil(item) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Value: "null",
}, nil
}
switch val := item.(type) {
case JSONMapSlice:
var n yaml.Node
n.Kind = yaml.MappingNode
for i := range val {
childNode, err := json2yaml(&val[i].Value)
if err != nil {
return nil, err
}
n.Content = append(n.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: val[i].Key,
}, childNode)
}
return &n, nil
case map[string]interface{}:
var n yaml.Node
n.Kind = yaml.MappingNode
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := val[k]
childNode, err := json2yaml(v)
if err != nil {
return nil, err
}
n.Content = append(n.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: k,
}, childNode)
}
return &n, nil
case []interface{}:
var n yaml.Node
n.Kind = yaml.SequenceNode
for i := range val {
childNode, err := json2yaml(val[i])
if err != nil {
return nil, err
}
n.Content = append(n.Content, childNode)
}
return &n, nil
case string:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: val,
}, nil
case float64:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlFloatScalar,
Value: strconv.FormatFloat(val, 'f', -1, 64),
}, nil
case int64:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlIntScalar,
Value: strconv.FormatInt(val, 10),
}, nil
case uint64:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlIntScalar,
Value: strconv.FormatUint(val, 10),
}, nil
case bool:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlBoolScalar,
Value: strconv.FormatBool(val),
}, nil
default:
return nil, fmt.Errorf("unhandled type: %T", val)
}
}
// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice
type JSONMapItem struct {
Key string
Value interface{}
}
// MarshalJSON renders a JSONMapItem as JSON
func (s JSONMapItem) MarshalJSON() ([]byte, error) {
w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty}
s.MarshalEasyJSON(w)
return w.BuildBytes()
}
// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON
func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) {
w.String(s.Key)
w.RawByte(':')
w.Raw(WriteJSON(s.Value))
}
// UnmarshalJSON makes a JSONMapItem from JSON
func (s *JSONMapItem) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
s.UnmarshalEasyJSON(&l)
return l.Error()
}
// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON
func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) {
key := in.UnsafeString()
in.WantColon()
value := in.Interface()
in.WantComma()
s.Key = key
s.Value = value
}
func transformData(input interface{}) (out interface{}, err error) {
format := func(t interface{}) (string, error) {
switch k := t.(type) {
case string:
return k, nil
case uint:
return strconv.FormatUint(uint64(k), 10), nil
case uint8:
return strconv.FormatUint(uint64(k), 10), nil
case uint16:
return strconv.FormatUint(uint64(k), 10), nil
case uint32:
return strconv.FormatUint(uint64(k), 10), nil
case uint64:
return strconv.FormatUint(k, 10), nil
case int:
return strconv.Itoa(k), nil
case int8:
return strconv.FormatInt(int64(k), 10), nil
case int16:
return strconv.FormatInt(int64(k), 10), nil
case int32:
return strconv.FormatInt(int64(k), 10), nil
case int64:
return strconv.FormatInt(k, 10), nil
default:
return "", fmt.Errorf("unexpected map key type, got: %T", k)
}
}
switch in := input.(type) {
case yaml.Node:
return yamlNode(&in)
case *yaml.Node:
return yamlNode(in)
case map[interface{}]interface{}:
o := make(JSONMapSlice, 0, len(in))
for ke, va := range in {
var nmi JSONMapItem
if nmi.Key, err = format(ke); err != nil {
return nil, err
}
v, ert := transformData(va)
if ert != nil {
return nil, ert
}
nmi.Value = v
o = append(o, nmi)
}
return o, nil
case []interface{}:
len1 := len(in)
o := make([]interface{}, len1)
for i := 0; i < len1; i++ {
o[i], err = transformData(in[i])
if err != nil {
return nil, err
}
}
return o, nil
}
return input, nil
}
// YAMLDoc loads a yaml document from either http or a file and converts it to json
func YAMLDoc(path string) (json.RawMessage, error) {
yamlDoc, err := YAMLData(path)
if err != nil {
return nil, err
}
data, err := YAMLToJSON(yamlDoc)
if err != nil {
return nil, err
}
return data, nil
}
// YAMLData loads a yaml document from either http or a file
func YAMLData(path string) (interface{}, error) {
data, err := LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return BytesToYAMLDoc(data)
}