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

Commit 5373ae1

Browse files
committed
Split func for strings
1 parent dc62a54 commit 5373ae1

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

interpolation/funcs.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ var CoreFunctions = map[string]ast.Function{
2222
"max": interpolationFuncMax(),
2323
"min": interpolationFuncMin(),
2424
"contains": interpolationFuncContains(),
25+
"split": interpolationFuncSplit(),
2526
}
2627

2728
// interpolationFuncEnv will extract a variable out of the env

interpolation/strings.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"strings"
66

7+
"github.com/hashicorp/hil"
78
"github.com/hashicorp/hil/ast"
89
)
910

@@ -54,6 +55,27 @@ func interpolationFuncJoin() ast.Function {
5455
}
5556
}
5657

58+
// interpolationFuncSplit will split a string into substrings separated by a separator string.
59+
func interpolationFuncSplit() ast.Function {
60+
return ast.Function{
61+
ArgTypes: []ast.Type{ast.TypeString, ast.TypeString},
62+
ReturnType: ast.TypeList,
63+
Callback: func(inputs []interface{}) (interface{}, error) {
64+
var result []ast.Variable
65+
val := inputs[0].(string)
66+
sep := inputs[1].(string)
67+
for _, sub := range strings.Split(val, sep) {
68+
nativeVal, err := hil.InterfaceToVariable(sub)
69+
if err != nil {
70+
return nil, err
71+
}
72+
result = append(result, nativeVal)
73+
}
74+
return result, nil
75+
},
76+
}
77+
}
78+
5779
// interpolationFuncReplace replaces the occurences of a value on the provided string with another value.
5880
// The number of occurences to replace is the last argument to the function.
5981
func interpolationFuncReplace() ast.Function {

interpolation/strings_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,26 @@ func TestInterpolationFuncContains(t *testing.T) {
164164
})
165165
}
166166
}
167+
168+
func TestInterpolationFuncSplit(t *testing.T) {
169+
testCases := []functionTestCase{
170+
{
171+
description: "Splits into list",
172+
text: `${split("foo,bar", ",")}`,
173+
expectation: []interface{}{"foo", "bar"},
174+
},
175+
{
176+
description: "Splits even when sep not found",
177+
text: `${split("foo,bar", ":")}`,
178+
expectation: []interface{}{"foo,bar"},
179+
},
180+
}
181+
182+
splitTestFunc := testInterpolationFunc(keyFuncs{"split": interpolationFuncSplit})
183+
184+
for _, tc := range testCases {
185+
t.Run(tc.description, func(t *testing.T) {
186+
splitTestFunc(t, tc)
187+
})
188+
}
189+
}

0 commit comments

Comments
 (0)