🔢 Version Comparison
The version_compare module (version_compare.go) provides version-string comparison and range checking. It is backed by the github.com/scagogogo/versions package for parsing version numbers.
Type
VersionRange
type VersionRange struct {
MinVersion string // inclusive lower bound
MaxVersion string // inclusive upper bound
}A closed version interval.
Functions
CompareVersions
func CompareVersions(v1, v2 string) intCompares two version strings.
Parameters:
v1— first versionv2— second version
Returns:
int—-1ifv1 < v2;0if equal;1ifv1 > v2
Example:
fmt.Println(cpeskills.CompareVersions("1.2.0", "1.2.1")) // -1
fmt.Println(cpeskills.CompareVersions("2.0", "1.9.9")) // 1
fmt.Println(cpeskills.CompareVersions("1.0", "1.0")) // 0IsVersionInRange
func IsVersionInRange(version, minVersion, maxVersion string) boolChecks whether version falls in the closed interval [minVersion, maxVersion]. An empty bound means that side is unbounded.
Parameters:
version— version to testminVersion— lower bound (empty = no lower bound)maxVersion— upper bound (empty = no upper bound)
Returns:
bool— whether in range
IsSubVersion
func IsSubVersion(parentVersion, subVersion string) boolChecks whether subVersion is a sub-version of parentVersion. For example 1.0.1 is a sub-version of 1.0: the numeric prefix of the child must match the parent exactly and be at least as long.
Parameters:
parentVersion— parent versionsubVersion— candidate sub-version
Returns:
bool— whether it is a sub-version
Example:
cpeskills.IsSubVersion("1.0", "1.0.5") // true
cpeskills.IsSubVersion("1.0", "1.1") // falseParseVersionRange
func ParseVersionRange(s string) (*VersionRange, error)Parses a version-range string. Supported formats:
"1.0"→ exact version (Min and Max both1.0)"1.0-2.0"→ range from 1.0 to 2.0"1.0+"→ 1.0 and above (Max empty)"-2.0"→ 2.0 and below (Min empty)
Parameters:
s— range string
Returns:
*VersionRange— parsed rangeerror— error on empty input
Example:
vr, err := cpeskills.ParseVersionRange("1.0-2.0")
if err != nil {
log.Fatal(err)
}
fmt.Println(vr.MinVersion, vr.MaxVersion) // 1.0 2.0VersionRange.Contains
func (vr *VersionRange) Contains(version string) boolChecks whether a version falls within this range (equivalent to IsVersionInRange(version, vr.MinVersion, vr.MaxVersion)).
Parameters:
version— version to test
Returns:
bool— whether in range