forked from easegress-io/easegress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visitor.go
78 lines (67 loc) · 1.42 KB
/
visitor.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
package command
import (
"bufio"
"io"
"strings"
"k8s.io/apimachinery/pkg/util/yaml"
)
// VisitorFunc executes visition logic
type VisitorFunc func([]spec)
// Visitor walk through the document via VisitorFunc
type Visitor interface {
Visit(VisitorFunc)
}
type spec struct {
Kind string
Name string
doc string
}
type streamVisitor struct {
io.Reader
}
// NewStreamVisitor returns a streamVisitor.
func NewStreamVisitor(src string) *streamVisitor {
return &streamVisitor{
Reader: strings.NewReader(src),
}
}
type yamlDecoder struct {
reader *yaml.YAMLReader
doc string
}
func newYAMLDecoder(r io.Reader) *yamlDecoder {
return &yamlDecoder{
reader: yaml.NewYAMLReader(bufio.NewReader(r)),
}
}
// Decode reads a YAML document into bytes and tries to yaml.Unmarshal it.
func (d *yamlDecoder) Decode(into interface{}) error {
bytes, err := d.reader.Read()
if err != nil && err != io.EOF {
return err
}
d.doc = string(bytes)
if len(bytes) != 0 {
err = yaml.Unmarshal(bytes, into)
}
return err
}
// Visit implements Visitor over a stream.
func (v *streamVisitor) Visit(fn VisitorFunc) {
d := newYAMLDecoder(v.Reader)
var validDocs []spec
for {
var s spec
if err := d.Decode(&s); err != nil {
if err == io.EOF {
break
} else {
ExitWithErrorf("error parsing %s: %v", d.doc, err)
}
}
s.doc = d.doc
//TODO can validate spec's Kind here
validDocs = append(validDocs, s)
}
fn(validDocs)
}