Skip to content

Commit

Permalink
tpl: Do not return errors in substr for out-of-bounds cases
Browse files Browse the repository at this point in the history
Most other substr implementations don't error out in out-of-bounds cases
but simply return an empty string (or a value that's printed as an empty
string). We'll follow their lead and not exit template execution.  Allow
the user decide what to do with the empty result.

Fixes gohugoio#8113
  • Loading branch information
moorereason authored and gzagatti committed Jan 11, 2021
1 parent d7bd9fa commit 9ea7e50
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
5 changes: 2 additions & 3 deletions tpl/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package strings

import (
"errors"
"fmt"
"html/template"
"strings"
"unicode/utf8"
Expand Down Expand Up @@ -322,7 +321,7 @@ func (ns *Namespace) Substr(a interface{}, nums ...interface{}) (string, error)
}

if start > rlen-1 {
return "", fmt.Errorf("start position out of bounds for %d-byte string", rlen)
return "", nil
}

end := rlen
Expand All @@ -337,7 +336,7 @@ func (ns *Namespace) Substr(a interface{}, nums ...interface{}) (string, error)
}

if start >= end {
return "", fmt.Errorf("calculated start position greater than end position: %d > %d", start, end)
return "", nil
}

if end < 0 {
Expand Down
9 changes: 5 additions & 4 deletions tpl/strings/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,9 +451,9 @@ func TestSubstr(t *testing.T) {
{"abcdef", -3, 1, "d"},
{"abcdef", 0, -1, "abcde"},
{"abcdef", 2, -1, "cde"},
{"abcdef", 4, -4, false},
{"abcdef", 7, 1, false},
{"abcdef", 6, nil, false},
{"abcdef", 4, -4, ""},
{"abcdef", 7, 1, ""},
{"abcdef", 6, nil, ""},
{"abcdef", 1, 100, "bcdef"},
{"abcdef", -100, 3, "abc"},
{"abcdef", -3, -1, "de"},
Expand All @@ -476,6 +476,7 @@ func TestSubstr(t *testing.T) {
{"abcdef", "doo", nil, false},
{"abcdef", "doo", "doo", false},
{"abcdef", 1, "doo", false},
{"", 0, nil, ""},
} {

var result string
Expand All @@ -491,7 +492,7 @@ func TestSubstr(t *testing.T) {
continue
}

c.Assert(err, qt.IsNil)
c.Assert(err, qt.IsNil, qt.Commentf("%v", test))
c.Check(result, qt.Equals, test.expect, qt.Commentf("%v", test))
}

Expand Down

0 comments on commit 9ea7e50

Please sign in to comment.