Skip to content

Commit

Permalink
Make chomp return the type it receives
Browse files Browse the repository at this point in the history
fixes #2187
  • Loading branch information
kropp authored and bep committed Dec 16, 2017
1 parent db4b7a5 commit 22cd89a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
11 changes: 9 additions & 2 deletions tpl/strings/strings.go
Expand Up @@ -78,13 +78,20 @@ func (ns *Namespace) CountWords(s interface{}) (int, error) {
}

// Chomp returns a copy of s with all trailing newline characters removed.
func (ns *Namespace) Chomp(s interface{}) (template.HTML, error) {
func (ns *Namespace) Chomp(s interface{}) (interface{}, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}

return template.HTML(_strings.TrimRight(ss, "\r\n")), nil
res := _strings.TrimRight(ss, "\r\n")
switch s.(type) {
case template.HTML:
return template.HTML(res), nil
default:
return res, nil
}

}

// Contains reports whether substr is in s.
Expand Down
18 changes: 12 additions & 6 deletions tpl/strings/strings_test.go
Expand Up @@ -19,6 +19,7 @@ import (
"testing"

"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -35,12 +36,12 @@ func TestChomp(t *testing.T) {
s interface{}
expect interface{}
}{
{"\n a\n", template.HTML("\n a")},
{"\n a\n\n", template.HTML("\n a")},
{"\n a\r\n", template.HTML("\n a")},
{"\n a\n\r\n", template.HTML("\n a")},
{"\n a\r\r", template.HTML("\n a")},
{"\n a\r", template.HTML("\n a")},
{"\n a\n", "\n a"},
{"\n a\n\n", "\n a"},
{"\n a\r\n", "\n a"},
{"\n a\n\r\n", "\n a"},
{"\n a\r\r", "\n a"},
{"\n a\r", "\n a"},
// errors
{tstNoStringer{}, false},
} {
Expand All @@ -55,6 +56,11 @@ func TestChomp(t *testing.T) {

require.NoError(t, err, errMsg)
assert.Equal(t, test.expect, result, errMsg)

// repeat the check with template.HTML input
result, err = ns.Chomp(template.HTML(cast.ToString(test.s)))
require.NoError(t, err, errMsg)
assert.Equal(t, template.HTML(cast.ToString(test.expect)), result, errMsg)
}
}

Expand Down

0 comments on commit 22cd89a

Please sign in to comment.