fix todo: use selector.DeepCopy replace of hard code

This commit is contained in:
hangaoshuai 2018-02-07 19:09:05 +08:00
parent 531369d70e
commit 3cbd8e2132
2 changed files with 9 additions and 26 deletions

View File

@ -25,34 +25,14 @@ func CloneSelectorAndAddLabel(selector *LabelSelector, labelKey, labelValue stri
}
// Clone.
newSelector := new(LabelSelector)
newSelector := selector.DeepCopy()
// TODO(madhusudancs): Check if you can use deepCopy_extensions_LabelSelector here.
newSelector.MatchLabels = make(map[string]string)
if selector.MatchLabels != nil {
for key, val := range selector.MatchLabels {
newSelector.MatchLabels[key] = val
}
if newSelector.MatchLabels == nil {
newSelector.MatchLabels = make(map[string]string)
}
newSelector.MatchLabels[labelKey] = labelValue
if selector.MatchExpressions != nil {
newMExps := make([]LabelSelectorRequirement, len(selector.MatchExpressions))
for i, me := range selector.MatchExpressions {
newMExps[i].Key = me.Key
newMExps[i].Operator = me.Operator
if me.Values != nil {
newMExps[i].Values = make([]string, len(me.Values))
copy(newMExps[i].Values, me.Values)
} else {
newMExps[i].Values = nil
}
}
newSelector.MatchExpressions = newMExps
} else {
newSelector.MatchExpressions = nil
}
return newSelector
}

View File

@ -27,6 +27,9 @@ func TestCloneSelectorAndAddLabel(t *testing.T) {
"foo2": "bar2",
"foo3": "bar3",
}
matchExpressions := []LabelSelectorRequirement{
{Key: "foo", Operator: LabelSelectorOpIn, Values: []string{"foo"}},
}
cases := []struct {
labels map[string]string
@ -60,8 +63,8 @@ func TestCloneSelectorAndAddLabel(t *testing.T) {
}
for _, tc := range cases {
ls_in := LabelSelector{MatchLabels: tc.labels}
ls_out := LabelSelector{MatchLabels: tc.want}
ls_in := LabelSelector{MatchLabels: tc.labels, MatchExpressions: matchExpressions}
ls_out := LabelSelector{MatchLabels: tc.want, MatchExpressions: matchExpressions}
got := CloneSelectorAndAddLabel(&ls_in, tc.labelKey, tc.labelValue)
if !reflect.DeepEqual(got, &ls_out) {