Skip to content

Commit a4cad4d

Browse files
committed
config: fix Duration formatting in generated config
The config generator uses fmt.Sprint() on field values, which prints Duration as a raw nanosecond integer instead of the human-readable form like "30d". Check for fmt.Stringer and use String() when available. Also fix formatValue() and zeroValue() to quote Stringer types as strings instead of treating them as integers. Signed-off-by: Robin Jarry <robin@jarry.cc>
1 parent 44c396b commit a4cad4d

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

‎pkg/config/generate.go‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,11 @@ func writeField(w io.Writer, typeName string, field reflect.StructField, val ref
8484
active := ""
8585

8686
if !val.IsZero() {
87-
active = fmt.Sprint(val.Interface())
87+
if s, ok := val.Interface().(fmt.Stringer); ok {
88+
active = s.String()
89+
} else {
90+
active = fmt.Sprint(val.Interface())
91+
}
8892
} else if def := field.Tag.Get("default"); def != "" {
8993
active = def
9094
}
@@ -109,20 +113,26 @@ func writeField(w io.Writer, typeName string, field reflect.StructField, val ref
109113
}
110114
}
111115

116+
var stringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
117+
112118
func formatValue(t reflect.Type, val string) string {
113-
switch t.Kind() {
114-
case reflect.Bool, reflect.Int, reflect.Int64:
119+
switch {
120+
case t.Implements(stringerType):
121+
return fmt.Sprintf("%q", val)
122+
case t.Kind() == reflect.Bool, t.Kind() == reflect.Int, t.Kind() == reflect.Int64:
115123
return val
116124
default:
117125
return fmt.Sprintf("%q", val)
118126
}
119127
}
120128

121129
func zeroValue(t reflect.Type) string {
122-
switch t.Kind() {
123-
case reflect.Bool:
130+
switch {
131+
case t.Implements(stringerType):
132+
return `""`
133+
case t.Kind() == reflect.Bool:
124134
return "false"
125-
case reflect.Int, reflect.Int64:
135+
case t.Kind() == reflect.Int, t.Kind() == reflect.Int64:
126136
return "0"
127137
default:
128138
return `""`

0 commit comments

Comments
 (0)