-
Notifications
You must be signed in to change notification settings - Fork 16
/
yaml.go
116 lines (100 loc) · 2.18 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
package polluter
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"strconv"
"github.com/pkg/errors"
"github.com/romanyx/jwalk"
yaml "gopkg.in/yaml.v2"
)
type yamlParser struct{}
func (p yamlParser) parse(r io.Reader) (jwalk.ObjectWalker, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.Wrap(err, "read from input")
}
j, err := yamlToJSON(data)
if err != nil {
return nil, errors.Wrap(err, "failed convert to json")
}
i, err := jwalk.Parse(j)
if err != nil {
return nil, errors.Wrap(err, "failed to parse")
}
obj, ok := i.(jwalk.ObjectWalker)
if !ok {
return nil, errors.New("unexpected format")
}
return obj, nil
}
func yamlToJSON(data []byte) ([]byte, error) {
mapSlice := yaml.MapSlice{}
err := yaml.Unmarshal(data, &mapSlice)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
buf := new(bytes.Buffer)
handleMapSlice(mapSlice, buf)
return buf.Bytes(), nil
}
func handleMapSlice(mapSlice yaml.MapSlice, buf *bytes.Buffer) {
buf.WriteString("{")
first := true
indent := ""
for _, item := range mapSlice {
buf.WriteString(indent + "\"" + item.Key.(string) + "\"" + ":")
switch v := item.Value.(type) {
case yaml.MapSlice:
handleMapSlice(v, buf)
case []interface{}:
buf.WriteString("[")
first := true
indent := ""
for _, i := range v {
switch v := i.(type) {
case yaml.MapSlice:
buf.WriteString(indent)
handleMapSlice(v, buf)
default:
buf.WriteString(indent + formatValue(v))
}
if first {
first = false
indent = ","
}
}
buf.WriteString("]")
default:
buf.WriteString(formatValue(v))
}
if first {
first = false
indent = ","
}
}
buf.WriteString("}")
}
func formatValue(typedYAMLObj interface{}) string {
switch typedVal := typedYAMLObj.(type) {
case string:
return fmt.Sprintf("\"%s\"", typedVal)
case int:
return strconv.FormatInt(int64(typedVal), 10)
case int64:
return strconv.FormatInt(typedVal, 10)
case float64:
return strconv.FormatFloat(typedVal, 'g', -1, 32)
case uint64:
return strconv.FormatUint(typedVal, 10)
case bool:
if typedVal {
return "true"
}
return "false"
default:
return "null"
}
return ""
}