sigs.k8s.io/cluster-api@v1.7.1/util/labels/format/helpers.go (about)

     1  /*
     2  Copyright 2021 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 format contains functions to format and compare formatted values used in Kubernetes labels.
    18  package format
    19  
    20  import (
    21  	"encoding/base64"
    22  	"fmt"
    23  	"hash/fnv"
    24  
    25  	"k8s.io/apimachinery/pkg/util/validation"
    26  )
    27  
    28  // MustFormatValue returns the passed inputLabelValue if it meets the standards for a Kubernetes label value.
    29  // If the name is not a valid label value this function returns a hash which meets the requirements.
    30  func MustFormatValue(str string) string {
    31  	// a valid Kubernetes label value must:
    32  	// - be less than 64 characters long.
    33  	// - be an empty string OR consist of alphanumeric characters, '-', '_' or '.'.
    34  	// - start and end with an alphanumeric character
    35  	if len(validation.IsValidLabelValue(str)) == 0 {
    36  		return str
    37  	}
    38  	hasher := fnv.New32a()
    39  	_, err := hasher.Write([]byte(str))
    40  	if err != nil {
    41  		// At time of writing the implementation of fnv's Write function can never return an error.
    42  		// If this changes in a future go version this function will panic.
    43  		panic(err)
    44  	}
    45  	return fmt.Sprintf("hash_%s_z", base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hasher.Sum(nil)))
    46  }
    47  
    48  // MustEqualValue returns true if the actualLabelValue equals either the inputLabelValue or the hashed
    49  // value of the inputLabelValue.
    50  func MustEqualValue(str, labelValue string) bool {
    51  	return labelValue == MustFormatValue(str)
    52  }