Skip to content
This repository has been archived by the owner on Aug 21, 2024. It is now read-only.

Commit

Permalink
Add interpliationFuncKeys to find keys in a map
Browse files Browse the repository at this point in the history
  • Loading branch information
cam-stitt committed Dec 1, 2017
1 parent ba062c7 commit d505ad1
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
29 changes: 29 additions & 0 deletions interpolation/maps.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package interpolation

import (
"fmt"
"sort"

"github.com/hashicorp/hil"

Expand Down Expand Up @@ -58,3 +59,31 @@ func interpolationFuncMap() ast.Function {
},
}
}

// interpolationFuncKeys returns the keys of the provided map sorted in dictionary order
func interpolationFuncKeys() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeMap},
ReturnType: ast.TypeList,
Variadic: false,
Callback: func(inputs []interface{}) (interface{}, error) {
mapInput := inputs[0].(map[string]ast.Variable)
keys := make([]string, 0, len(mapInput)+1)
result := make([]ast.Variable, 0, len(mapInput)+1)
for key := range mapInput {
keys = append(keys, key)
}
sort.Strings(keys)

for _, key := range keys {
nativeKey, err := hil.InterfaceToVariable(key)
if err != nil {
return nil, err
}
result = append(result, nativeKey)
}

return result, nil
},
}
}
33 changes: 33 additions & 0 deletions interpolation/maps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,36 @@ func TestInterpolationFuncMap(t *testing.T) {
})
}
}

func TestInterpolationFuncKeys(t *testing.T) {
testCases := []functionTestCase{
{
description: "Returns the keys",
text: `${keys(foo)}`,
expectation: []interface{}{"bar", "bar2"},
vars: map[string]ast.Variable{
"foo": ast.Variable{
Type: ast.TypeMap,
Value: map[string]ast.Variable{
"bar2": ast.Variable{
Type: ast.TypeString,
Value: "other2",
},
"bar": ast.Variable{
Type: ast.TypeString,
Value: "other",
},
},
},
},
},
}

keysTestFunc := testInterpolationFunc("keys", interpolationFuncKeys)

for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
keysTestFunc(t, tc)
})
}
}

0 comments on commit d505ad1

Please # to comment.