From 47640b8b945b02d78be60978342b8ec2616c8d0f Mon Sep 17 00:00:00 2001 From: shreyas-goenka <88374338+shreyas-goenka@users.noreply.github.com> Date: Tue, 25 Jul 2023 16:42:53 +0200 Subject: [PATCH] Add regexp compile helper function for templates (#601) ## Tests unit test --- libs/template/helpers.go | 5 ++++ libs/template/helpers_test.go | 25 +++++++++++++++++++ .../regexp-compile/template/hello.tmpl | 5 ++++ 3 files changed, 35 insertions(+) create mode 100644 libs/template/helpers_test.go create mode 100644 libs/template/testdata/regexp-compile/template/hello.tmpl diff --git a/libs/template/helpers.go b/libs/template/helpers.go index 271fd539..342b3811 100644 --- a/libs/template/helpers.go +++ b/libs/template/helpers.go @@ -2,6 +2,7 @@ package template import ( "fmt" + "regexp" "text/template" ) @@ -17,4 +18,8 @@ var helperFuncs = template.FuncMap{ "fail": func(format string, args ...any) (any, error) { return nil, ErrFail{fmt.Sprintf(format, args...)} }, + // Alias for https://pkg.go.dev/regexp#Compile. Allows usage of all methods of regexp.Regexp + "regexp": func(expr string) (*regexp.Regexp, error) { + return regexp.Compile(expr) + }, } diff --git a/libs/template/helpers_test.go b/libs/template/helpers_test.go new file mode 100644 index 00000000..fbb66ae2 --- /dev/null +++ b/libs/template/helpers_test.go @@ -0,0 +1,25 @@ +package template + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestTemplateRegexpCompileFunction(t *testing.T) { + ctx := context.Background() + tmpDir := t.TempDir() + + r, err := newRenderer(ctx, nil, "./testdata/regexp-compile/template", "./testdata/regexp-compile/library", tmpDir) + require.NoError(t, err) + + err = r.walk() + assert.NoError(t, err) + + assert.Len(t, r.files, 1) + content := string(r.files[0].content) + assert.Contains(t, content, "0:food") + assert.Contains(t, content, "1:fool") +} diff --git a/libs/template/testdata/regexp-compile/template/hello.tmpl b/libs/template/testdata/regexp-compile/template/hello.tmpl new file mode 100644 index 00000000..5ea55d79 --- /dev/null +++ b/libs/template/testdata/regexp-compile/template/hello.tmpl @@ -0,0 +1,5 @@ +{{with (regexp "foo.?")}} +{{range $index, $element := (.FindAllString "seafood fool" -1) }} +{{print $index ":" $element}} +{{end}} +{{end}}