Allow nil to truncate template function (#5656)

Fixes #5643
This commit is contained in:
Mislav Marohnić 2022-05-16 19:05:17 +02:00 committed by GitHub
commit c9503df123
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 1 deletions

View file

@ -56,7 +56,15 @@ func (t *Template) parseTemplate(tpl string) (*template.Template, error) {
"join": templateJoin,
"tablerow": t.tableRow,
"tablerender": t.tableRender,
"truncate": text.Truncate,
"truncate": func(maxWidth int, v interface{}) (string, error) {
if v == nil {
return "", nil
}
if s, ok := v.(string); ok {
return text.Truncate(maxWidth, s), nil
}
return "", fmt.Errorf("invalid value; expected string, got %T", v)
},
}
if !t.io.ColorEnabled() {

View file

@ -263,6 +263,38 @@ func Test_executeTemplate(t *testing.T) {
},
wantW: "This is a ...",
},
{
name: "truncate with JSON null",
args: args{
json: strings.NewReader(`{}`),
template: `{{ truncate 13 .title }}`,
},
wantW: "",
},
{
name: "truncate with piped JSON null",
args: args{
json: strings.NewReader(`{}`),
template: `{{ .title | truncate 13 }}`,
},
wantW: "",
},
{
name: "truncate with piped JSON null in parenthetical",
args: args{
json: strings.NewReader(`{}`),
template: `{{ (.title | truncate 13) }}`,
},
wantW: "",
},
{
name: "truncate invalid type",
args: args{
json: strings.NewReader(`{"title": 42}`),
template: `{{ (.title | truncate 13) }}`,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {