#15291: config/interpolate_funcs: Added contains() function to test if a given element is present in the list

This commit is contained in:
trung 2017-06-16 14:38:01 -04:00 committed by Martin Atkins
parent 14a2c04ddf
commit 681661a539
3 changed files with 57 additions and 0 deletions

View File

@ -70,6 +70,7 @@ func Funcs() map[string]ast.Function {
"coalescelist": interpolationFuncCoalesceList(),
"compact": interpolationFuncCompact(),
"concat": interpolationFuncConcat(),
"contains": interpolationFuncContains(),
"dirname": interpolationFuncDirname(),
"distinct": interpolationFuncDistinct(),
"element": interpolationFuncElement(),
@ -356,6 +357,22 @@ func interpolationFuncCoalesceList() ast.Function {
}
}
// interpolationFuncContains returns true if an element is in the list
// and return false otherwise
func interpolationFuncContains() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeList, ast.TypeString},
ReturnType: ast.TypeBool,
Callback: func(args []interface{}) (interface{}, error) {
_, err := interpolationFuncIndex().Callback(args)
if err != nil {
return false, nil
}
return true, nil
},
}
}
// interpolationFuncConcat implements the "concat" function that concatenates
// multiple lists.
func interpolationFuncConcat() ast.Function {

View File

@ -943,6 +943,43 @@ func TestInterpolateFuncConcat(t *testing.T) {
})
}
func TestInterpolateFuncContains(t *testing.T) {
testFunction(t, testFunctionConfig{
Vars: map[string]ast.Variable{
"var.listOfStrings": interfaceToVariableSwallowError([]string{"notfoo", "stillnotfoo", "bar"}),
"var.listOfInts": interfaceToVariableSwallowError([]int{1, 2, 3}),
},
Cases: []testFunctionCase{
{
`${contains(var.listOfStrings, "bar")}`,
"true",
false,
},
{
`${contains(var.listOfStrings, "foo")}`,
"false",
false,
},
{
`${contains(var.listOfInts, 1)}`,
"true",
false,
},
{
`${contains(var.listOfInts, 10)}`,
"false",
false,
},
{
`${contains(var.listOfInts, "2")}`,
"true",
false,
},
},
})
}
func TestInterpolateFuncMerge(t *testing.T) {
testFunction(t, testFunctionConfig{
Cases: []testFunctionCase{

View File

@ -205,6 +205,9 @@ The supported built-in functions are:
* `concat(list1, list2, ...)` - Combines two or more lists into a single list.
Example: `concat(aws_instance.db.*.tags.Name, aws_instance.web.*.tags.Name)`
* `contains(list, element)` - Returns *true* if a list contains the given element
and returns *false* otherwise. Examples: `element(var.list_of_strings, "an_element")`
* `dirname(path)` - Returns all but the last element of path, typically the path's directory.
* `distinct(list)` - Removes duplicate items from a list. Keeps the first