Use go templates/sprig for messages (#2527)

This commit is contained in:
Markus Thierolf 2022-02-26 13:08:32 +01:00 • committed by GitHub
parent 2f06a88ead
commit 45a5bdf7d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 67 additions and 12 deletions

View file

@ -1,10 +1,14 @@
package util
import (
"bytes"
"fmt"
"html/template"
"regexp"
"strings"
"time"
"github.com/Masterminds/sprig/v3"
)
var re = regexp.MustCompile(`\${(\w+)(:([a-zA-Z0-9%.]+))?}`)
@ -46,6 +50,20 @@ func FormatValue(format string, val interface{}) string {
// ReplaceFormatted replaces all occurrences of ${key} with formatted val from the kv map
func ReplaceFormatted(s string, kv map[string]interface{}) (string, error) {
// Enhanced golang template logic
tpl, err := template.New("base").Funcs(sprig.FuncMap()).Parse(s)
if err != nil {
return s, err
}
var rs bytes.Buffer
err = tpl.Execute(&rs, kv)
if err != nil {
return s, err
}
s = rs.String()
// Regex logic for backward compatibility
wanted := make([]string, 0)
for m := re.FindStringSubmatch(s); m != nil; m = re.FindStringSubmatch(s) {
@ -65,7 +83,6 @@ func ReplaceFormatted(s string, kv map[string]interface{}) (string, error) {
}
// return missing keys
var err error
if len(wanted) > 0 {
got := make([]string, 0)
for k := range kv {