From e46507655b4577bcfda0be6eb687a43987d7e84c Mon Sep 17 00:00:00 2001 From: wata_mac Date: Sat, 25 Mar 2017 15:04:48 +0900 Subject: [PATCH] Fix panic when parsing empty list --- evaluator/variable.go | 51 ++++++++++++++++++++++---------------- evaluator/variable_test.go | 11 ++++++++ 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/evaluator/variable.go b/evaluator/variable.go index ed6941b1e..83d45ae80 100644 --- a/evaluator/variable.go +++ b/evaluator/variable.go @@ -134,30 +134,37 @@ func parseVariable(val interface{}, varType string) hilast.Variable { case HCL_LIST_VARTYPE: s := reflect.ValueOf(val) - switch reflect.TypeOf(s.Index(0).Interface()).Kind() { - case reflect.Map: - var variables map[string]hilast.Variable - variables = map[string]hilast.Variable{} - for i := 0; i < s.Len(); i++ { - ms := reflect.ValueOf(s.Index(i).Interface()) - for _, k := range ms.MapKeys() { - key := k.Interface().(string) - value := ms.MapIndex(reflect.ValueOf(key)).Interface() - variables[key] = parseVariable(value, "") - } - } - hilVar = hilast.Variable{ - Type: hilast.TypeMap, - Value: variables, - } - default: - var variables []hilast.Variable - for i := 0; i < s.Len(); i++ { - variables = append(variables, parseVariable(s.Index(i).Interface(), "")) - } + if s.Len() == 0 { hilVar = hilast.Variable{ Type: hilast.TypeList, - Value: variables, + Value: []hilast.Variable{}, + } + } else { + switch reflect.TypeOf(s.Index(0).Interface()).Kind() { + case reflect.Map: + var variables map[string]hilast.Variable + variables = map[string]hilast.Variable{} + for i := 0; i < s.Len(); i++ { + ms := reflect.ValueOf(s.Index(i).Interface()) + for _, k := range ms.MapKeys() { + key := k.Interface().(string) + value := ms.MapIndex(reflect.ValueOf(key)).Interface() + variables[key] = parseVariable(value, "") + } + } + hilVar = hilast.Variable{ + Type: hilast.TypeMap, + Value: variables, + } + default: + var variables []hilast.Variable + for i := 0; i < s.Len(); i++ { + variables = append(variables, parseVariable(s.Index(i).Interface(), "")) + } + hilVar = hilast.Variable{ + Type: hilast.TypeList, + Value: variables, + } } } } diff --git a/evaluator/variable_test.go b/evaluator/variable_test.go index 59a00d3e0..7f31ca803 100644 --- a/evaluator/variable_test.go +++ b/evaluator/variable_test.go @@ -550,6 +550,17 @@ func TestParseVariable(t *testing.T) { }, }, }, + { + Name: "parse empty list", + Input: Input{ + Val: []string{}, + Type: "list", + }, + Result: hilast.Variable{ + Type: hilast.TypeList, + Value: []hilast.Variable{}, + }, + }, } for _, tc := range cases {