mirror of
https://github.com/opentofu/opentofu.git
synced 2024-12-30 10:47:14 -06:00
cb9ef298f3
The mapstructure library has a regrettable backward compatibility concern whereby a WeakDecode of []interface{}{} into a target of map[string]interface{} yields an empty map rather than an error. One possibility is to switch to using Decode instead of WeakDecode, but this loses the nice handling of type conversion, requiring a large volume of code to be added to Terraform or HIL in order to retain that behaviour. Instead we add a DecodeHook to our usage of the mapstructure library which checks for decoding []interface{}{} or []string{} into a map and returns an error instead. This has the effect of defeating the code added to retain backwards compatibility in mapstructure, giving us the correct (for our circumstances) behaviour of Decode for empty structures and the type conversion of WeakDecode. The code is identical to that in the HIL library, and packaged into a helper.
42 lines
1.3 KiB
Go
42 lines
1.3 KiB
Go
package hilmapstructure
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
|
|
"github.com/mitchellh/mapstructure"
|
|
)
|
|
|
|
var hilMapstructureDecodeHookEmptySlice []interface{}
|
|
var hilMapstructureDecodeHookStringSlice []string
|
|
var hilMapstructureDecodeHookEmptyMap map[string]interface{}
|
|
|
|
// WeakDecode behaves in the same way as mapstructure.WeakDecode but has a
|
|
// DecodeHook which defeats the backward compatibility mode of mapstructure
|
|
// which WeakDecodes []interface{}{} into an empty map[string]interface{}. This
|
|
// allows us to use WeakDecode (desirable), but not fail on empty lists.
|
|
func WeakDecode(m interface{}, rawVal interface{}) error {
|
|
config := &mapstructure.DecoderConfig{
|
|
DecodeHook: func(source reflect.Type, target reflect.Type, val interface{}) (interface{}, error) {
|
|
sliceType := reflect.TypeOf(hilMapstructureDecodeHookEmptySlice)
|
|
stringSliceType := reflect.TypeOf(hilMapstructureDecodeHookStringSlice)
|
|
mapType := reflect.TypeOf(hilMapstructureDecodeHookEmptyMap)
|
|
|
|
if (source == sliceType || source == stringSliceType) && target == mapType {
|
|
return nil, fmt.Errorf("Cannot convert a []interface{} into a map[string]interface{}")
|
|
}
|
|
|
|
return val, nil
|
|
},
|
|
WeaklyTypedInput: true,
|
|
Result: rawVal,
|
|
}
|
|
|
|
decoder, err := mapstructure.NewDecoder(config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return decoder.Decode(m)
|
|
}
|