A Go (golang) library for parsing and verifying versions and version constraints.

Versioning Library for Go

Build Status GoDoc

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 SemVer.

Installation and Usage

Package documentation can be found on GoDoc.

Installation can be done with a normal go get:

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

Version Parsing and Comparison

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)
}

Version Constraints

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

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))

Issues and Contributing

If you find an issue with this library, please report an issue. If you'd like, we welcome any contributions. Fork this library and submit a pull request.

Owner
HashiCorp
Consistent workflows to provision, secure, connect, and run any infrastructure for any application.
HashiCorp
Comments
  • Feature/4ormoredots

    Feature/4ormoredots

    We ran into an issue where we had version strings with more specificity than 3 dots - We had to hack around it for the time being, but we'd ultimately appreciate if the library could natively support this.

    I took a crack at changing the Regex - It now supports an unlimited number of dots (because no matter what number I pick, someone else will need it bumped up by 1 some day), and altered a few things to support that (removing the cap on the segments slice), and added some comments around why some code still refers to 3 places (such as where you handle the segments being less than 3 in number, to support the default case of MAJOR.MINOR.PATCH).

    I also had to update the way the pessimistic comparator worked, to cover the additional edge cases present in the ability to support a greater specificity, as well as problems stemming from a jagged or uneven specificity between constraints and versions that I wasn't sure was explicitly being covered properly.

    I also added test cases to cover this.

    And I fixed an annoying nag from the go tools about replacing +=1 with ++, along with one about a syntax change to a range iterator.

  • Enable Sourcegraph

    Enable Sourcegraph

    I want to use Sourcegraph for go-version code search, browsing, and usage examples. Can an admin enable Sourcegraph for this repository? Just go to https://sourcegraph.com/github.com/hashicorp/go-version. (It should only take 30 seconds.)

    Thank you!

  • Adding support for an optional v prefix.

    Adding support for an optional v prefix.

    While not part of the SemVer 2.0.0 spec, the leading v is common. The release tags on SemVer itself have the v prefix. While not part of the spec they are optional in practice.

    In practice the SemVer libraries in other languages support the optional v prefix. For example, node-semver (used by npm and common for node.js projects doing versioning) allows the v prefix.

    Note, my hope is to use this to add support for SemVer to Glide

  • Prerelease constraint handling

    Prerelease constraint handling

    The logic in fbe76cf doesn't seem quite right. In particular, consider the use-case here: https://github.com/gesellix/couchdb-prometheus-exporter/blob/master/lib/couchdb-client.go#L52-L69 where we are checking if the server version is >= 2.0 and the reported version is e.g. 2.2.0-302bd8b. Clearly, in this scenario, the constraint check should return true (but it returns false). At the very least, the constraint needs to be able to opt-out of this mode.

    https://semver.org/#spec-item-11 implies that 2.2.0-pre >= 2.0 should be true: "1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0." I can certainly see the case for not wanting to match pre-releases at all in certain circumstances.

  • Fix function comments based on best practices from Effective Go

    Fix function comments based on best practices from Effective Go

    Every exported function in a program should have a doc comment. The first sentence should be a summary that starts with the name being declared. From effective go.

    I generated this with CodeLingo and I'm keen to get some feedback, but this is automated so feel free to close it and just say "opt out" to opt out of future CodeLingo outreach PRs.

  • Adhere to semvar pre-release separator

    Adhere to semvar pre-release separator

    The semvar specifications X.Y.Z states Z must be non-negative integers. Without a hyphen - between the version and a pre-release identifier, Z is no longer an integer and is alphanumeric.

    A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically. For instance: 1.9.0 -> 1.10.0 -> 1.11.0

    this is introducing a backwards incompatible change

  • Fixes version parsing for versions including ~

    Fixes version parsing for versions including ~

    • Closes https://github.com/terraform-providers/terraform-provider-mysql/issues/6
    • ~ comes in a lot of packages as part of the Debian package versioning: http://aalvarez.me/blog/posts/debian-package-versioning.html
  • Add tests about pre releases

    Add tests about pre releases

    I tried add tests and source code about prerelease following the semver precedence: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1

    But probably this patch needs revision.

    :cloud:

  • Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents

    Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents

    Technically quoted string is valid JSON, but in the context of go-version we deal with single line of text being serialized or unserialized, not structures which are more common for JSON or YAML.

    Implementing encoding.TextMarshaler and encoding.TextUnmarshaler retains the same functionality (as demonstrated by existing passing tests) since json.Marshal and json.Unmarshal will both reflect that interface and makes it work for other formats, such as YAML.

    cc @Jukie

  • add Core func

    add Core func

    Adds a Core function to Version, which returns a new Version created from only the MAJOR.MINOR.PATCH segments of the original version, without prerelease or metadata strings.

    Consumers of go-version often want to treat prereleases of versions as equal to non-prerelease versions, e.g. 0.15.0-dev as equal to 0.15.0. The present functionality is intended as an easy way to opt in to this behaviour.

    Example in a library used by the Terraform Language Server: https://github.com/hashicorp/terraform-schema/blob/8c206fbd85ae346716b4efbd776c8b8097fc5b42/schema/core_schema.go#L47-L52

  • fix pre-release checks in constraints

    fix pre-release checks in constraints

    Pre-releases should not be automatically accepted as candidate versions for constraints without a pre-release component. This follows the logic documented for RubyGems which appears to be the inspiration for the constraint operators, and matches the behavior of other version packages.

    Adding a pre-release component to a pessimistic constraint will limit accepted versions to pre-releases only. Adding a pre-release to other constraint types will accept any comparable version, including pre-releases.

  • GHA Migration

    GHA Migration

    This PR officially migrates go-version to GHA from CircleCI. It's intention is to work the same as the CircleCI tests but in GHA format.

    Note: I've added a matrix that keeps go1.15.3 to ensure that we maintain compatibility and also added the latest go version [1.19] to ensure that we are maintaining the repo and keeping it up to date.

  • Prerelease String shouldn't always be treated as lower version

    Prerelease String shouldn't always be treated as lower version

    Hey, I've found some irregularity where I have the following two versions for tcpdump 4.9.3-4ubuntu0.1 4.9.3

    Using the example code from the readme we get that 4.9.3 is greater than 4.9.3-4ubuntu0.1 even though that's not the case Link to playground to see my tests.

    I'm pretty sure that 4ubuntu0.1 doesn't mean it's a prerelease version and it's a widely used suffix. In other compiled binaries for ubuntu.

    I'm not sure what's the correct approach to solve this, but I was wondering whether we should narrow down the behavior when evaluating the prerelease string. WDYT?

  • Incorrect hanling of prerelease in constraints

    Incorrect hanling of prerelease in constraints

      v, _ := version.NewVersion("1.1.8-alpha1")
      if fast_check, err := version.NewConstraint(">= 1.1.7"); err == nil {
        if fast_check.Check(v) {
          fmt.Printf("OK: %v >= 1.1.7\n", v)
        } else {
          fmt.Printf("BUG: %v < 1.1.7\n", v)
        }
    

    Constraint check incorrectly returns false, which is obviously a bug.

  • Skipping some versions

    Skipping some versions

    Hello, I want to make a smooth migration for AWS provider from version 3 to 4.9.0 or newer https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-4-upgrade In Node.js world it is possible to define allowed version of a package like this: <1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0 So for my scenario Node.js-like version constraint would look like this: >= 3.0 < 4.0 || >= 4.9 < 5.0

    But when I try to do something similar for AWS provider in terraform this is the only working possibility >= 3.0, != 4.0, != 4.1, != 4.2, != 4.3, != 4.4, != 4.5, != 4.6, != 4.7, != 4.8, < 5.0 or am I missing something?

  • Proposal: Add version diff

    Proposal: Add version diff

    go-version currently supports comparing versions as a whole, e.g. 2.3.4 > 1.2.3. Sometimes we need to determine if the difference between versions is a major change, a minor change, etc.

    Since Compare() supports an arbitrary number of components, the diff should as well.

    Only the first diff is likely to be relevant, as in the diff of 2.3.4 vs 1.2.3, we care about the major version change, and the minor version changes are not meaningful.

    I can work on this if this sounds good. We're going to be using a very pared-down version of this in the AWS Provider.

  • [question] which is bigger according the constraint?

    [question] which is bigger according the constraint?

    I have a range of the versions and a version that I need to check if it is inside the range. the constraint that I build was:

    element 0: >=3.6.6
    element 1: <3.6.8-15.1
    

    (see screenshot for clearer vision) image

    The version that I'm checking is 3.6.8 The check is returning false on the "less than" element (<3.6.8-15.1)

    Why does 3.6.8-15.1 considered not bigger than 3.6.8?

Related tags
Molecule is a Go library for parsing protobufs in an efficient and zero-allocation manner

Molecule Molecule is a Go library for parsing protobufs in an efficient and zero-allocation manner. The API is loosely based on this excellent Go JSON

Sep 6, 2022
Simple library to handle ANSI functions and parsing of color formatting strings

Emerald A basic color library for use in my Go projects, built on top of mgutz/ansi. Package ansi is a small, fast library to create ANSI colored stri

Nov 15, 2021
A library for parsing ANSI encoded strings
 A library for parsing ANSI encoded strings

Go ANSI Parser converts strings with ANSI escape codes into a slice of structs that represent styled text

Jun 27, 2022
A small & fast dependency-free library for parsing micro expressions.

MicroExpr A small & fast dependency-free library for parsing micro expressions. This library was originally built for use in templating languages (e.g

Aug 27, 2022
A utility library to do files/io/bytes processing/parsing in file-system or network.

goreader A utility library to do files/io/bytes processing/parsing in file-system or network. These features are really common to be implemented for a

Nov 1, 2021
This library provides an ASTERIX Frame(binary data) decoding/parsing(json,xml) capabilities for Go.

GoAsterix This library provides an ASTERIX Frame(binary data) decoding/parsing(json,xml) capabilities for Go. ASTERIX ASTERIX (All Purpose Structured

Jun 1, 2022
Golang source code parsing, usage like reflect package

gotype Golang source code parsing, usage like reflect package English 简体中文 Usage API Documentation Examples License Pouch is licensed under the MIT Li

Aug 31, 2022
Go-path - A helper package that provides utilities for parsing and using ipfs paths

go-path is a helper package that provides utilities for parsing and using ipfs paths

Jan 18, 2022
Small utility to allow simpler, quicker testing of parsing files in crowdsec

cs_parser_test Small utility to allow simpler, quicker testing of parsing files in crowdsec Usage $ sudo cs_parser_test -t syslog /var/log/mail.log N

Jul 13, 2021
Gene parsing package for Axie Infinity

agp Package agp is a gene parsing package for Axie Infinity. The name agp stands for "Axie Gene Parser" which decodes the hex representation of an Axi

Apr 18, 2022
Yet another semantic version incrementor and tagger for git

git-tag-inc Increments the version number and tags it. (You will need to push) Usage ./git-tag-inc [major] [minor] [release] [test] [uat] git-tag-in

Apr 30, 2022
yaml-patch is a version of Evan Phoenix's json-patch, which is an implementation of JSON Patch, directly transposed to YAML

yaml-patch yaml-patch is a version of Evan Phoenix's json-patch, which is an implementation of JavaScript Object Notation (JSON) Patch, directly trans

Jan 15, 2022
Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package.
Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package.

Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package. The library allows you to call Go service methods from PHP with a minimal footprint, structures and []byte support.

Sep 22, 2022
A well tested and comprehensive Golang statistics library package with no dependencies.

Stats - Golang Statistics Package A well tested and comprehensive Golang statistics library / package / module with no dependencies. If you have any s

Sep 24, 2022
Cogger is a standalone binary and a golang library that reads an internally tiled geotiff

Cogger is a standalone binary and a golang library that reads an internally tiled geotiff (optionally with overviews and masks) and rewrites it

Sep 23, 2022
GoDynamic can load and run Golang dynamic library compiled by -buildmode=shared -linkshared

GoDynamic can load and run Golang dynamic library compiled by -buildmode=shared -linkshared How does it work? GoDynamic works like a dynamic

Aug 31, 2022
A golang library to validate and format swiss social security numbers

s3n is a golang library to validate and format swiss social security numbers (aka. AVS in french and AHV in german).

Nov 15, 2021
Govalid is a data validation library that can validate most data types supported by golang

Govalid is a data validation library that can validate most data types supported by golang. Custom validators can be used where the supplied ones are not enough.

Apr 22, 2022
Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

go-attr Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs. This package provides user frien

Jul 5, 2022