Skip to content

Commit

Permalink
add gstr.IsGNUVersion (#1937)
Browse files Browse the repository at this point in the history
  • Loading branch information
gqcn authored Jun 24, 2022
1 parent f051159 commit d7faae0
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
26 changes: 26 additions & 0 deletions text/gstr/gstr_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
17 changes: 17 additions & 0 deletions text/gstr/gstr_z_unit_version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit d7faae0

Please sign in to comment.