Make ge, le etc. work with the Hugo Version number

This means that you can do something ala:

```html
{{ if ge .Hugo.Version "0.36" }}Reasonable new Hugo version!{{ end }}
```

The intented use is feature toggling, but please note that it will take some time and Hugo versions until this can be trusted. It does not work in older Hugo versions.

Fixes #4443
This commit is contained in:
Bjørn Erik Pedersen
2018-02-22 09:15:12 +01:00
parent 55bd46a633
commit 0602135fd4
9 changed files with 127 additions and 14 deletions

View File

@@ -18,6 +18,7 @@ import (
"fmt"
"strings"
"github.com/gohugoio/hugo/compare"
"github.com/spf13/cast"
)
@@ -34,10 +35,40 @@ type HugoVersion struct {
Suffix string
}
var (
_ compare.Eqer = (*HugoVersionString)(nil)
_ compare.Comparer = (*HugoVersionString)(nil)
)
type HugoVersionString string
func (v HugoVersion) String() string {
return hugoVersion(v.Number, v.PatchLevel, v.Suffix)
}
func (v HugoVersion) Version() HugoVersionString {
return HugoVersionString(v.String())
}
func (h HugoVersionString) String() string {
return string(h)
}
// Implements compare.Comparer
func (h HugoVersionString) Compare(other interface{}) int {
v := MustParseHugoVersion(h.String())
return compareVersions(v.Number, v.PatchLevel, other)
}
// Implements compare.Eqer
func (h HugoVersionString) Eq(other interface{}) bool {
s, err := cast.ToStringE(other)
if err != nil {
return false
}
return s == h.String()
}
// ParseHugoVersion parses a version string.
func ParseHugoVersion(s string) (HugoVersion, error) {
var vv HugoVersion

View File

@@ -29,6 +29,11 @@ func TestHugoVersion(t *testing.T) {
require.Equal(t, v.ReleaseVersion().String(), "0.21")
require.Equal(t, "0.21-DEV", v.String())
require.Equal(t, "0.22", v.Next().String())
nextVersionString := v.Next().Version()
require.Equal(t, "0.22", nextVersionString.String())
require.True(t, nextVersionString.Eq("0.22"))
require.False(t, nextVersionString.Eq("0.21"))
require.True(t, nextVersionString.Eq(nextVersionString))
require.Equal(t, "0.20.3", v.NextPatchLevel(3).String())
}