k8s.io/component-base/logs: fix usage through Go flag package

api/v1.AddFlags only supports a pflag.FlagSet. The assumption was that code
which wants to use flag.FlagSet can use VisitAll to copy the flags. That works,
with one caveat: the flag.FlagSet help implementation will call String for the
zero value to determine whether the flag has a non-default value. This
currently leads to additional warnings at the end of the -help output:

     panic calling String method on zero v1.verbosityLevelPflag for flag v: runtime error: invalid memory address or nil pointer dereference
     panic calling String method on zero v1.vmoduleConfigurationPFlag for flag vmodule: runtime error: invalid memory address or nil pointer dereference

Supporting usage of methods with the zero value is good practice anyway and
thus gets added. This then avoids these panics.
This commit is contained in:
Patrick Ohly 2022-12-23 17:10:42 +01:00
parent 8a71485643
commit 8bcf26b575

View File

@ -36,6 +36,9 @@ type vmoduleConfigurationPFlag struct {
// String returns the -vmodule parameter (comma-separated list of pattern=N).
func (wrapper vmoduleConfigurationPFlag) String() string {
if wrapper.value == nil {
return ""
}
var patterns []string
for _, item := range *wrapper.value {
patterns = append(patterns, fmt.Sprintf("%s=%d", item.FilePattern, item.Verbosity))
@ -82,10 +85,16 @@ type verbosityLevelPflag struct {
}
func (wrapper verbosityLevelPflag) String() string {
if wrapper.value == nil {
return "0"
}
return strconv.FormatInt(int64(*wrapper.value), 10)
}
func (wrapper verbosityLevelPflag) Get() interface{} {
if wrapper.value == nil {
return VerbosityLevel(0)
}
return *wrapper.value
}