knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/kmap/lookup.go (about)

     1  /*
     2  Copyright 2021 The Knative 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 kmap
    18  
    19  // KeyPriority is a utility struct for getting values from a map
    20  // given a list of ordered keys
    21  //
    22  // This is to help the migration/renaming of annotations & labels
    23  type KeyPriority []string
    24  
    25  // Key returns the default key that should be used for
    26  // accessing the map
    27  func (p KeyPriority) Key() string {
    28  	// this intentionally panics rather than returning an empty string
    29  	return p[0]
    30  }
    31  
    32  // Value iterates looks up the ordered keys in the map and returns
    33  // a string value. An empty string will be returned if the keys
    34  // are not present in the map
    35  func (p KeyPriority) Value(m map[string]string) string {
    36  	_, v, _ := p.Get(m)
    37  	return v
    38  }
    39  
    40  // Get iterates over the ordered keys and looks up the corresponding
    41  // values in the map
    42  //
    43  // It returns the key, value, and true|false signaling whether the
    44  // key was present in the map
    45  //
    46  // If no key is present the default key (lowest ordinal) is returned
    47  // with an empty string as the value
    48  func (p KeyPriority) Get(m map[string]string) (string, string, bool) {
    49  	var k, v string
    50  	var ok bool
    51  	for _, k = range p {
    52  		v, ok = m[k]
    53  		if ok {
    54  			return k, v, ok
    55  		}
    56  	}
    57  
    58  	return p.Key(), "", false
    59  }
    60  
    61  // UpdateKey will update the map with the KeyPriority's default
    62  // key iff any of the other synonym keys are present
    63  func (p KeyPriority) UpdateKey(m map[string]string) {
    64  	if k, v, ok := p.Get(m); ok && k != p.Key() {
    65  		delete(m, k)
    66  		m[p.Key()] = v
    67  	}
    68  }
    69  
    70  // UpdateKeys iterates over the lookups and updates entries in the map
    71  // to use the default key
    72  func UpdateKeys(m map[string]string, keys ...KeyPriority) map[string]string {
    73  	for _, key := range keys {
    74  		key.UpdateKey(m)
    75  	}
    76  	return m
    77  }