...

Source file src/k8s.io/component-base/cli/flag/flags.go

Documentation: k8s.io/component-base/cli/flag

     1  /*
     2  Copyright 2014 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 flag
    18  
    19  import (
    20  	goflag "flag"
    21  	"strings"
    22  
    23  	"github.com/spf13/pflag"
    24  	"k8s.io/klog/v2"
    25  )
    26  
    27  var underscoreWarnings = make(map[string]bool)
    28  
    29  // WordSepNormalizeFunc changes all flags that contain "_" separators
    30  func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
    31  	if strings.Contains(name, "_") {
    32  		return pflag.NormalizedName(strings.Replace(name, "_", "-", -1))
    33  	}
    34  	return pflag.NormalizedName(name)
    35  }
    36  
    37  // WarnWordSepNormalizeFunc changes and warns for flags that contain "_" separators
    38  func WarnWordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
    39  	if strings.Contains(name, "_") {
    40  		nname := strings.Replace(name, "_", "-", -1)
    41  		if _, alreadyWarned := underscoreWarnings[name]; !alreadyWarned {
    42  			klog.Warningf("using an underscore in a flag name is not supported. %s has been converted to %s.", name, nname)
    43  			underscoreWarnings[name] = true
    44  		}
    45  
    46  		return pflag.NormalizedName(nname)
    47  	}
    48  	return pflag.NormalizedName(name)
    49  }
    50  
    51  // InitFlags normalizes, parses, then logs the command line flags
    52  func InitFlags() {
    53  	pflag.CommandLine.SetNormalizeFunc(WordSepNormalizeFunc)
    54  	pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)
    55  	pflag.Parse()
    56  	pflag.VisitAll(func(flag *pflag.Flag) {
    57  		klog.V(2).Infof("FLAG: --%s=%q", flag.Name, flag.Value)
    58  	})
    59  }
    60  
    61  // PrintFlags logs the flags in the flagset
    62  func PrintFlags(flags *pflag.FlagSet) {
    63  	flags.VisitAll(func(flag *pflag.Flag) {
    64  		klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value)
    65  	})
    66  }
    67  

View as plain text