Skip to content

Commit

Permalink
Add pick and omit funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
cam-stitt committed Dec 20, 2017
1 parent 0e34b8f commit 9051e14
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
11 changes: 11 additions & 0 deletions examples/vars.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,15 @@ variable "bar" {
value = {
"this" = "that"
}
}

variable "nested" {
value = [
{
"id" = "1"
},
{
"id" = "2"
}
]
}
44 changes: 44 additions & 0 deletions interpolation/maps.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,47 @@ func interpolationFuncMerge() ast.Function {
},
}
}

// interpolationFuncPick will pick the values of the provided keys, and create a new map
func interpolationFuncPick() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeMap},
ReturnType: ast.TypeMap,
Variadic: true,
VariadicType: ast.TypeString,
Callback: func(inputs []interface{}) (interface{}, error) {
inMap := inputs[0].(map[string]ast.Variable)
result := make(map[string]ast.Variable)

for i := 1; i < len(inputs); i++ {
key := inputs[i].(string)

if val, ok := inMap[key]; ok {
result[key] = val
}
}

return result, nil
},
}
}

// interpolationFuncOmit will return a map that has omitted the keys provided
func interpolationFuncOmit() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeMap},
ReturnType: ast.TypeMap,
Variadic: true,
VariadicType: ast.TypeString,
Callback: func(inputs []interface{}) (interface{}, error) {
inMap := inputs[0].(map[string]ast.Variable)

for i := 1; i < len(inputs); i++ {
key := inputs[i].(string)
delete(inMap, key)
}

return inMap, nil
},
}
}
46 changes: 46 additions & 0 deletions interpolation/maps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,49 @@ func TestInterpolationFuncMerge(t *testing.T) {
})
}
}

func TestInterpolationFuncPick(t *testing.T) {
testCases := []functionTestCase{
{
description: "Picks correctly",
text: `${pick(map("foo", "bar", "this", "that"), "foo")}`,
expectation: map[string]interface{}{
"foo": "bar",
},
},
}

pickTestFunc := testInterpolationFunc(keyFuncs{
"pick": interpolationFuncPick,
"map": interpolationFuncMap,
})

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

func TestInterpolationFuncOmit(t *testing.T) {
testCases := []functionTestCase{
{
description: "Omit correctly",
text: `${omit(map("foo", "bar", "this", "that"), "foo")}`,
expectation: map[string]interface{}{
"this": "that",
},
},
}

pickTestFunc := testInterpolationFunc(keyFuncs{
"omit": interpolationFuncOmit,
"map": interpolationFuncMap,
})

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

0 comments on commit 9051e14

Please sign in to comment.