/
select_annotations_predicate.go
70 lines (55 loc) · 1.68 KB
/
select_annotations_predicate.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
/*
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
*/
package predicates
import (
"reflect"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
type HasAnnotationChanged func(old *string, new *string) bool
func HasBasicAnnotationChanged(old *string, new *string) bool {
return !reflect.DeepEqual(old, new)
}
// MakeSelectAnnotationChangedPredicate creates a selectAnnotationChangedPredicate watching for
// changes to select annotations.
// annotations is a map of annotations to HasAnnotationChanged handlers which define if the annotation has been
// changed in a way we care about.
func MakeSelectAnnotationChangedPredicate(annotations map[string]HasAnnotationChanged) predicate.Predicate {
return selectAnnotationChangedPredicate{
annotations: annotations,
}
}
type selectAnnotationChangedPredicate struct {
predicate.Funcs
annotations map[string]HasAnnotationChanged
}
var _ predicate.Predicate = selectAnnotationChangedPredicate{}
// Update implements UpdateEvent filter for annotation changes.
func (p selectAnnotationChangedPredicate) Update(e event.UpdateEvent) bool {
if e.ObjectOld == nil {
return false
}
if e.ObjectNew == nil {
return false
}
newAnnotations := e.ObjectNew.GetAnnotations()
oldAnnotations := e.ObjectOld.GetAnnotations()
for k, f := range p.annotations {
oldAnnotation := valueOrNil(oldAnnotations, k)
newAnnotation := valueOrNil(newAnnotations, k)
changed := f(oldAnnotation, newAnnotation)
if changed {
return true
}
}
return false
}
func valueOrNil(annotations map[string]string, key string) *string {
val, ok := annotations[key]
if !ok {
return nil
}
return &val
}