From 9d8d74d9bf438c337ac0d6eed1b5dede5cc0ceb2 Mon Sep 17 00:00:00 2001 From: Bence Ferdinandy Date: Wed, 10 Jul 2024 22:26:22 +0200 Subject: templates: add head and tail functions Add head and tail functions to get beginning or ends of strings. E.g.: {{"hello" | head 2}} will return "he" {{"hello" | tail 2}} will return "lo" Implements: https://todo.sr.ht/~rjarry/aerc/220 Changelog-added: New `head` and `tail` templates functions for strings. Signed-off-by: Bence Ferdinandy Reviewed-by: Moritz Poldrack Acked-by: Robin Jarry --- lib/templates/functions.go | 20 ++++++++++++++++++++ lib/templates/functions_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) (limited to 'lib') diff --git a/lib/templates/functions.go b/lib/templates/functions.go index 8b7af449..0d204b8f 100644 --- a/lib/templates/functions.go +++ b/lib/templates/functions.go @@ -334,6 +334,24 @@ func hasPrefix(prefix, s string) bool { return strings.HasPrefix(s, prefix) } +func head(n uint, s string) string { + r := []rune(s) + length := uint(len(r)) + if length >= n { + return string(r[:n]) + } + return s +} + +func tail(n uint, s string) string { + r := []rune(s) + length := uint(len(r)) + if length >= n { + return string(r[length-n:]) + } + return s +} + var templateFuncs = template.FuncMap{ "quote": quote, "wrapText": wrapText, @@ -367,4 +385,6 @@ var templateFuncs = template.FuncMap{ "toLower": strings.ToLower, "toUpper": strings.ToUpper, "replace": replace, + "head": head, + "tail": tail, } diff --git a/lib/templates/functions_test.go b/lib/templates/functions_test.go index 492aad01..3dac591e 100644 --- a/lib/templates/functions_test.go +++ b/lib/templates/functions_test.go @@ -121,3 +121,37 @@ func TestTemplates_DifferentInitialsFormats(t *testing.T) { assert.Equal(t, c.initials, intls[0]) } } + +func TestTemplates_Head(t *testing.T) { + type testCase struct { + head uint + input string + output string + } + cases := []testCase{ + {head: 3, input: "abcde", output: "abc"}, + {head: 10, input: "abcde", output: "abcde"}, + } + + for _, c := range cases { + out := head(c.head, c.input) + assert.Equal(t, c.output, out) + } +} + +func TestTemplates_Tail(t *testing.T) { + type testCase struct { + tail uint + input string + output string + } + cases := []testCase{ + {tail: 2, input: "abcde", output: "de"}, + {tail: 8, input: "abcde", output: "abcde"}, + } + + for _, c := range cases { + out := tail(c.tail, c.input) + assert.Equal(t, c.output, out) + } +} -- cgit