Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,29 @@ func StringToSliceHookFunc(sep string) DecodeHookFunc {
}
}

// StringToWeakSliceHookFunc brings back the old (pre-v2) behavior of [StringToSliceHookFunc].
//
// As of mapstructure v2.0.0 [StringToSliceHookFunc] checks if the return type is a string slice.
// This function removes that check.
func StringToWeakSliceHookFunc(sep string) DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data any,
) (any, error) {
if f.Kind() != reflect.String || t.Kind() != reflect.Slice {
return data, nil
}

raw := data.(string)
if raw == "" {
return []string{}, nil
}

return strings.Split(raw, sep), nil
}
}

// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
// strings to time.Duration.
func StringToTimeDurationHookFunc() DecodeHookFunc {
Expand Down
57 changes: 57 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,63 @@ func TestStringToSliceHookFunc(t *testing.T) {
})
}

func TestStringToWeakSliceHookFunc(t *testing.T) {
f := StringToWeakSliceHookFunc(",")

strValue := reflect.ValueOf("42")
sliceValue := reflect.ValueOf([]string{"42"})
sliceValue2 := reflect.ValueOf([]byte("42"))

cases := []struct {
f, t reflect.Value
result any
err bool
}{
{sliceValue, sliceValue, []string{"42"}, false},
{sliceValue2, sliceValue2, []byte("42"), false},
{reflect.ValueOf([]byte("42")), reflect.ValueOf([]byte{}), []byte("42"), false},
{strValue, strValue, "42", false},
{
reflect.ValueOf("foo,bar,baz"),
sliceValue,
[]string{"foo", "bar", "baz"},
false,
},
{
reflect.ValueOf("foo,bar,baz"),
sliceValue2,
[]string{"foo", "bar", "baz"},
false,
},
{
reflect.ValueOf(""),
sliceValue,
[]string{},
false,
},
{
reflect.ValueOf(""),
sliceValue2,
[]string{},
false,
},
}

for i, tc := range cases {
actual, err := DecodeHookExec(f, tc.f, tc.t)

if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}

if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}

func TestStringToTimeDurationHookFunc(t *testing.T) {
suite := decodeHookTestSuite[string, time.Duration]{
fn: StringToTimeDurationHookFunc(),
Expand Down
Loading