From be0e4a22abcef260e31e33ea22a3b08ab3e958ab Mon Sep 17 00:00:00 2001 From: Dean Sofer Date: Wed, 25 Apr 2018 13:56:44 -0700 Subject: [PATCH 1/3] Added negative truncation to helper function This allows you to grab a truncated portion of a string from the end. --- template/helpers.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/template/helpers.go b/template/helpers.go index 3c7a371..bd59acd 100644 --- a/template/helpers.go +++ b/template/helpers.go @@ -100,13 +100,18 @@ func isFailure(conditional bool, options *raymond.Options) string { } func truncate(s string, len int) string { - if utf8.RuneCountInString(s) <= len { + if utf8.RuneCountInString(s) <= int(math.Abs(float64(len))) { return s } runes := []rune(s) - return string(runes[:len]) + if len < 0 { + len = -len + return string(runes[len:]) + } else { + return string(runes[:len]) + } } func urlencode(options *raymond.Options) string { From ecbb4a10a52050ad25ac0384f6e149aa7cd0447f Mon Sep 17 00:00:00 2001 From: Don Date: Fri, 18 Sep 2020 10:58:48 -0700 Subject: [PATCH 2/3] Add test for negative truncation --- template/helpers_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/template/helpers_test.go b/template/helpers_test.go index 96d6e6e..b93339d 100644 --- a/template/helpers_test.go +++ b/template/helpers_test.go @@ -53,6 +53,22 @@ func TestTruncate(t *testing.T) { } } +func TestNegativeTruncate(t *testing.T) { + vals := map[string]string{ + "foobarz": "rz", + "foöäüüu": "üu", + "üpsßßßk": "ßk", + "1234567": "67", + "!'§$%&/": "&/", + } + + for input, want := range vals { + if got := truncate(input, -5); got != want { + t.Errorf("Want transform %s to %s, got %s", input, want, got) + } + } +} + func TestSince(t *testing.T) { t.Skip() } From 29099fe4a4491871e7c1bad80ff55564721ca8e3 Mon Sep 17 00:00:00 2001 From: Don Date: Fri, 18 Sep 2020 11:00:31 -0700 Subject: [PATCH 3/3] Fix build and lints --- template/helpers.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/template/helpers.go b/template/helpers.go index bd59acd..b4085b4 100644 --- a/template/helpers.go +++ b/template/helpers.go @@ -17,6 +17,7 @@ package template import ( "fmt" "net/url" + "math" "regexp" "strings" "time" @@ -109,9 +110,9 @@ func truncate(s string, len int) string { if len < 0 { len = -len return string(runes[len:]) - } else { - return string(runes[:len]) } + + return string(runes[:len]) } func urlencode(options *raymond.Options) string {