-
Notifications
You must be signed in to change notification settings - Fork 2
/
yaml.go
61 lines (45 loc) · 991 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
54
55
56
57
58
59
60
61
package bkl
import (
"bytes"
"regexp"
"gopkg.in/yaml.v3"
)
func yamlMarshalStream(vs []any) ([]byte, error) {
// Differs from repeated yaml.Encode by writing "---\n---" for an empty
// document rather than "null".
first := true
buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
for _, v := range vs {
first2 := first
first = false
if v == nil {
if !first2 {
buf.Write([]byte("---\n"))
}
continue
}
err := enc.Encode(v)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
var yamlRE = regexp.MustCompile(`(?m)^---$`)
func yamlUnmarshalStream(in []byte) ([]any, error) {
// Differs from repeated yaml.Decode by treating "---\n---" as an empty
// document rather than skipping it.
parts := yamlRE.Split(string(in), -1)
ret := []any{}
for _, s := range parts {
var obj any
err := yaml.Unmarshal([]byte(s), &obj)
if err != nil {
return nil, err
}
ret = append(ret, obj)
}
return ret, nil
}