Skip to content

Commit

Permalink
Decode into flat structures for objects
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Aug 3, 2014
1 parent 58215e2 commit 96e92c5
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 2 deletions.
4 changes: 3 additions & 1 deletion Makefile
@@ -1,10 +1,12 @@
TEST?=./...

default: test

fmt: hcl/y.go json/y.go
go fmt ./...

test: hcl/y.go json/y.go
go test ./...
go test $(TEST) $(TESTARGS)

hcl/y.go: hcl/parse.y
cd hcl && \
Expand Down
19 changes: 18 additions & 1 deletion decoder.go
Expand Up @@ -3,6 +3,7 @@ package hcl
import (
"fmt"
"reflect"
"strconv"

"github.com/hashicorp/hcl/ast"
)
Expand Down Expand Up @@ -145,6 +146,19 @@ func (d *decoder) decodeInterface(name string, raw ast.Node, result reflect.Valu
}

func (d *decoder) decodeMap(name string, raw ast.Node, result reflect.Value) error {
// If we have a list, then we decode each element into a map
if list, ok := raw.(ast.ListNode); ok {
for i, elem := range list.Elem {
fieldName := fmt.Sprintf("%s.%d", name, i)
err := d.decode(fieldName, elem, result)
if err != nil {
return err
}
}

return nil
}

obj, ok := raw.(ast.ObjectNode)
if !ok {
return fmt.Errorf("%s: not an object type", name)
Expand Down Expand Up @@ -257,10 +271,13 @@ func (d *decoder) decodeString(name string, raw ast.Node, result reflect.Value)
}

switch n.Type {
case ast.ValueTypeInt:
result.Set(reflect.ValueOf(
strconv.FormatInt(int64(n.Value.(int)), 10)))
case ast.ValueTypeString:
result.Set(reflect.ValueOf(n.Value.(string)))
default:
return fmt.Errorf("%s: unknown type %s", name, n.Type)
return fmt.Errorf("%s: unknown type to string: %s", name, n.Type)
}

return nil
Expand Down
20 changes: 20 additions & 0 deletions decoder_test.go
Expand Up @@ -117,3 +117,23 @@ func TestDecode_equal(t *testing.T) {
}
}
}

func TestDecode_flatMap(t *testing.T) {
var val map[string]map[string]string

err := Decode(&val, testReadFile(t, "structure_flatmap.hcl"))
if err != nil {
t.Fatalf("err: %s", err)
}

expected := map[string]map[string]string{
"foo": map[string]string{
"foo": "bar",
"key": "7",
},
}

if !reflect.DeepEqual(val, expected) {
t.Fatalf("Actual: %#v\n\nExpected: %#v", val, expected)
}
}
15 changes: 15 additions & 0 deletions hcl_test.go
@@ -1,4 +1,19 @@
package hcl

import (
"io/ioutil"
"path/filepath"
"testing"
)

// This is the directory where our test fixtures are.
const fixtureDir = "./test-fixtures"

func testReadFile(t *testing.T, n string) string {
d, err := ioutil.ReadFile(filepath.Join(fixtureDir, n))
if err != nil {
t.Fatalf("err: %s", err)
}

return string(d)
}
7 changes: 7 additions & 0 deletions test-fixtures/structure_flatmap.hcl
@@ -0,0 +1,7 @@
foo {
key = 7
}

foo {
foo = "bar"
}

0 comments on commit 96e92c5

Please sign in to comment.