Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement gohcl.EvalContext #569

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions gohcl/eval_context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package gohcl

import (
"bytes"
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
"reflect"
)

// EvalContext constructs an expression evaluation context from a Go struct value,
// making the fields available as variables and the methods available as functions,
// after transforming the field and method names such that each word (starting with
// an uppercase letter) is all lowercase and separated by underscores.
//
// Cause of Functions variable are implemented by special stdlib functions,
// this function could not evaluation golang native function variable
func EvalContext(v interface{}) *hcl.EvalContext {
return &hcl.EvalContext{
Variables: structMapVal(v),
}
}

// structMapVal use reflect to traverse the struct,
// input could be a pointer,it would check the source
// struct, and return a map of cty.Value.
func structMapVal(v interface{}) map[string]cty.Value {
rt := reflect.TypeOf(v)
rv := reflect.ValueOf(v)

if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}

var variables = make(map[string]cty.Value)

for index := 0; index < rt.NumField(); index++ {
key := rt.Field(index)
value := rv.Field(index)

if !value.IsZero() {
k := marshalKey(key.Name)
refVal, err := reflectVal(value)
if err == nil {
variables[k] = refVal
}
}

}
return variables

}

// reflectVal receive a reflect.Value and according to the kind implemented,
// return a cty.Value. The value kind that have been implemented so far are
// Int/Uint, Float, String, and nest Struct and Slice
func reflectVal(v reflect.Value) (cty.Value, error) {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return cty.NumberIntVal(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return cty.NumberUIntVal(v.Uint()), nil
case reflect.Float32, reflect.Float64:
return cty.NumberFloatVal(v.Float()), nil
case reflect.String:
return cty.StringVal(v.String()), nil
case reflect.Struct:
return structVal(v)
case reflect.Slice:
return listVal(v)
case reflect.Map:
return mapVal(v)
default:
return cty.EmptyObjectVal, fmt.Errorf("target value must be pointer to number, string, slice, struct or map, not %s", v.String())
}
}

func mapVal(v reflect.Value) (cty.Value, error) {
var mapVar = make(map[string]cty.Value)
kind := v.Type().Key().Kind()
if kind == reflect.String {
iter := v.MapRange()
for iter.Next() {
refVal, err := reflectVal(iter.Value())
if err == nil {
mapVar[marshalKey(iter.Key().String())] = refVal
}
}
if len(mapVar) > 0 {
return cty.MapVal(mapVar), nil
}
return cty.EmptyObjectVal, fmt.Errorf("target map error or is empty")
}
return cty.EmptyObjectVal, fmt.Errorf("target key should be string, %s is not support", kind.String())
}

// listVal receive a reflect.Value which should be asserted as Slice type.
// In the for loop, each var would be called by func reflectVal to return
// a cty.Value and add into a slice.Finally return cty.ListVal
func listVal(v reflect.Value) (cty.Value, error) {
elems := []cty.Value{}
for i := 0; i < v.Len(); i++ {
refVal, err := reflectVal(v.Index(i))
if err == nil {
elems = append(elems, refVal)
}
}
if len(elems) > 0 {
return cty.ListVal(elems), nil
}
return cty.EmptyTupleVal, fmt.Errorf(" slice is empty, cty.ListVal must not call ListVal with empty slice")
}

// structVal received a reflect.Value which should be asserted as Struct type.
// It uses the NumFiled() of reflect type to loop all struct fields,
// and return cty.MapVal

func structVal(v reflect.Value) (cty.Value, error) {
var ctyVals = make(map[string]cty.Value)
for index := 0; index < v.Type().NumField(); index++ {
key := v.Type().Field(index)
value := v.Field(index)
refVal, err := reflectVal(value)
if err == nil {
ctyVals[marshalKey(key.Name)] = refVal
}
}
if len(ctyVals) > 0 {
return cty.MapVal(ctyVals), nil
}
return cty.EmptyObjectVal, fmt.Errorf(" slice is empty, cty.ListVal must not call ListVal with empty map")
}

// marshalKey trans camelcase to lowercase with separated by underscores
func marshalKey(input string) string {
if input == "" {
return ""
}
var output bytes.Buffer
for index, letter := range input {
if letter < 96 {
letter = letter + 32
if index > 0 {
output.WriteString("_")
}

}
output.WriteRune(letter)
}
return output.String()
}
137 changes: 137 additions & 0 deletions gohcl/eval_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package gohcl

import (
"bytes"
"fmt"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
"testing"
)

var (
valueComparer = cmp.Comparer(cty.Value.RawEquals)
)

func TestEvalContext(t *testing.T) {

type ServiceConfig struct {
Type string `hcl:"type,label"`
Name string `hcl:"name,label"`
ListenAddr string `hcl:"listen_addr"`
}
type Config struct {
IOMode string `hcl:"io_mode"`
Services []ServiceConfig `hcl:"service,block"`
}

type Context struct {
Pid string
}

tests := []struct {
Input interface{}
Output hcl.EvalContext
}{
{
Input: &Context{
Pid: "fake-pid",
},
Output: hcl.EvalContext{
Variables: map[string]cty.Value{
"pid": cty.StringVal("fake-pid"),
},
},
},
{
Input: &Config{
IOMode: "fake-mode",
Services: []ServiceConfig{
{
Type: "t",
Name: "n",
ListenAddr: "addr",
},
},
},
Output: hcl.EvalContext{
Variables: map[string]cty.Value{
"i_o_mode": cty.StringVal("fake-mode"),
"services": cty.ListVal([]cty.Value{
cty.MapVal(map[string]cty.Value{
"type": cty.StringVal("t"),
"name": cty.StringVal("n"),
"listen_addr": cty.StringVal("addr"),
}),
}),
},
},
},
{
Input: struct {
HashMap map[string]string
}{
HashMap: map[string]string{
"a": "b",
"c": "d",
},
},
Output: hcl.EvalContext{Variables: map[string]cty.Value{
"hash_map": cty.MapVal(map[string]cty.Value{
"a": cty.StringVal("b"),
"c": cty.StringVal("d"),
}),
}},
},
{
Input: struct {
HashMap map[string]string
}{
HashMap: map[string]string{},
},
Output: hcl.EvalContext{Variables: map[string]cty.Value{}},
},
{
Input: struct {
Array []string
}{
Array: []string{"elem-1", "elem-2"},
},
Output: hcl.EvalContext{Variables: map[string]cty.Value{
"array": cty.ListVal(
[]cty.Value{
cty.StringVal("elem-1"),
cty.StringVal("elem-2"),
}),
}},
},
{
Input: struct {
Array []string
}{
Array: []string{},
},
Output: hcl.EvalContext{Variables: map[string]cty.Value{}},
},
}

for index, test := range tests {
t.Run(fmt.Sprintf("test-%d", index), func(t *testing.T) {
realOutput := EvalContext(test.Input)

gotVal := realOutput.Variables
wantVal := test.Output.Variables

if !cmp.Equal(gotVal, wantVal, valueComparer) {
diff := cmp.Diff(gotVal, wantVal, cmp.Comparer(func(a, b []byte) bool {
return bytes.Equal(a, b)
}))
t.Errorf(
"wrong result\nvalue: %#v\ngot: %#v\nwant: %#v\ndiff: %s",
test.Input, gotVal, wantVal, diff,
)
}

})
}
}