2023-02-08 12:42:55 +00:00
|
|
|
package template
|
|
|
|
|
|
|
|
import (
|
2024-01-02 21:21:53 +00:00
|
|
|
"fmt"
|
2023-02-08 12:42:55 +00:00
|
|
|
"text/template"
|
2024-01-02 21:21:53 +00:00
|
|
|
"unicode"
|
|
|
|
"unicode/utf8"
|
2023-02-08 12:42:55 +00:00
|
|
|
|
|
|
|
"github.com/Masterminds/sprig/v3"
|
|
|
|
)
|
|
|
|
|
2024-03-11 08:23:17 +00:00
|
|
|
// LoadFuncMap merges the sprig template functions with any custom functions
|
|
|
|
// provided, giving priority to the custom functions in case of collisions.
|
2023-12-21 10:15:41 +00:00
|
|
|
func LoadFuncMap() template.FuncMap {
|
2023-02-08 12:42:55 +00:00
|
|
|
sprigFuncs := sprig.GenericFuncMap()
|
2024-01-02 21:21:53 +00:00
|
|
|
customFuncs := template.FuncMap{
|
|
|
|
"ToSentence": ToSentence,
|
|
|
|
}
|
2023-02-08 12:42:55 +00:00
|
|
|
|
|
|
|
for name, f := range customFuncs {
|
|
|
|
if _, ok := sprigFuncs[name]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
sprigFuncs[name] = f
|
|
|
|
}
|
|
|
|
|
|
|
|
return sprigFuncs
|
|
|
|
}
|
2024-01-02 21:21:53 +00:00
|
|
|
|
2024-03-11 08:23:17 +00:00
|
|
|
// ToSentence capitalizes the first letter of the input string,
|
|
|
|
// adds a period at the end if needed, and returns the resulting sentence.
|
2024-01-02 21:21:53 +00:00
|
|
|
func ToSentence(s string) string {
|
|
|
|
if s == "" {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
r, n := utf8.DecodeRuneInString(s)
|
|
|
|
|
|
|
|
closer := ""
|
|
|
|
if getLastRune(s, 1) != "." {
|
|
|
|
closer = "."
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf("%s%s%s", string(unicode.ToUpper(r)), s[n:], closer)
|
|
|
|
}
|
|
|
|
|
2024-03-11 08:23:17 +00:00
|
|
|
// getLastRune returns the last n runes in the string s.
|
|
|
|
// It decodes s from the end, counting n runes.
|
2024-01-02 21:21:53 +00:00
|
|
|
func getLastRune(s string, c int) string {
|
|
|
|
j := len(s)
|
|
|
|
for i := 0; i < c && j > 0; i++ {
|
|
|
|
_, size := utf8.DecodeLastRuneInString(s[:j])
|
|
|
|
j -= size
|
|
|
|
}
|
|
|
|
|
|
|
|
return s[j:]
|
|
|
|
}
|