Skip to content

Commit

Permalink
✨ Add ContainsLabels helper option for List calls
Browse files Browse the repository at this point in the history
Signed-off-by: Vince Prignano <vincepri@vmware.com>
  • Loading branch information
vincepri committed Feb 6, 2020
1 parent 82a78f9 commit 72b0730
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
14 changes: 12 additions & 2 deletions pkg/client/fake/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ var _ = Describe("Fake client", func() {
Expect(list.Items).To(HaveLen(2))
})

It("should support filtering by labels", func() {
By("Listing deployments with a particular label")
It("should support filtering by labels and their values", func() {
By("Listing deployments with a particular label and value")
list := &appsv1.DeploymentList{}
err := cl.List(nil, list, client.InNamespace("ns1"),
client.MatchingLabels(map[string]string{
Expand All @@ -134,6 +134,16 @@ var _ = Describe("Fake client", func() {
Expect(list.Items).To(ConsistOf(*dep2))
})

It("should support filtering by label existence", func() {
By("Listing deployments with a particular label")
list := &appsv1.DeploymentList{}
err := cl.List(nil, list, client.InNamespace("ns1"),
client.ContainsLabels{"test-label"})
Expect(err).To(BeNil())
Expect(list.Items).To(HaveLen(1))
Expect(list.Items).To(ConsistOf(*dep2))
})

It("should be able to Create", func() {
By("Creating a new configmap")
newcm := &corev1.ConfigMap{
Expand Down
20 changes: 20 additions & 0 deletions pkg/client/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
)

// {{{ "Functional" Option Interfaces
Expand Down Expand Up @@ -388,6 +389,25 @@ func (m MatchingLabels) ApplyToDeleteAllOf(opts *DeleteAllOfOptions) {
m.ApplyToList(&opts.ListOptions)
}

// ContainsLabels filters the list/delete operation checking if the set of labels exists
// without checking their values.
type ContainsLabels []string

func (m ContainsLabels) ApplyToList(opts *ListOptions) {
sel := labels.NewSelector()
for _, label := range m {
r, err := labels.NewRequirement(label, selection.Exists, nil)
if err == nil {
sel = sel.Add(*r)
}
}
opts.LabelSelector = sel
}

func (m ContainsLabels) ApplyToDeleteAllOf(opts *DeleteAllOfOptions) {
m.ApplyToList(&opts.ListOptions)
}

// MatchingLabelsSelector filters the list/delete operation on the given label
// selector (or index in the case of cached lists). A struct is used because
// labels.Selector is an interface, which cannot be aliased.
Expand Down

0 comments on commit 72b0730

Please sign in to comment.