-
Notifications
You must be signed in to change notification settings - Fork 98
/
parser.go
82 lines (69 loc) · 1.56 KB
/
parser.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
package firmwarepasswd
import (
"bufio"
"bytes"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
)
type Matcher struct {
Match func(string) bool
KeyFunc func(string) (string, error)
ValFunc func(string) (string, error)
}
type OutputParser struct {
matchers []Matcher
logger log.Logger
}
func NewParser(logger log.Logger, matchers []Matcher) *OutputParser {
p := &OutputParser{
matchers: matchers,
logger: logger,
}
return p
}
// Parse looks at command output, line by line. It uses the defined Matchers to set any appropriate values
func (p *OutputParser) Parse(input *bytes.Buffer) []map[string]string {
var results []map[string]string
scanner := bufio.NewScanner(input)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}
row := make(map[string]string)
// check each possible key match
for _, m := range p.matchers {
if m.Match(line) {
key, err := m.KeyFunc(line)
if err != nil {
level.Debug(p.logger).Log(
"msg", "key match failed",
"line", line,
"err", err,
)
continue
}
val, err := m.ValFunc(line)
if err != nil {
level.Debug(p.logger).Log(
"msg", "value match failed",
"line", line,
"err", err,
)
continue
}
row[key] = val
continue
}
}
if len(row) == 0 {
level.Debug(p.logger).Log("msg", "No matched keys", "line", line)
continue
}
results = append(results, row)
}
if err := scanner.Err(); err != nil {
level.Debug(p.logger).Log("msg", "scanner error", "err", err)
}
return results
}