Skip to content

Commit 85877d7

Browse files
omerap12chethanuk
authored andcommitted
[MISC] Refactor labels.go & add unit tests (vllm-project#1563)
* [MISC] Refactor labels.go & add unit tests Signed-off-by: Omer Aplatony <[email protected]> * adjust comments Signed-off-by: Omer Aplatony <[email protected]> * adjust comments Signed-off-by: Omer Aplatony <[email protected]> --------- Signed-off-by: Omer Aplatony <[email protected]> Signed-off-by: ChethanUK <[email protected]>
1 parent 7b057cf commit 85877d7

File tree

2 files changed

+414
-26
lines changed

2 files changed

+414
-26
lines changed

pkg/utils/labels.go

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -65,42 +65,29 @@ func AddLabel(labels map[string]string, labelKey, labelValue string) map[string]
6565
return labels
6666
}
6767

68-
// Clones the given selector and returns a new selector with the given key and value added.
68+
// Use DeepCopy to clone the selector, or create new one if nil
6969
// Returns the given selector, if labelKey is empty.
7070
func CloneSelectorAndAddLabel(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector {
7171
if labelKey == "" {
7272
// Don't need to add a label.
7373
return selector
7474
}
7575

76-
// Clone.
77-
newSelector := new(metav1.LabelSelector)
78-
79-
// TODO(madhusudancs): Check if you can use deepCopy_extensions_LabelSelector here.
80-
newSelector.MatchLabels = make(map[string]string)
81-
if selector.MatchLabels != nil {
82-
for key, val := range selector.MatchLabels {
83-
newSelector.MatchLabels[key] = val
84-
}
76+
// Use DeepCopy to clone the selector
77+
var newSelector *metav1.LabelSelector
78+
if selector != nil {
79+
newSelector = selector.DeepCopy()
80+
} else {
81+
newSelector = &metav1.LabelSelector{}
8582
}
86-
newSelector.MatchLabels[labelKey] = labelValue
8783

88-
if selector.MatchExpressions != nil {
89-
newMExps := make([]metav1.LabelSelectorRequirement, len(selector.MatchExpressions))
90-
for i, me := range selector.MatchExpressions {
91-
newMExps[i].Key = me.Key
92-
newMExps[i].Operator = me.Operator
93-
if me.Values != nil {
94-
newMExps[i].Values = make([]string, len(me.Values))
95-
copy(newMExps[i].Values, me.Values)
96-
} else {
97-
newMExps[i].Values = nil
98-
}
99-
}
100-
newSelector.MatchExpressions = newMExps
101-
} else {
102-
newSelector.MatchExpressions = nil
84+
// Initialize MatchLabels if nil
85+
if newSelector.MatchLabels == nil {
86+
newSelector.MatchLabels = make(map[string]string)
10387
}
10488

89+
// Add the new label
90+
newSelector.MatchLabels[labelKey] = labelValue
91+
10592
return newSelector
10693
}

0 commit comments

Comments
 (0)