Skip to content

Commit

Permalink
Fix squash not working when decoder config option is set and squash s…
Browse files Browse the repository at this point in the history
…truct tags are present
  • Loading branch information
kralicky committed Apr 20, 2022
1 parent b9b99d7 commit 7bbefaa
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
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

0 comments on commit 7bbefaa

Please sign in to comment.