Refactor '(default: …)' flag string into utility function

The usage of the `(default: …)` strings are a bit error prone so we now
refactor them into a dedicated helper function.

Signed-off-by: Sascha Grunert <sgrunert@suse.com>
This commit is contained in:
Sascha Grunert 2020-03-02 13:05:43 +01:00
parent 573004ad6a
commit 7742363500
No known key found for this signature in database
GPG Key ID: 8CE029DD1A866E52

14
flag.go
View File

@ -244,6 +244,10 @@ func flagValue(f Flag) reflect.Value {
return fv return fv
} }
func formatDefault(format string) string {
return " (default: " + format + ")"
}
func stringifyFlag(f Flag) string { func stringifyFlag(f Flag) string {
fv := flagValue(f) fv := flagValue(f)
@ -269,20 +273,20 @@ func stringifyFlag(f Flag) string {
val := fv.FieldByName("Value") val := fv.FieldByName("Value")
if val.IsValid() { if val.IsValid() {
needsPlaceholder = val.Kind() != reflect.Bool needsPlaceholder = val.Kind() != reflect.Bool
defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface()) defaultValueString = fmt.Sprintf(formatDefault("%v"), val.Interface())
if val.Kind() == reflect.String && val.String() != "" { if val.Kind() == reflect.String && val.String() != "" {
defaultValueString = fmt.Sprintf(" (default: %q)", val.String()) defaultValueString = fmt.Sprintf(formatDefault("%q"), val.String())
} }
} }
helpText := fv.FieldByName("DefaultText") helpText := fv.FieldByName("DefaultText")
if helpText.IsValid() && helpText.String() != "" { if helpText.IsValid() && helpText.String() != "" {
needsPlaceholder = val.Kind() != reflect.Bool needsPlaceholder = val.Kind() != reflect.Bool
defaultValueString = fmt.Sprintf(" (default: %s)", helpText.String()) defaultValueString = fmt.Sprintf(formatDefault("%s"), helpText.String())
} }
if defaultValueString == " (default: )" { if defaultValueString == formatDefault("") {
defaultValueString = "" defaultValueString = ""
} }
@ -351,7 +355,7 @@ func stringifySliceFlag(usage string, names, defaultVals []string) string {
defaultVal := "" defaultVal := ""
if len(defaultVals) > 0 { if len(defaultVals) > 0 {
defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", ")) defaultVal = fmt.Sprintf(formatDefault("%s"), strings.Join(defaultVals, ", "))
} }
usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal)) usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))