1 /* 2 Copyright 2018 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 globalflag 18 19 import ( 20 "flag" 21 "fmt" 22 23 "github.com/spf13/pflag" 24 "k8s.io/component-base/logs" 25 ) 26 27 // AddGlobalFlags explicitly registers flags that libraries (klog, verflag, etc.) register 28 // against the global flagsets from "flag" and "k8s.io/klog/v2". 29 // We do this in order to prevent unwanted flags from leaking into the component's flagset. 30 // 31 // k8s.io/component-base/logs.SkipLoggingConfigurationFlags must be used as 32 // option when the program also uses a LoggingConfiguration struct for 33 // configuring logging. Then only flags not covered by that get added. 34 func AddGlobalFlags(fs *pflag.FlagSet, name string, opts ...logs.Option) { 35 logs.AddFlags(fs, opts...) 36 37 fs.BoolP("help", "h", false, fmt.Sprintf("help for %s", name)) 38 } 39 40 // Register adds a flag to local that targets the Value associated with the Flag named globalName in flag.CommandLine. 41 func Register(local *pflag.FlagSet, globalName string) { 42 if f := flag.CommandLine.Lookup(globalName); f != nil { 43 pflagFlag := pflag.PFlagFromGoFlag(f) 44 normalizeFunc := local.GetNormalizeFunc() 45 pflagFlag.Name = string(normalizeFunc(local, pflagFlag.Name)) 46 local.AddFlag(pflagFlag) 47 } else { 48 panic(fmt.Sprintf("failed to find flag in global flagset (flag): %s", globalName)) 49 } 50 } 51