Add string functions for lowercase, uppercase and capitalize to shoutrrr templates (#593)

* Added string functions for lowercase, uppercase and capitalize to shoutrrr templates

* Update pkg/notifications/shoutrrr.go

Co-authored-by: nils måsén <nils@piksel.se>

* Update pkg/notifications/shoutrrr.go

Co-authored-by: nils måsén <nils@piksel.se>

* Update pkg/notifications/shoutrrr.go

Co-authored-by: nils måsén <nils@piksel.se>

* Update pkg/notifications/shoutrrr_test.go

Co-authored-by: nils måsén <nils@piksel.se>

* escape quotation marks in test

Co-authored-by: nils måsén <nils@piksel.se>
pull/606/head
Possible Triangle 4 years ago committed by GitHub
parent d0f3ea3683
commit f76c48a95e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"text/template"
"strings"
"github.com/containrrr/shoutrrr"
"github.com/containrrr/shoutrrr/pkg/router"
@ -109,10 +110,16 @@ func getShoutrrrTemplate(c *cobra.Command) *template.Template {
tplString, err := flags.GetString("notification-template")
funcs := template.FuncMap{
"ToUpper": strings.ToUpper,
"ToLower": strings.ToLower,
"Title": strings.Title,
}
// If we succeed in getting a non-empty template configuration
// try to parse the template string.
if tplString != "" && err == nil {
tpl, err = template.New("").Parse(tplString)
tpl, err = template.New("").Funcs(funcs).Parse(tplString)
}
// In case of errors (either from parsing the template string
@ -128,7 +135,7 @@ func getShoutrrrTemplate(c *cobra.Command) *template.Template {
// template wasn't configured (the empty template string)
// fallback to using the default template.
if err != nil || tplString == "" {
tpl = template.Must(template.New("").Parse(shoutrrrDefaultTemplate))
tpl = template.Must(template.New("").Funcs(funcs).Parse(shoutrrrDefaultTemplate))
}
return tpl

@ -51,6 +51,30 @@ func TestShoutrrrTemplate(t *testing.T) {
require.Equal(t, "info: foo bar\n", s)
}
func TestShoutrrrStringFunctions(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{range .}}{{.Level | printf \"%v\" | ToUpper }}: {{.Message | ToLower }} {{.Message | Title }}{{println}}{{end}}"})
require.NoError(t, err)
shoutrrr := &shoutrrrTypeNotifier{
template: getShoutrrrTemplate(cmd),
}
entries := []*log.Entry{
{
Level: log.InfoLevel,
Message: "foo Bar",
},
}
s := shoutrrr.buildMessage(entries)
require.Equal(t, "INFO: foo bar Foo Bar\n", s)
}
func TestShoutrrrInvalidTemplateUsesTemplate(t *testing.T) {
cmd := new(cobra.Command)

Loading…
Cancel
Save