[Awesome Go] Use go-version to parse, compare and verify versions

go-version

go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version can sort a collection of versions properly, handles prerelease/beta versions, can increment versions, etc.

Versions used with go-version must follow Semantic Versioning 2.0.0 | Semantic Versioning - https://semver.org/.

Installation

Standard go get:

1
$ go get -u github.com/hashicorp/go-version

Usages

Version Parsing and Comparison

1
2
3
4
5
6
7
8
9
10
11
12
v1, err := version.NewVersion("1.2")
v2, err := version.NewVersion("1.5+metadata")

// Comparison example. There is also GreaterThan, Equal, and just
// a simple Compare that returns an int allowing easy >=, <=, etc.
if v1.LessThan(v2) {
fmt.Printf("%s is less than %s", v1, v2)
}

if v1.Compare(v2) == -1 {
mt.Printf("%s is less than %s", v1, v2)
}

Version Constraints

1
2
3
4
5
6
7
v1, err := version.NewVersion("1.2")

// Constraints example.
constraints, err := version.NewConstraint(">= 1.0, < 1.4")
if constraints.Check(v1) {
fmt.Printf("%s satisfies constraints %s", v1, constraints)
}

Version Sorting

1
2
3
4
5
6
7
8
9
versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"}
versions := make([]*version.Version, len(versionsRaw))
for i, raw := range versionsRaw {
v, _ := version.NewVersion(raw)
versions[i] = v
}

// After this, the versions are properly sorted
sort.Sort(version.Collection(versions))

Version Prerelease

1
2
v1, err := version.NewVersion("1.2-beta")
v1.Prerelease() // "beta"

Version Segments

1
2
3
v1, err := version.NewVersion("1.2")
v1.Segments() // {1, 2}
// Or v1.Segments64

See go-version/version_test.go at master · hashicorp/go-version - https://github.com/hashicorp/go-version/blob/master/version_test.go to learn more usages.

References

[1] hashicorp/go-version: A Go (golang) library for parsing and verifying versions and version constraints. - https://github.com/hashicorp/go-version

[2] Semantic Versioning 2.0.0 | Semantic Versioning - https://semver.org/