diff options
author | Bence Ferdinandy <bence@ferdinandy.com> | 2024-07-10 22:26:22 +0200 |
---|---|---|
committer | Robin Jarry <robin@jarry.cc> | 2024-08-03 17:41:15 +0200 |
commit | 9d8d74d9bf438c337ac0d6eed1b5dede5cc0ceb2 (patch) | |
tree | be09268e158dfbe03bf20fa0582f4ddf704e95ac /lib | |
parent | f8b74a9a9f1b607e20f7b5654e85b03be34ce0ed (diff) | |
download | aerc-9d8d74d9bf438c337ac0d6eed1b5dede5cc0ceb2.tar.gz |
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 <bence@ferdinandy.com>
Reviewed-by: Moritz Poldrack <moritz@poldrack.dev>
Acked-by: Robin Jarry <robin@jarry.cc>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/templates/functions.go | 20 | ||||
-rw-r--r-- | lib/templates/functions_test.go | 34 |
2 files changed, 54 insertions, 0 deletions
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) + } +} |