...

Source file src/k8s.io/kubectl/pkg/util/fieldpath/fieldpath.go

Documentation: k8s.io/kubectl/pkg/util/fieldpath

     1  /*
     2  Copyright 2015 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 fieldpath
    18  
    19  import (
    20  	"fmt"
    21  	"strings"
    22  
    23  	"k8s.io/apimachinery/pkg/api/meta"
    24  	"k8s.io/apimachinery/pkg/util/sets"
    25  	"k8s.io/apimachinery/pkg/util/validation"
    26  )
    27  
    28  // TODO(yue9944882): Remove this helper package once it's copied to k/apimachinery
    29  
    30  // FormatMap formats map[string]string to a string.
    31  func FormatMap(m map[string]string) (fmtStr string) {
    32  	// output with keys in sorted order to provide stable output
    33  	keys := sets.NewString()
    34  	for key := range m {
    35  		keys.Insert(key)
    36  	}
    37  	for _, key := range keys.List() {
    38  		fmtStr += fmt.Sprintf("%v=%q\n", key, m[key])
    39  	}
    40  	fmtStr = strings.TrimSuffix(fmtStr, "\n")
    41  
    42  	return
    43  }
    44  
    45  // ExtractFieldPathAsString extracts the field from the given object
    46  // and returns it as a string.  The object must be a pointer to an
    47  // API type.
    48  func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error) {
    49  	accessor, err := meta.Accessor(obj)
    50  	if err != nil {
    51  		return "", nil
    52  	}
    53  
    54  	if path, subscript, ok := SplitMaybeSubscriptedPath(fieldPath); ok {
    55  		switch path {
    56  		case "metadata.annotations":
    57  			if errs := validation.IsQualifiedName(strings.ToLower(subscript)); len(errs) != 0 {
    58  				return "", fmt.Errorf("invalid key subscript in %s: %s", fieldPath, strings.Join(errs, ";"))
    59  			}
    60  			return accessor.GetAnnotations()[subscript], nil
    61  		case "metadata.labels":
    62  			if errs := validation.IsQualifiedName(subscript); len(errs) != 0 {
    63  				return "", fmt.Errorf("invalid key subscript in %s: %s", fieldPath, strings.Join(errs, ";"))
    64  			}
    65  			return accessor.GetLabels()[subscript], nil
    66  		default:
    67  			return "", fmt.Errorf("fieldPath %q does not support subscript", fieldPath)
    68  		}
    69  	}
    70  
    71  	switch fieldPath {
    72  	case "metadata.annotations":
    73  		return FormatMap(accessor.GetAnnotations()), nil
    74  	case "metadata.labels":
    75  		return FormatMap(accessor.GetLabels()), nil
    76  	case "metadata.name":
    77  		return accessor.GetName(), nil
    78  	case "metadata.namespace":
    79  		return accessor.GetNamespace(), nil
    80  	case "metadata.uid":
    81  		return string(accessor.GetUID()), nil
    82  	}
    83  
    84  	return "", fmt.Errorf("unsupported fieldPath: %v", fieldPath)
    85  }
    86  
    87  // SplitMaybeSubscriptedPath checks whether the specified fieldPath is
    88  // subscripted, and
    89  //   - if yes, this function splits the fieldPath into path and subscript, and
    90  //     returns (path, subscript, true).
    91  //   - if no, this function returns (fieldPath, "", false).
    92  //
    93  // Example inputs and outputs:
    94  //
    95  //	"metadata.annotations['myKey']" --> ("metadata.annotations", "myKey", true)
    96  //	"metadata.annotations['a[b]c']" --> ("metadata.annotations", "a[b]c", true)
    97  //	"metadata.labels['']"           --> ("metadata.labels", "", true)
    98  //	"metadata.labels"               --> ("metadata.labels", "", false)
    99  func SplitMaybeSubscriptedPath(fieldPath string) (string, string, bool) {
   100  	if !strings.HasSuffix(fieldPath, "']") {
   101  		return fieldPath, "", false
   102  	}
   103  	s := strings.TrimSuffix(fieldPath, "']")
   104  	parts := strings.SplitN(s, "['", 2)
   105  	if len(parts) < 2 {
   106  		return fieldPath, "", false
   107  	}
   108  	if len(parts[0]) == 0 {
   109  		return fieldPath, "", false
   110  	}
   111  	return parts[0], parts[1], true
   112  }
   113  

View as plain text