forked from totvs-cloud/go-manifest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
116 lines (94 loc) · 2.25 KB
/
filter.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
108
109
110
111
112
113
114
115
116
package manifest
import (
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
)
type Filter func(u *unstructured.Unstructured) bool
func (l *list) Filter(funcs ...Filter) List {
resources := make([]*unstructured.Unstructured, 0, l.Size())
for _, v := range l.Resources() {
resource := v.DeepCopy()
for _, filter := range funcs {
if filter(resource) {
resources = append(resources, resource)
}
}
}
return &list{resources: resources, fieldManager: l.fieldManager, client: l.client, mapper: l.mapper}
}
func All(filters ...Filter) Filter {
return func(u *unstructured.Unstructured) bool {
for _, filter := range filters {
if !filter(u) {
return false
}
}
return true
}
}
func Any(filters ...Filter) Filter {
return func(u *unstructured.Unstructured) bool {
for _, filter := range filters {
if filter(u) {
return true
}
}
return false
}
}
func Not(filter Filter) Filter {
return func(u *unstructured.Unstructured) bool {
return !filter(u)
}
}
func ByAPIVersion(apiVersion string) Filter {
return func(u *unstructured.Unstructured) bool {
return u.GetAPIVersion() == apiVersion
}
}
func ByKind(kind string) Filter {
return func(u *unstructured.Unstructured) bool {
return u.GetKind() == kind
}
}
func ByAnnotation(annotation, value string) Filter {
return func(u *unstructured.Unstructured) bool {
v, ok := u.GetAnnotations()[annotation]
if value == "" {
return ok
}
return v == value
}
}
func ByLabel(label, value string) Filter {
return func(u *unstructured.Unstructured) bool {
v, ok := u.GetLabels()[label]
if value == "" {
return ok
}
return v == value
}
}
func ByLabels(labels map[string]string) Filter {
return func(u *unstructured.Unstructured) bool {
for key, value := range labels {
if v := u.GetLabels()[key]; v == value {
return true
}
}
return false
}
}
func In(manifest List) Filter {
key := func(u *unstructured.Unstructured) string {
return fmt.Sprintf("%s|%s/%s", u.GroupVersionKind().GroupKind(), u.GetNamespace(), u.GetName())
}
index := sets.NewString()
for _, u := range manifest.Resources() {
index.Insert(key(u))
}
return func(u *unstructured.Unstructured) bool {
return index.Has(key(u))
}
}