From ff709668c3e42ce53502c7eee7868f76037f8d06 Mon Sep 17 00:00:00 2001 From: Vincent Le Goff Date: Fri, 17 Mar 2023 10:10:59 +0100 Subject: [PATCH] feat: add toBool function for template --- file/readfile.go | 8 +++++++- file/readfile_test.go | 27 +++++++++++++++++++++++++++ file/testdata/parsebool/file.yaml | 4 ++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 file/testdata/parsebool/file.yaml diff --git a/file/readfile.go b/file/readfile.go index c32301955..e19daea9b 100644 --- a/file/readfile.go +++ b/file/readfile.go @@ -7,6 +7,7 @@ import ( "io" "io/ioutil" "os" + "strconv" "strings" "text/template" @@ -145,9 +146,14 @@ func getPrefixedEnvVar(key string) (string, error) { return value, nil } +func toBool(key string) (bool, error) { + return strconv.ParseBool(key) +} + func renderTemplate(content string) (string, error) { t := template.New("state").Funcs(template.FuncMap{ - "env": getPrefixedEnvVar, + "env": getPrefixedEnvVar, + "toBool": toBool, }).Delims("${{", "}}") t, err := t.Parse(content) if err != nil { diff --git a/file/readfile_test.go b/file/readfile_test.go index 2a416d2f3..3be06f9d3 100644 --- a/file/readfile_test.go +++ b/file/readfile_test.go @@ -424,6 +424,33 @@ func Test_getContent(t *testing.T) { }, wantErr: false, }, + { + name: "file with env var and parse bool", + args: args{[]string{"testdata/parsebool/file.yaml"}}, + envVars: map[string]string{ + "DECK_MOCKBIN_ENABLED": "true", + }, + want: &Content{ + Services: []FService{ + { + Service: kong.Service{ + Name: kong.String("svc1"), + Host: kong.String("mockbin.org"), + Enabled: kong.Bool(true), + }, + }, + }, + }, + wantErr: false, + }, + { + name: "file with env var and parse bool - err on bad value", + args: args{[]string{"testdata/parsebool/file.yaml"}}, + envVars: map[string]string{ + "DECK_MOCKBIN_ENABLED": "RIP", + }, + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/file/testdata/parsebool/file.yaml b/file/testdata/parsebool/file.yaml new file mode 100644 index 000000000..209a9344e --- /dev/null +++ b/file/testdata/parsebool/file.yaml @@ -0,0 +1,4 @@ +services: +- name: svc1 + host: mockbin.org + enabled: ${{ env "DECK_MOCKBIN_ENABLED" | toBool }}