Skip to content

Commit a083a52

Browse files
committed
Add metav1.SetMetaDataLabel func
Signed-off-by: ialidzhikov <[email protected]>
1 parent 19f0a54 commit a083a52

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,20 @@ func SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string) {
201201
obj.Annotations[ann] = value
202202
}
203203

204+
// HasLabel returns a bool if passed in label exists
205+
func HasLabel(obj ObjectMeta, label string) bool {
206+
_, found := obj.Labels[label]
207+
return found
208+
}
209+
210+
// SetMetaDataLabel sets the label and value
211+
func SetMetaDataLabel(obj *ObjectMeta, label string, value string) {
212+
if obj.Labels == nil {
213+
obj.Labels = make(map[string]string)
214+
}
215+
obj.Labels[label] = value
216+
}
217+
204218
// SingleObject returns a ListOptions for watching a single object.
205219
func SingleObject(meta ObjectMeta) ListOptions {
206220
return ListOptions{

staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,38 @@ func TestResetObjectMetaForStatus(t *testing.T) {
195195
t.Error(diff.ObjectDiff(meta, existingMeta))
196196
}
197197
}
198+
199+
func TestSetMetaDataLabel(t *testing.T) {
200+
tests := []struct {
201+
obj *ObjectMeta
202+
label string
203+
value string
204+
want map[string]string
205+
}{
206+
{
207+
obj: &ObjectMeta{},
208+
label: "foo",
209+
value: "bar",
210+
want: map[string]string{"foo": "bar"},
211+
},
212+
{
213+
obj: &ObjectMeta{Labels: map[string]string{"foo": "bar"}},
214+
label: "foo",
215+
value: "baz",
216+
want: map[string]string{"foo": "baz"},
217+
},
218+
{
219+
obj: &ObjectMeta{Labels: map[string]string{"foo": "bar"}},
220+
label: "version",
221+
value: "1.0.0",
222+
want: map[string]string{"foo": "bar", "version": "1.0.0"},
223+
},
224+
}
225+
226+
for _, tc := range tests {
227+
SetMetaDataLabel(tc.obj, tc.label, tc.value)
228+
if !reflect.DeepEqual(tc.obj.Labels, tc.want) {
229+
t.Errorf("got %v, want %v", tc.obj.Labels, tc.want)
230+
}
231+
}
232+
}

0 commit comments

Comments
 (0)