From 5a52c9fb37d519ce70bc6ac27940ea664e03443d Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 28 Nov 2024 14:37:49 +0200 Subject: [PATCH] feat: respect map HashIncludeMap --- hashstructure.go | 11 +++++++---- hashstructure_test.go | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/hashstructure.go b/hashstructure.go index 651f840..8c107f4 100644 --- a/hashstructure.go +++ b/hashstructure.go @@ -206,9 +206,13 @@ 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 } } @@ -218,8 +222,7 @@ func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) { for _, k := range v.MapKeys() { v := v.MapIndex(k) if includeMap != nil { - incl, err := includeMap.HashIncludeMap( - opts.StructField, k.Interface(), v.Interface()) + incl, err := includeMap.HashIncludeMap(field, k.Interface(), v.Interface()) if err != nil { return 0, err } diff --git a/hashstructure_test.go b/hashstructure_test.go index 0b35af2..aa84422 100644 --- a/hashstructure_test.go +++ b/hashstructure_test.go @@ -576,6 +576,23 @@ 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 { @@ -728,3 +745,9 @@ func (t *testHashablePointer) Hash() (uint64, error) { return 100, nil } + +type testIncludableMapMap map[string]string + +func (t testIncludableMapMap) HashIncludeMap(_ string, k, _ interface{}) (bool, error) { + return k.(string) != "ignore", nil +}