forked from helmfile/vals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
104 lines (91 loc) · 1.74 KB
/
io.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
package vals
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
func Inputs(f string) ([]yaml.Node, error) {
var reader io.Reader
if f == "-" {
reader = os.Stdin
} else if f != "" {
fp, err := os.Open(f)
if err != nil {
return nil, err
}
info, err := fp.Stat()
if err != nil {
return nil, err
}
if info.IsDir() {
entries, err := fp.ReadDir(0)
if err != nil {
return nil, err
}
var nodes []yaml.Node
for _, e := range entries {
s := filepath.Join(f, e.Name())
ns, err := Inputs(s)
if err != nil {
return nil, err
}
nodes = append(nodes, ns...)
}
return nodes, nil
}
reader = fp
defer func() {
_ = fp.Close()
}()
} else {
return nil, fmt.Errorf("Nothing to eval: No file specified")
}
return nodesFromReader(reader)
}
func nodesFromReader(reader io.Reader) ([]yaml.Node, error) {
nodes := []yaml.Node{}
buf := bufio.NewReader(reader)
decoder := yaml.NewDecoder(buf)
for {
node := yaml.Node{}
if err := decoder.Decode(&node); err != nil {
if err != io.EOF {
return nil, err
}
break
}
if len(node.Content[0].Content) > 0 {
nodes = append(nodes, node)
}
}
return nodes, nil
}
func Output(output io.Writer, format string, nodes []yaml.Node) error {
for i, node := range nodes {
var v interface{}
if err := node.Decode(&v); err != nil {
return err
}
if format == "json" {
bs, err := json.Marshal(v)
if err != nil {
return err
}
fmt.Fprintln(output, string(bs))
} else {
encoder := yaml.NewEncoder(output)
encoder.SetIndent(2)
if err := encoder.Encode(v); err != nil {
return err
}
}
if i != len(nodes)-1 {
fmt.Fprintln(output, "---")
}
}
return nil
}