/
main.go
89 lines (78 loc) · 1.84 KB
/
main.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
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/HaesungSeo/yamlconv"
"gopkg.in/yaml.v2"
)
type SearchKey []string
func (m *SearchKey) String() string {
return fmt.Sprint(*m)
}
func (m *SearchKey) Set(v string) error {
*m = append(*m, v)
return nil
}
func main() {
var searchKeys SearchKey
yamlpath := flag.String("f", "/dev/stdin", "yaml file")
ofmt := flag.String("o", "text", "output format, one of yaml, json, text")
flag.Var(&searchKeys, "s", "define search keys multiple times, e.g. -s sriov -s [0] -s ip")
flag.Parse()
// read yaml file into buffer
var filebuf []byte
filename, err := filepath.Abs(*yamlpath)
if err != nil {
panic(err.Error())
}
filebuf, err = os.ReadFile(filename)
if err != nil {
panic(err.Error())
}
// remove comments and empty lines, etc
lines := strings.Split(string(filebuf), "\n")
rline := make([]string, 0)
for _, line := range lines {
nline := strings.TrimRight(line, "\r\n")
if len(nline) == 0 {
continue
} else if nline[0] == '#' {
continue
}
rline = append(rline, nline)
}
// '\n' to \n, if input is single line of string
if len(rline) <= 1 {
nbuf := strings.ReplaceAll(string(filebuf), `\n`, "\n")
filebuf = []byte(nbuf)
}
// parse it
var data interface{}
err = yaml.Unmarshal(filebuf, &data)
if err != nil {
panic(fmt.Sprintf("ERROR: %s\n", err.Error()))
}
data, err = yamlconv.Search(data, searchKeys)
if err != nil {
panic(fmt.Sprintf("ERROR: %s\n", err.Error()))
}
switch *ofmt {
case "text":
yamlconv.Print(data, " ")
case "json":
buf, err := yamlconv.MarshalJson(data, []string{})
if err != nil {
panic(fmt.Sprintf("ERROR: %s\n", err.Error()))
}
os.Stdout.Write(buf)
case "yaml":
buf, err := yaml.Marshal(data)
if err != nil {
panic(fmt.Sprintf("ERROR: %s\n", err.Error()))
}
os.Stdout.Write(buf)
}
}