forked from kubernetes/kube-state-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whiteblacklist.go
107 lines (90 loc) · 2.23 KB
/
whiteblacklist.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 whiteblacklist
import (
"errors"
"strings"
)
// WhiteBlackList encapsulates the logic needed to filter based on a string.
type WhiteBlackList struct {
list map[string]struct{}
isWhiteList bool
}
// New constructs a new WhtieBlackList based on a white- and a
// blacklist. Only one of them can be not empty.
func New(w, b map[string]struct{}) (*WhiteBlackList, error) {
if len(w) != 0 && len(b) != 0 {
return nil, errors.New(
"whitelist and blacklist are both set, they are mutually exclusive, only one of them can be set",
)
}
white := copyList(w)
black := copyList(b)
var list map[string]struct{}
var isWhiteList bool
// Default to blacklisting
if len(white) != 0 {
list = white
isWhiteList = true
} else {
list = black
isWhiteList = false
}
return &WhiteBlackList{
list: list,
isWhiteList: isWhiteList,
}, nil
}
// Include includes the given items in the list.
func (l *WhiteBlackList) Include(items []string) {
if l.isWhiteList {
for _, item := range items {
l.list[item] = struct{}{}
}
} else {
for _, item := range items {
delete(l.list, item)
}
}
}
// Exclude excludes the given items from the list.
func (l *WhiteBlackList) Exclude(items []string) {
if l.isWhiteList {
for _, item := range items {
delete(l.list, item)
}
} else {
for _, item := range items {
l.list[item] = struct{}{}
}
}
}
// IsIncluded returns if the given item is included.
func (l *WhiteBlackList) IsIncluded(item string) bool {
_, exists := l.list[item]
if l.isWhiteList {
return exists
}
return !exists
}
// IsExcluded returns if the given item is excluded.
func (l *WhiteBlackList) IsExcluded(item string) bool {
return !l.IsIncluded(item)
}
// Status returns the status of the WhtieBlackList that can e.g. be passed into
// a logger.
func (l *WhiteBlackList) Status() string {
items := []string{}
for key := range l.list {
items = append(items, key)
}
if l.isWhiteList {
return "whitelisting the following items: " + strings.Join(items, ", ")
}
return "blacklisting the following items: " + strings.Join(items, ", ")
}
func copyList(l map[string]struct{}) map[string]struct{} {
newList := map[string]struct{}{}
for k, v := range l {
newList[k] = v
}
return newList
}