Hi, I’m @Luo Zhu

This article was first published on luo Zhu’s official website

This article synchronizes in the public account “luo Zhu early teahouse”, reprint please contact the author.

Creation is not easy, form a habit, quality three even!

A Go (Golang) library for parsing and validating versions and version constraints.

This library can be understood as a simplified version of Semver, where go-Version is a library for resolving versions and version constraints, and validating versions against a set of constraints. Go-version can properly sort version sets, handle prerelease/beta builds, can increment builds, and so on.

The version used with go-version must follow SemVer.

The installation

You can view the package documentation on GoDoc.

You can use Go Get to complete the installation:

$ go get github.com/hashicorp/go-version
Copy the code

Version Parsing and Comparison

v1, err := version.NewVersion("1.2")
v2, err := version.NewVersion("1.5 + metadata")

// Compare examples. There are also GreaterThan, Equal, and methods that allow simple comparisons using '>=', '<=' and return an int value
if v1.LessThan(v2) {
    fmt.Printf("%s is less than %s", v1, v2)
}
Copy the code

Version constraint

v1, err := version.NewVersion("1.2")

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

Edition version of the sort

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 a few operations, the versions are nicely sorted
sort.Sort(version.Collection(versions))
Copy the code

Issues and Contributing

If you find a problem with this library, please report the problem. If you like, we welcome any contributions. Fork the library and submit a pull request.