github.com/cilium/cilium@v1.16.2/pkg/versioncheck/check.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 // Package versioncheck provides utility wrappers for go-version, allowing the 5 // constraints to be used as global variables. 6 package versioncheck 7 8 import ( 9 "fmt" 10 "strconv" 11 "strings" 12 13 "github.com/blang/semver/v4" 14 ) 15 16 // MustCompile wraps go-version.NewConstraint, panicing when an error is 17 // returns (this occurs when the constraint cannot be parsed). 18 // It is intended to be use similar to re.MustCompile, to ensure unparseable 19 // constraints are caught in testing. 20 func MustCompile(constraint string) semver.Range { 21 verCheck, err := Compile(constraint) 22 if err != nil { 23 panic(fmt.Errorf("cannot compile go-version constraint '%s': %w", constraint, err)) 24 } 25 return verCheck 26 } 27 28 // Compile trivially wraps go-version.NewConstraint, returning the constraint 29 // and error 30 func Compile(constraint string) (semver.Range, error) { 31 return semver.ParseRange(constraint) 32 } 33 34 // MustVersion wraps go-version.NewVersion, panicing when an error is 35 // returns (this occurs when the version cannot be parsed). 36 func MustVersion(version string) semver.Version { 37 ver, err := Version(version) 38 if err != nil { 39 panic(fmt.Errorf("cannot compile go-version version '%s': %w", version, err)) 40 } 41 return ver 42 } 43 44 // Version wraps go-version.NewVersion, panicing when an error is 45 // returns (this occurs when the version cannot be parsed). 46 func Version(version string) (semver.Version, error) { 47 ver, err := semver.ParseTolerant(version) 48 if err != nil { 49 return ver, err 50 } 51 52 if len(ver.Pre) == 0 { 53 return ver, nil 54 } 55 56 for _, pre := range ver.Pre { 57 if strings.Contains(pre.VersionStr, "rc") || 58 strings.Contains(pre.VersionStr, "beta") || 59 strings.Contains(pre.VersionStr, "alpha") || 60 strings.Contains(pre.VersionStr, "snapshot") { 61 return ver, nil 62 } 63 } 64 65 strSegments := make([]string, 3) 66 strSegments[0] = strconv.Itoa(int(ver.Major)) 67 strSegments[1] = strconv.Itoa(int(ver.Minor)) 68 strSegments[2] = strconv.Itoa(int(ver.Patch)) 69 verStr := strings.Join(strSegments, ".") 70 return semver.ParseTolerant(verStr) 71 }