add gstr.IsGNUVersion (#1937)

This commit is contained in:
John Guo 2022-06-24 16:54:24 +08:00 committed by GitHub
parent f0511592b5
commit d7faae0531
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 0 deletions

View File

@ -12,6 +12,32 @@ import (
"github.com/gogf/gf/v2/util/gconv"
)
// IsGNUVersion checks and returns whether given `version` is valid GNU version string.
func IsGNUVersion(version string) bool {
if version != "" && (version[0] == 'v' || version[0] == 'V') {
version = version[1:]
}
if version == "" {
return false
}
var array = strings.Split(version, ".")
if len(array) > 3 {
return false
}
for _, v := range array {
if v == "" {
return false
}
if !IsNumeric(v) {
return false
}
if v[0] == '-' || v[0] == '+' {
return false
}
}
return true
}
// CompareVersion compares `a` and `b` as standard GNU version.
// It returns 1 if `a` > `b`.
// It returns -1 if `a` < `b`.

View File

@ -15,6 +15,23 @@ import (
"github.com/gogf/gf/v2/text/gstr"
)
func Test_IsGNUVersion(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.AssertEQ(gstr.IsGNUVersion(""), false)
t.AssertEQ(gstr.IsGNUVersion("v"), false)
t.AssertEQ(gstr.IsGNUVersion("v0"), true)
t.AssertEQ(gstr.IsGNUVersion("v0."), false)
t.AssertEQ(gstr.IsGNUVersion("v1."), false)
t.AssertEQ(gstr.IsGNUVersion("v1.1"), true)
t.AssertEQ(gstr.IsGNUVersion("v1.1.0"), true)
t.AssertEQ(gstr.IsGNUVersion("v1.1."), false)
t.AssertEQ(gstr.IsGNUVersion("v1.1.0.0"), false)
t.AssertEQ(gstr.IsGNUVersion("v0.0.0"), true)
t.AssertEQ(gstr.IsGNUVersion("v1.1.-1"), false)
t.AssertEQ(gstr.IsGNUVersion("v1.1.+1"), false)
})
}
func Test_CompareVersion(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.AssertEQ(gstr.CompareVersion("1", ""), 1)