Skip to content

Commit

Permalink
provisioner: update split template function logic for empty input
Browse files Browse the repository at this point in the history
Splitting empty string intuitively should produce zero parts.

Stdlib strings.Split returns s if s does not contain d therefore
strings.Split("", ",") returns one part [""].

This should simplify a common pattern:
```
{{ if ne .ConfigItems.foo "" }}
{{ range $bar := split .ConfigItems.foo "," }}
  - "{{ $bar }}"
{{ end }}
{{ end }}
```
to
```
{{ range $bar := split .ConfigItems.foo "," }}
  - "{{ $bar }}"
{{ end }}
```

Signed-off-by: Alexander Yastrebov <alexander.yastrebov@zalando.de>
  • Loading branch information
AlexanderYastrebov committed Mar 29, 2023
1 parent 9b6a926 commit beff6c4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
3 changes: 3 additions & 0 deletions provisioner/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ func azCount(subnets map[string]string) int {

// split is a template function that takes a string and a separator and returns the splitted parts.
func split(s string, d string) []string {
if s == "" {
return nil
}
return strings.Split(s, d)
}

Expand Down
32 changes: 32 additions & 0 deletions provisioner/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,38 @@ func TestAZCountNoSubnets(t *testing.T) {
require.EqualValues(t, "0", result)
}

func TestSplit(t *testing.T) {
t.Run("empty", func(t *testing.T) {
result, err := renderSingle(
t,
`{{ range $index, $element := split .Values.data "," }}{{ $index }}={{ $element}}{{end}}`,
"")

require.NoError(t, err)
require.Equal(t, "", result)
})

t.Run("single", func(t *testing.T) {
result, err := renderSingle(
t,
`{{ range $index, $element := split .Values.data "," }}{{ $index }}={{ $element}}{{end}}`,
"foo")

require.NoError(t, err)
require.Equal(t, "0=foo", result)
})

t.Run("multiple", func(t *testing.T) {
result, err := renderSingle(
t,
`{{ range $index, $element := split .Values.data "," }}{{ $index }}={{ $element}}{{end}}`,
"foo,bar")

require.NoError(t, err)
require.Equal(t, "0=foo1=bar", result)
})
}

func TestMountUnitName(t *testing.T) {
result, err := renderSingle(
t,
Expand Down

0 comments on commit beff6c4

Please sign in to comment.