diff options
author | Cameron Moore <moorereason@gmail.com> | 2021-01-03 21:01:42 +0300 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2021-01-08 12:13:10 +0300 |
commit | 8a26ab0bc5dd9fa34e1362681fc08b0e522cd4ea (patch) | |
tree | 40b069293d1edff1ae47bcb6885af3dd3734c7df /tpl | |
parent | 788e50ad3a55609ed49ce0b7ee98965c181fe9cf (diff) |
tpl: Do not return errors in substr for out-of-bounds cases
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 #8113
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/strings/strings.go | 5 | ||||
-rw-r--r-- | tpl/strings/strings_test.go | 9 |
2 files changed, 7 insertions, 7 deletions
diff --git a/tpl/strings/strings.go b/tpl/strings/strings.go index 178d17bc0..b2f02d8f5 100644 --- a/tpl/strings/strings.go +++ b/tpl/strings/strings.go @@ -16,7 +16,6 @@ package strings import ( "errors" - "fmt" "html/template" "strings" "unicode/utf8" @@ -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 @@ -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 { diff --git a/tpl/strings/strings_test.go b/tpl/strings/strings_test.go index ef926aeef..f3bb82c63 100644 --- a/tpl/strings/strings_test.go +++ b/tpl/strings/strings_test.go @@ -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"}, @@ -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 @@ -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)) } |