forked from goss-org/goss
/
matching.go
107 lines (89 loc) · 2.41 KB
/
matching.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
105
106
107
package resource
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/aelsabbahy/goss/system"
"github.com/aelsabbahy/goss/util"
)
type Matching struct {
Title string `json:"title,omitempty" yaml:"title,omitempty"`
Meta meta `json:"meta,omitempty" yaml:"meta,omitempty"`
Content interface{} `json:"content,omitempty" yaml:"content,omitempty"`
Id string `json:"-" yaml:"-"`
Matches matcher `json:"matches" yaml:"matches"`
}
type MatchingMap map[string]*Matching
func (a *Matching) ID() string { return a.Id }
func (a *Matching) SetID(id string) { a.Id = id }
// FIXME: Can this be refactored?
func (r *Matching) GetTitle() string { return r.Title }
func (r *Matching) GetMeta() meta { return r.Meta }
func (a *Matching) Validate(sys *system.System) []TestResult {
skip := false
// ValidateValue expects a function
stub := func() (interface{}, error) {
return a.Content, nil
}
var results []TestResult
results = append(results, ValidateValue(a, "matches", a.Matches, stub, skip))
return results
}
func (ret *MatchingMap) UnmarshalJSON(data []byte) error {
// Curried json.Unmarshal
unmarshal := func(i interface{}) error {
if err := json.Unmarshal(data, i); err != nil {
return err
}
return nil
}
// Validate configuration
zero := Matching{}
whitelist, err := util.WhitelistAttrs(zero, util.JSON)
if err != nil {
return err
}
if err := util.ValidateSections(unmarshal, zero, whitelist); err != nil {
return err
}
var tmp map[string]*Matching
if err := unmarshal(&tmp); err != nil {
return err
}
typ := reflect.TypeOf(zero)
typs := strings.Split(typ.String(), ".")[1]
for id, res := range tmp {
if res == nil {
return fmt.Errorf("Could not parse resource %s:%s", typs, id)
}
res.SetID(id)
}
*ret = tmp
return nil
}
func (ret *MatchingMap) UnmarshalYAML(unmarshal func(v interface{}) error) error {
// Validate configuration
zero := Matching{}
whitelist, err := util.WhitelistAttrs(zero, util.YAML)
if err != nil {
return err
}
if err := util.ValidateSections(unmarshal, zero, whitelist); err != nil {
return err
}
var tmp map[string]*Matching
if err := unmarshal(&tmp); err != nil {
return err
}
typ := reflect.TypeOf(zero)
typs := strings.Split(typ.String(), ".")[1]
for id, res := range tmp {
if res == nil {
return fmt.Errorf("Could not parse resource %s:%s", typs, id)
}
res.SetID(id)
}
*ret = tmp
return nil
}