github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/helper/hilmapstructure/hilmapstructure.go (about)

     1  package hilmapstructure
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	"github.com/mitchellh/mapstructure"
     8  )
     9  
    10  var hilMapstructureDecodeHookEmptySlice []interface{}
    11  var hilMapstructureDecodeHookStringSlice []string
    12  var hilMapstructureDecodeHookEmptyMap map[string]interface{}
    13  
    14  // WeakDecode behaves in the same way as mapstructure.WeakDecode but has a
    15  // DecodeHook which defeats the backward compatibility mode of mapstructure
    16  // which WeakDecodes []interface{}{} into an empty map[string]interface{}. This
    17  // allows us to use WeakDecode (desirable), but not fail on empty lists.
    18  func WeakDecode(m interface{}, rawVal interface{}) error {
    19  	config := &mapstructure.DecoderConfig{
    20  		DecodeHook: func(source reflect.Type, target reflect.Type, val interface{}) (interface{}, error) {
    21  			sliceType := reflect.TypeOf(hilMapstructureDecodeHookEmptySlice)
    22  			stringSliceType := reflect.TypeOf(hilMapstructureDecodeHookStringSlice)
    23  			mapType := reflect.TypeOf(hilMapstructureDecodeHookEmptyMap)
    24  
    25  			if (source == sliceType || source == stringSliceType) && target == mapType {
    26  				return nil, fmt.Errorf("Cannot convert a []interface{} into a map[string]interface{}")
    27  			}
    28  
    29  			return val, nil
    30  		},
    31  		WeaklyTypedInput: true,
    32  		Result:           rawVal,
    33  	}
    34  
    35  	decoder, err := mapstructure.NewDecoder(config)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	return decoder.Decode(m)
    41  }