Skip to content

Commit

Permalink
✨ Add HasOwnerReference (#2882)
Browse files Browse the repository at this point in the history
* add HasOwnerReference

Signed-off-by: sivchari <[email protected]>

* revise API

Signed-off-by: sivchari <[email protected]>

* add new suite test

Signed-off-by: sivchari <[email protected]>

* fix: test

Signed-off-by: sivchari <[email protected]>

---------

Signed-off-by: sivchari <[email protected]>
  • Loading branch information
sivchari authored Sep 21, 2024
1 parent 62834f9 commit 659afe9
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/controller/controllerutil/controllerutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,21 @@ func HasControllerReference(object metav1.Object) bool {
return false
}

// HasOwnerReference returns true if the owners list contains an owner reference
// that matches the object's group, kind, and name.
func HasOwnerReference(ownerRefs []metav1.OwnerReference, obj client.Object, scheme *runtime.Scheme) (bool, error) {
gvk, err := apiutil.GVKForObject(obj, scheme)
if err != nil {
return false, err
}
idx := indexOwnerRef(ownerRefs, metav1.OwnerReference{
APIVersion: gvk.GroupVersion().String(),
Name: obj.GetName(),
Kind: gvk.Kind,
})
return idx != -1, nil
}

// RemoveControllerReference removes an owner reference where the controller
// equals true
func RemoveControllerReference(owner, object metav1.Object, scheme *runtime.Scheme) error {
Expand Down
27 changes: 27 additions & 0 deletions pkg/controller/controllerutil/controllerutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,33 @@ var _ = Describe("Controllerutil", func() {
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(BeFalse())
})
})

Describe("HasOwnerReference", func() {
It("should return true if the object has the owner reference", func() {
rs := &appsv1.ReplicaSet{
ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: "foo-uid"},
}
dep := &extensionsv1beta1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: "foo-uid"},
}
Expect(controllerutil.SetOwnerReference(dep, rs, scheme.Scheme)).ToNot(HaveOccurred())
b, err := controllerutil.HasOwnerReference(rs.GetOwnerReferences(), dep, scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
Expect(b).To(BeTrue())
})

It("should return false if the object does not have the owner reference", func() {
rs := &appsv1.ReplicaSet{
ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: "foo-uid"},
}
dep := &extensionsv1beta1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: "foo-uid"},
}
b, err := controllerutil.HasOwnerReference(rs.GetOwnerReferences(), dep, scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
Expect(b).To(BeFalse())
})
})
})
})

Expand Down

0 comments on commit 659afe9

Please sign in to comment.