From 85c7126bbd77ee464c557874a002d9ad5ba044aa Mon Sep 17 00:00:00 2001 From: andig Date: Thu, 2 Mar 2023 15:51:19 +0100 Subject: [PATCH] Fix rendering nil interfaces as "" string --- util/decoder_test.go | 36 ++++++++++++++++++++++++++++++++++++ util/templates/template.go | 7 ++++++- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 util/decoder_test.go diff --git a/util/decoder_test.go b/util/decoder_test.go new file mode 100644 index 000000000..b78eb42c5 --- /dev/null +++ b/util/decoder_test.go @@ -0,0 +1,36 @@ +package util + +import ( + "testing" + + "github.com/mitchellh/mapstructure" + "github.com/stretchr/testify/assert" +) + +func TestDecodeNil(t *testing.T) { + var dst struct { + User, Password string + } + + decoderConfig := &mapstructure.DecoderConfig{ + Result: &dst, + ErrorUnused: true, + WeaklyTypedInput: true, + DecodeHook: mapstructure.ComposeDecodeHookFunc( + mapstructure.StringToTimeDurationHookFunc(), + mapstructure.TextUnmarshallerHookFunc(), + ), + } + + decoder, err := mapstructure.NewDecoder(decoderConfig) + assert.NoError(t, err) + + err = decoder.Decode(map[string]any{ + "user": nil, + }) + assert.NoError(t, err) + + assert.Equal(t, struct { + User, Password string + }{}, dst) +} diff --git a/util/templates/template.go b/util/templates/template.go index 2a9230680..1982e7b0c 100644 --- a/util/templates/template.go +++ b/util/templates/template.go @@ -323,7 +323,12 @@ func (t *Template) RenderResult(renderMode string, other map[string]interface{}) default: if res[out] == nil || res[out].(string) == "" { - res[out] = yamlQuote(fmt.Sprintf("%v", val)) + // prevent rendering nil interfaces as "" string + var s string + if val != nil { + s = yamlQuote(fmt.Sprintf("%v", val)) + } + res[out] = s } } }