diff --git a/decoder/decoder.go b/decoder/decoder.go index 9ce700e1..24e07330 100644 --- a/decoder/decoder.go +++ b/decoder/decoder.go @@ -277,15 +277,15 @@ func traversalToAddress(traversal hcl.Traversal) (lang.Address, error) { addr := lang.Address{} for _, tr := range traversal { switch t := tr.(type) { - case *hcl.TraverseRoot: + case hcl.TraverseRoot: addr = append(addr, lang.RootStep{ Name: t.Name, }) - case *hcl.TraverseAttr: + case hcl.TraverseAttr: addr = append(addr, lang.AttrStep{ Name: t.Name, }) - case *hcl.TraverseIndex: + case hcl.TraverseIndex: addr = append(addr, lang.IndexStep{ Key: t.Key, }) diff --git a/decoder/decoder_test.go b/decoder/decoder_test.go index 227b0828..4019d9d9 100644 --- a/decoder/decoder_test.go +++ b/decoder/decoder_test.go @@ -1,10 +1,15 @@ package decoder import ( + "fmt" "testing" "github.com/google/go-cmp/cmp" + "github.com/hashicorp/hcl-lang/lang" "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclsyntax" + "github.com/zclconf/go-cty-debug/ctydebug" + "github.com/zclconf/go-cty/cty" ) func TestDecoder_LoadFile_nilFile(t *testing.T) { @@ -31,3 +36,56 @@ func TestDecoder_LoadFile_nilRootBody(t *testing.T) { t.Fatalf("unexpected error: %s", diff) } } + +func TestTraversalToAddress(t *testing.T) { + testCases := []struct { + rawTraversal string + expectedAddr lang.Address + }{ + { + "one", + lang.Address{ + lang.RootStep{Name: "one"}, + }, + }, + { + "first.second", + lang.Address{ + lang.RootStep{Name: "first"}, + lang.AttrStep{Name: "second"}, + }, + }, + { + "foo[2]", + lang.Address{ + lang.RootStep{Name: "foo"}, + lang.IndexStep{Key: cty.NumberIntVal(2)}, + }, + }, + { + `foo["bar"]`, + lang.Address{ + lang.RootStep{Name: "foo"}, + lang.IndexStep{Key: cty.StringVal("bar")}, + }, + }, + } + + for i, tc := range testCases { + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + traversal, diags := hclsyntax.ParseTraversalAbs([]byte(tc.rawTraversal), "test.tf", hcl.InitialPos) + if len(diags) > 0 { + t.Fatal(diags) + } + + addr, err := traversalToAddress(traversal) + if err != nil { + t.Fatal(err) + } + + if diff := cmp.Diff(tc.expectedAddr, addr, ctydebug.CmpOptions); diff != "" { + t.Fatalf("address mismatch: %s", diff) + } + }) + } +}