Skip to content

Commit

Permalink
Merge pull request #2031 from erikgb/feat/not-predicate
Browse files Browse the repository at this point in the history
✨ feat: add NOT predicate
  • Loading branch information
k8s-ci-robot committed Nov 6, 2022
2 parents c2f04bb + 02c1fae commit ff622bd
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
30 changes: 30 additions & 0 deletions pkg/predicate/predicate.go
Expand Up @@ -50,6 +50,7 @@ var _ Predicate = GenerationChangedPredicate{}
var _ Predicate = AnnotationChangedPredicate{}
var _ Predicate = or{}
var _ Predicate = and{}
var _ Predicate = not{}

// Funcs is a function that implements Predicate.
type Funcs struct {
Expand Down Expand Up @@ -340,6 +341,35 @@ func (o or) Generic(e event.GenericEvent) bool {
return false
}

// Not returns a predicate that implements a logical NOT of the predicate passed to it.
func Not(predicate Predicate) Predicate {
return not{predicate}
}

type not struct {
predicate Predicate
}

func (n not) InjectFunc(f inject.Func) error {
return f(n.predicate)
}

func (n not) Create(e event.CreateEvent) bool {
return !n.predicate.Create(e)
}

func (n not) Update(e event.UpdateEvent) bool {
return !n.predicate.Update(e)
}

func (n not) Delete(e event.DeleteEvent) bool {
return !n.predicate.Delete(e)
}

func (n not) Generic(e event.GenericEvent) bool {
return !n.predicate.Generic(e)
}

// LabelSelectorPredicate constructs a Predicate from a LabelSelector.
// Only objects matching the LabelSelector will be admitted.
func LabelSelectorPredicate(s metav1.LabelSelector) (Predicate, error) {
Expand Down
22 changes: 22 additions & 0 deletions pkg/predicate/predicate_test.go
Expand Up @@ -879,6 +879,28 @@ var _ = Describe("Predicate", func() {
Expect(prct.injected).To(BeTrue())
})
})
Describe("When checking a Not predicate", func() {
It("should return false when its predicate returns true", func() {
n := predicate.Not(passFuncs)
Expect(n.Create(event.CreateEvent{})).To(BeFalse())
Expect(n.Update(event.UpdateEvent{})).To(BeFalse())
Expect(n.Delete(event.DeleteEvent{})).To(BeFalse())
Expect(n.Generic(event.GenericEvent{})).To(BeFalse())
})
It("should return true when its predicate returns false", func() {
n := predicate.Not(failFuncs)
Expect(n.Create(event.CreateEvent{})).To(BeTrue())
Expect(n.Update(event.UpdateEvent{})).To(BeTrue())
Expect(n.Delete(event.DeleteEvent{})).To(BeTrue())
Expect(n.Generic(event.GenericEvent{})).To(BeTrue())
})
It("should inject into its predicate", func() {
prct := &injectablePredicate{}
n := predicate.Not(prct)
Expect(injectFunc(n)).To(Succeed())
Expect(prct.injected).To(BeTrue())
})
})
})

Describe("NewPredicateFuncs with a namespace filter function", func() {
Expand Down

0 comments on commit ff622bd

Please sign in to comment.