Skip to content

Commit

Permalink
tpl/compare: Fix nil compare in eq/ne for interface values
Browse files Browse the repository at this point in the history
Fixes #5905
  • Loading branch information
bep committed Apr 29, 2019
1 parent 4f93f8c commit 66b143a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
6 changes: 5 additions & 1 deletion tpl/compare/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"strconv"
"time"

"github.com/gohugoio/hugo/common/types"

"github.com/gohugoio/hugo/compare"
)

Expand Down Expand Up @@ -88,7 +90,6 @@ func (*Namespace) Default(dflt interface{}, given ...interface{}) (interface{},

// Eq returns the boolean truth of arg1 == arg2.
func (*Namespace) Eq(x, y interface{}) bool {

if e, ok := x.(compare.Eqer); ok {
return e.Eq(y)
}
Expand All @@ -98,6 +99,9 @@ func (*Namespace) Eq(x, y interface{}) bool {
}

normalize := func(v interface{}) interface{} {
if types.IsNil(v) {
return nil
}
vv := reflect.ValueOf(v)
switch vv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Expand Down
24 changes: 23 additions & 1 deletion tpl/compare/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ import (
"github.com/stretchr/testify/require"
)

type T struct {
NonEmptyInterfaceNil I
NonEmptyInterfaceTypedNil I
}

type I interface {
Foo() string
}

func (t *T) Foo() string {
return "foo"
}

var testT = &T{
NonEmptyInterfaceTypedNil: (*T)(nil),
}

type tstEqerType1 string
type tstEqerType2 string

Expand Down Expand Up @@ -183,7 +200,12 @@ func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b inte
{"0.37-DEV", hugo.MustParseVersion("0.37").Version(), -1},
{"0.36", hugo.MustParseVersion("0.37-DEV").Version(), -1},
{"0.37-DEV", hugo.MustParseVersion("0.37-DEV").Version(), 0},
// https://github.com/gohugoio/hugo/issues/5905
{nil, nil, 0},
{testT.NonEmptyInterfaceNil, nil, 0},
{testT.NonEmptyInterfaceTypedNil, nil, 0},
} {

result := funcUnderTest(test.left, test.right)
success := false

Expand All @@ -206,7 +228,7 @@ func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b inte
}

if !success {
t.Errorf("[%d][%s] %v compared to %v: %t", i, path.Base(runtime.FuncForPC(reflect.ValueOf(funcUnderTest).Pointer()).Name()), test.left, test.right, result)
t.Fatalf("[%d][%s] %v compared to %v: %t", i, path.Base(runtime.FuncForPC(reflect.ValueOf(funcUnderTest).Pointer()).Name()), test.left, test.right, result)
}
}
}
Expand Down

0 comments on commit 66b143a

Please sign in to comment.