Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix squash not working when decoder config option is set and squash struct tags are present #280

Merged
merged 1 commit into from Apr 20, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion mapstructure.go
Expand Up @@ -920,7 +920,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
}

// If "squash" is specified in the tag, we squash the field down.
squash = !squash && strings.Index(tagValue[index+1:], "squash") != -1
squash = squash || strings.Index(tagValue[index+1:], "squash") != -1
if squash {
// When squashing, the embedded type can be a pointer to a struct.
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
Expand Down
47 changes: 47 additions & 0 deletions mapstructure_test.go
Expand Up @@ -812,6 +812,53 @@ func TestDecodeFrom_EmbeddedSquashConfig(t *testing.T) {
}
}

func TestDecodeFrom_EmbeddedSquashConfig_WithTags(t *testing.T) {
t.Parallel()

var v interface{}
var ok bool

input := EmbeddedSquash{
Basic: Basic{
Vstring: "foo",
},
Vunique: "bar",
}

result := map[string]interface{}{}
config := &DecoderConfig{
Squash: true,
Result: &result,
}
decoder, err := NewDecoder(config)
if err != nil {
t.Fatalf("got an err: %s", err.Error())
}

err = decoder.Decode(input)
if err != nil {
t.Fatalf("got an err: %s", err.Error())
}

if _, ok = result["Basic"]; ok {
t.Error("basic should not be present in map")
}

v, ok = result["Vstring"]
if !ok {
t.Error("vstring should be present in map")
} else if !reflect.DeepEqual(v, "foo") {
t.Errorf("vstring value should be 'foo': %#v", v)
}

v, ok = result["Vunique"]
if !ok {
t.Error("vunique should be present in map")
} else if !reflect.DeepEqual(v, "bar") {
t.Errorf("vunique value should be 'bar': %#v", v)
}
}

func TestDecode_SquashOnNonStructType(t *testing.T) {
t.Parallel()

Expand Down