github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/apis/meta/v1/labels.go (about)

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