labels.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package v1
  14. // Clones the given selector and returns a new selector with the given key and value added.
  15. // Returns the given selector, if labelKey is empty.
  16. func CloneSelectorAndAddLabel(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {
  17. if labelKey == "" {
  18. // Don't need to add a label.
  19. return selector
  20. }
  21. // Clone.
  22. newSelector := selector.DeepCopy()
  23. if newSelector.MatchLabels == nil {
  24. newSelector.MatchLabels = make(map[string]string)
  25. }
  26. newSelector.MatchLabels[labelKey] = labelValue
  27. return newSelector
  28. }
  29. // AddLabelToSelector returns a selector with the given key and value added to the given selector's MatchLabels.
  30. func AddLabelToSelector(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {
  31. if labelKey == "" {
  32. // Don't need to add a label.
  33. return selector
  34. }
  35. if selector.MatchLabels == nil {
  36. selector.MatchLabels = make(map[string]string)
  37. }
  38. selector.MatchLabels[labelKey] = labelValue
  39. return selector
  40. }
  41. // SelectorHasLabel checks if the given selector contains the given label key in its MatchLabels
  42. func SelectorHasLabel(selector *LabelSelector, labelKey string) bool {
  43. return len(selector.MatchLabels[labelKey]) > 0
  44. }