Skip to content

Commit c3ab38d

Browse files
committed
✨ Add ContainsFinalizer helper to the controllerutil
1 parent a457e27 commit c3ab38d

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

pkg/controller/controllerutil/controllerutil.go

+21
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,24 @@ func RemoveFinalizerWithError(o runtime.Object, finalizer string) error {
280280
RemoveFinalizer(m, finalizer)
281281
return nil
282282
}
283+
284+
// ContainsFinalizer checks a metav1 object that the provided finalizer is present.
285+
func ContainsFinalizer(o metav1.Object, finalizer string) bool {
286+
f := o.GetFinalizers()
287+
for _, e := range f {
288+
if e == finalizer {
289+
return true
290+
}
291+
}
292+
return false
293+
}
294+
295+
// ContainsFinalizerWithError checks a metav1 object that the provided finalizer is present.
296+
// It returns an error if the provided object cannot provide an accessor.
297+
func ContainsFinalizerWithError(o runtime.Object, finalizer string) (bool, error) {
298+
m, err := meta.Accessor(o)
299+
if err != nil {
300+
return false, err
301+
}
302+
return ContainsFinalizer(m, finalizer), nil
303+
}

pkg/controller/controllerutil/controllerutil_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,18 @@ var _ = Describe("Controllerutil", func() {
446446
Expect(deploy.ObjectMeta.GetFinalizers()).To(Equal([]string{}))
447447
})
448448
})
449+
450+
Describe("ContainsFinalizer", func() {
451+
It("should check that finalizer is present", func() {
452+
controllerutil.AddFinalizer(deploy, testFinalizer)
453+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(true))
454+
})
455+
456+
It("should check that finalizer is not present after RemoveFinalizer call", func() {
457+
controllerutil.RemoveFinalizer(deploy, testFinalizer)
458+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(false))
459+
})
460+
})
449461
})
450462
})
451463

0 commit comments

Comments
 (0)