Add templating coalesce function (#4492)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2024-03-15 10:33:10 -04:00
1 parent 7105270cd5
commit 4542eef22b
8 files changed
+52 -8

No files matched your search

+11
View File
@@ -12,3 +12,14 @@ func truncateFrom(str, sep string) string {
before, _, _ := strings.Cut(str, sep)
return before
}
// coalesce will return the first non-empty string in the list of strings, and
// an empty string if all parameters are empty.
func coalesce(vals ...string) string {
for _, val := range vals {
if val != "" {
return val
}
}
return ""
}
+1
View File
@@ -33,6 +33,7 @@ func New(ctx context.Context, raw string) (*Parsed, error) {
raw: raw,
funcMap: map[string]any{
"truncateFrom": truncateFrom,
"coalesce": coalesce,
},
}
+5 -1
View File
@@ -39,7 +39,7 @@ func TestErrors(t *testing.T) {
require.NotNil(parsed)
assert.Equal(ts, parsed.raw)
assert.NotNil(parsed.tmpl)
assert.Len(parsed.funcMap, 1)
assert.Len(parsed.funcMap, 2)
// Test out errors on the parsed value
@@ -102,6 +102,8 @@ func TestGenerate(t *testing.T) {
{{ .Account.Subject }}
{{ .Account.Email }}
{{ truncateFrom .Account.Email "@" }}
{{ coalesce "" .Account.LoginName .Account.Name }}
{{ coalesce "" "" .Account.Name .Account.LoginName }}
`)
parsed, err := New(ctx, raw)
@@ -128,6 +130,8 @@ accountLoginName
accountSubject
account@email.com
account
accountLoginName
accountName
`)
assert.Equal(exp, out)
+5 -4
View File
@@ -19,10 +19,11 @@ type Data struct {
// request to be from a different auth method, in which case it may not match
// what's in the Account struct.
type User struct {
Id *string
Name *string
FullName *string
Email *string
Id *string
Name *string
LoginName *string
FullName *string
Email *string
}
// Account contains account information. Not all fields will always be