diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2022-02-26 10:42:21 +0100 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2022-02-26 21:54:36 +0100 |
commit | 10928a4f781c2faf704825ef95234125812ad860 (patch) | |
tree | 6d53312b301ad5259eb509fbdd13efa6c5c199e5 /common/text | |
parent | afd63bf7d56194a6aa5d32483151d71fa0b84f3a (diff) |
Remove the trailing new line in .Code
Fixes #9572
Diffstat (limited to 'common/text')
-rw-r--r-- | common/text/transform.go | 16 | ||||
-rw-r--r-- | common/text/transform_test.go | 15 |
2 files changed, 31 insertions, 0 deletions
diff --git a/common/text/transform.go b/common/text/transform.go index f59577803..66a67d8bc 100644 --- a/common/text/transform.go +++ b/common/text/transform.go @@ -14,6 +14,7 @@ package text import ( + "strings" "sync" "unicode" @@ -45,3 +46,18 @@ func RemoveAccentsString(s string) string { accentTransformerPool.Put(t) return s } + +// Chomp removes trailing newline characters from s. +func Chomp(s string) string { + return strings.TrimRightFunc(s, func(r rune) bool { + return r == '\n' || r == '\r' + }) +} + +// Puts adds a trailing \n none found. +func Puts(s string) string { + if s == "" || s[len(s)-1] == '\n' { + return s + } + return s + "\n" +} diff --git a/common/text/transform_test.go b/common/text/transform_test.go index 08265f976..992dd524c 100644 --- a/common/text/transform_test.go +++ b/common/text/transform_test.go @@ -26,3 +26,18 @@ func TestRemoveAccents(t *testing.T) { c.Assert(string(RemoveAccents([]byte("Hugo Rocks!"))), qt.Equals, "Hugo Rocks!") c.Assert(string(RemoveAccentsString("Resumé")), qt.Equals, "Resume") } + +func TestChomp(t *testing.T) { + c := qt.New(t) + + c.Assert(Chomp("\nA\n"), qt.Equals, "\nA") + c.Assert(Chomp("A\r\n"), qt.Equals, "A") +} + +func TestPuts(t *testing.T) { + c := qt.New(t) + + c.Assert(Puts("A"), qt.Equals, "A\n") + c.Assert(Puts("\nA\n"), qt.Equals, "\nA\n") + c.Assert(Puts(""), qt.Equals, "") +} |