-
Notifications
You must be signed in to change notification settings - Fork 13
/
yaml.go
53 lines (48 loc) · 963 Bytes
/
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
// Package yaml provides a way to convert YAML into types.Value and vice versa.
package yaml
import (
"errors"
"io"
"gopkg.in/yaml.v2"
"github.com/genkami/watson/pkg/types"
)
func Decode(w io.Writer, val *types.Value) error {
obj := val.ToGoObject()
enc := yaml.NewEncoder(w)
defer enc.Close()
arr, ok := obj.([]interface{})
if !ok {
return enc.Encode(obj)
}
for _, v := range arr {
err := enc.Encode(v)
if err != nil {
return err
}
}
return nil
}
func Encode(r io.Reader) (*types.Value, error) {
var any interface{}
dec := yaml.NewDecoder(r)
results := make([]*types.Value, 0)
for {
err := dec.Decode(&any)
if err != nil {
if errors.Is(err, io.EOF) && len(results) > 0 {
break
}
return nil, err
}
v, err := types.ToValue(any)
if err != nil {
return nil, err
}
results = append(results, v)
}
if len(results) == 1 {
return results[0], nil
} else {
return types.NewArrayValue(results), nil
}
}