From 7bb335770392c7a626905c2bc3e07f32805b7389 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 14 Jul 2022 00:22:30 +0300 Subject: [PATCH] respect map's IncludableMap interface --- hashstructure.go | 9 ++++++--- hashstructure_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/hashstructure.go b/hashstructure.go index 3dc0eb7..5243e5d 100644 --- a/hashstructure.go +++ b/hashstructure.go @@ -233,9 +233,12 @@ func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) { case reflect.Map: var includeMap IncludableMap - if opts != nil && opts.Struct != nil { + var field string + if v, ok := v.Interface().(IncludableMap); ok { + includeMap = v + } else if opts != nil && opts.Struct != nil { if v, ok := opts.Struct.(IncludableMap); ok { - includeMap = v + includeMap, field = v, opts.StructField } } @@ -246,7 +249,7 @@ func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) { v := v.MapIndex(k) if includeMap != nil { incl, err := includeMap.HashIncludeMap( - opts.StructField, k.Interface(), v.Interface()) + field, k.Interface(), v.Interface()) if err != nil { return 0, err } diff --git a/hashstructure_test.go b/hashstructure_test.go index 7b0034a..03ccef9 100644 --- a/hashstructure_test.go +++ b/hashstructure_test.go @@ -577,6 +577,24 @@ func TestHash_includableMap(t *testing.T) { testIncludableMap{Map: map[string]string{"bar": "baz"}}, false, }, + + { + testIncludableMapMap{"foo": "bar"}, + testIncludableMapMap{"foo": "bar"}, + true, + }, + + { + testIncludableMapMap{"foo": "bar", "ignore": "true"}, + testIncludableMapMap{"foo": "bar"}, + true, + }, + + { + testIncludableMapMap{"foo": "bar", "ignore": "true"}, + testIncludableMapMap{"bar": "baz"}, + false, + }, } for _, tc := range cases { @@ -701,6 +719,12 @@ func (t testIncludableMap) HashIncludeMap(field string, k, v interface{}) (bool, return true, nil } +type testIncludableMapMap map[string]string + +func (t testIncludableMapMap) HashIncludeMap(_ string, k, _ interface{}) (bool, error) { + return k.(string) != "ignore", nil +} + type testHashable struct { Value string Err error