From 3f6796aa059bfb2c19ab750f096664e47135d7f4 Mon Sep 17 00:00:00 2001 From: Juan Ariza Toledano Date: Thu, 30 Nov 2023 09:23:45 +0100 Subject: [PATCH] feat: initial version package (#1) --- README.md | 128 +++++++++ go.mod | 15 ++ go.sum | 24 ++ pkg/version/constraint.go | 229 ++++++++++++++++ pkg/version/constraint_option.go | 15 ++ pkg/version/constraint_test.go | 430 +++++++++++++++++++++++++++++++ pkg/version/version.go | 295 +++++++++++++++++++++ pkg/version/version_test.go | 92 +++++++ 8 files changed, 1228 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 pkg/version/constraint.go create mode 100644 pkg/version/constraint_option.go create mode 100644 pkg/version/constraint_test.go create mode 100644 pkg/version/version.go create mode 100644 pkg/version/version_test.go diff --git a/README.md b/README.md index df50d52..d10bb93 100644 --- a/README.md +++ b/README.md @@ -1 +1,129 @@ # go-version + +[![Go Report Card](https://goreportcard.com/badge/github.com/bitnami/go-version)](https://goreportcard.com/report/github.com/bitnami/go-version) +[![CI](https://github.com/bitnami/gonit/actions/workflows/go.yml/badge.svg)](https://github.com/bitnami/gonit/actions/workflows/go.yml) + +go-version is a library for parsing Bitnami packages versions and version constraints, and verifying versions against a set of constraints. + + + + +- [Usage](#usage) + - [Version parsing and comparison](#version-parsing-and-comparison) + - [Version constraints](#version-constraints) + - [Version revision](#version-revision) + - [Missing major/minor/patch versions](#missing-majorminorpatch-versions) +- [License](#license) + + + +## Usage + +Versions used with `version` package must follow [Semantic Versioning](https://semver.org/) with a small adjustments: **pre-release versions are considered revisions** and, therefore, the bigger the revision number, the newer the version. + +### Version parsing and comparison + +When two versions are compared using functions such as Compare, LessThan, and others, it will follow the specification and always include revisions within the comparison. +It will provide an answer that is valid with the comparison section of [the spec](https://semver.org/#spec-item-11). + +```go +v1, _ := version.Parse("1.2.0") +v2, _ := version.Parse("1.2.1") + +// 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 + +Comma-separated version constraints are considered an `AND`. For example, `>= 1.2.3, < 2.0.0` means the version needs to be greater than or equal to `1.2` and less than `3.0.0`. +In addition, they can be separated by `|| (OR)`. For example, `>= 1.2.3, < 2.0.0 || > 4.0.0` means the version needs to be greater than or equal to `1.2` and less than `3.0.0`, or greater than `4.0.0`. + +```go +v, _ := version.Parse("2.1.0") +c, _ := version.NewConstraints(">= 1.0, < 1.4 || > 2.0") + +if c.Check(v) { + fmt.Printf("%s satisfies constraints '%s'", v, c) +} +``` + +Supported operators: + +- `=` : you accept that exact version +- `!=` : not equal +- `>` : you accept any version higher than the one you specify +- `>=` : you accept any version equal to or higher than the one you specify +- `<` : you accept any version lower to the one you specify +- `<=` : you accept any version equal or lower to the one you specify +- `^` : it will only do updates that do not change the leftmost non-zero number. + - e.g. `^1.2.3` := `>=1.2.3, <2.0.0` +- `~` : allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. + - e.g. `~1.2.3` := `>=1.2.3, <1.3.0` + +#### Version revision + +A revision may be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Revision have a greater precedence than the associated normal version (e.g. `1.2.3-1 > 1.2.3`). + +```go +v, _ := version.Parse("2.0.0") +c, _ := version.NewConstraints(">2.0.0-2") + +c.Check(v) // false +``` + +Comparisons include revisions even with no revisions constraint: + +```go +v, _ := version.Parse("2.0.0-1") +c, _ := version.NewConstraints(">2.0.0") + +c.Check(v) // true +``` + +#### Missing major/minor/patch versions + +If some of major/minor/patch versions are not specified, it is treated as `*` by default. In short, `3.1.3` satisfies `= 3` because `= 3` is converted to `= 3.*.*`. + +```go +v, _ := version.Parse("2.3.4") +c, _ := version.NewConstraints("=2") + +c.Check(v) // true +``` + +Then, `2.2.3` doesn't satisfy `> 2` as `> 2` is treated as `> 2.*.*` = `>= 3.0.0` + +```go +v, _ := version.Parse("2.2.3") +c, _ := version.NewConstraints(">2") + +c.Check(v) // false +``` + +`3.3.9` satisifies `= 3.3`, and `5.1.2` doesn't satisfy `> 5.1` likewise. + +If you want to treat them as 0, you can pass `version.WithZeroPadding(true)` as an argument of `version.NewConstraints` + +```go +v, _ := version.Parse("2.3.4") +c, _ := version.NewConstraints("= 2", version.WithZeroPadding(true)) + +c.Check(v) // false +``` + +## License + +Copyright © 2023 VMware, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e8ca5f2 --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module github.com/bitnami/go-version + +go 1.20 + +require ( + github.com/aquasecurity/go-version v0.0.0-20210121072130-637058cfe492 + github.com/stretchr/testify v1.8.4 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e369f02 --- /dev/null +++ b/go.sum @@ -0,0 +1,24 @@ +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/aquasecurity/go-version v0.0.0-20210121072130-637058cfe492 h1:rcEG5HI490FF0a7zuvxOxen52ddygCfNVjP0XOCMl+M= +github.com/aquasecurity/go-version v0.0.0-20210121072130-637058cfe492/go.mod h1:9Beu8XsUNNfzml7WBf3QmyPToP1wm1Gj/Vc5UJKqTzU= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/version/constraint.go b/pkg/version/constraint.go new file mode 100644 index 0000000..f1695b4 --- /dev/null +++ b/pkg/version/constraint.go @@ -0,0 +1,229 @@ +package version + +import ( + "fmt" + "regexp" + "strings" + + "github.com/aquasecurity/go-version/pkg/part" +) + +const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + +var ( + constraintOperators = map[string]operatorFunc{ + "": constraintEqual, + "=": constraintEqual, + "==": constraintEqual, + "!=": constraintNotEqual, + ">": constraintGreaterThan, + "<": constraintLessThan, + ">=": constraintGreaterThanEqual, + "=>": constraintGreaterThanEqual, + "<=": constraintLessThanEqual, + "=<": constraintLessThanEqual, + "~": constraintTilde, + "^": constraintCaret, + } + constraintRegexp *regexp.Regexp + validConstraintRegexp *regexp.Regexp +) + +type operatorFunc func(v, c Version) bool + +func init() { + ops := make([]string, 0, len(constraintOperators)) + for k := range constraintOperators { + ops = append(ops, regexp.QuoteMeta(k)) + } + + constraintRegexp = regexp.MustCompile(fmt.Sprintf( + `(%s)\s*(%s)`, + strings.Join(ops, "|"), + cvRegex)) + + validConstraintRegexp = regexp.MustCompile(fmt.Sprintf( + `^\s*(\s*(%s)\s*(%s)\s*\,?)*\s*$`, + strings.Join(ops, "|"), + cvRegex)) +} + +type Constraints struct { + constraints [][]constraint + conf conf +} + +// NewConstraints parses a given constraint and returns a new instance of Constraints +func NewConstraints(v string, opts ...ConstraintOption) (Constraints, error) { + c := new(conf) + + // Apply options + for _, o := range opts { + o.apply(c) + } + + var css [][]constraint + for _, vv := range strings.Split(v, "||") { + // Validate the segment + if !validConstraintRegexp.MatchString(vv) { + return Constraints{}, fmt.Errorf("improper constraint: %s", vv) + } + + ss := constraintRegexp.FindAllString(vv, -1) + if ss == nil { + ss = append(ss, strings.TrimSpace(vv)) + } + + var cs []constraint + for _, single := range ss { + c, err := newConstraint(single, *c) + if err != nil { + return Constraints{}, err + } + cs = append(cs, c) + } + css = append(css, cs) + } + + return Constraints{ + constraints: css, + conf: *c, + }, nil +} + +// Returns the string format of the constraints +func (cs Constraints) String() string { + var csStr []string + for _, orC := range cs.constraints { + var cstr []string + for _, andC := range orC { + cstr = append(cstr, andC.String()) + } + csStr = append(csStr, strings.Join(cstr, ",")) + } + + return strings.Join(csStr, "||") +} + +// Constraints is one or more constraint that a semantic version can be +// checked against. +type constraint struct { + version Version + operator operatorFunc + original string +} + +func newConstraint(c string, conf conf) (constraint, error) { + if c == "" { + return constraint{ + version: Version{ + major: part.Any(true), + minor: part.Any(true), + patch: part.Any(true), + revision: part.NewParts("*"), + }, + operator: constraintOperators[""], + }, nil + } + + m := constraintRegexp.FindStringSubmatch(c) + if m == nil { + return constraint{}, fmt.Errorf("improper constraint: %s", c) + } + + major := m[3] + minor := strings.TrimPrefix(m[4], ".") + patch := strings.TrimPrefix(m[5], ".") + + v := Version{ + major: newPart(major, conf), + minor: newPart(minor, conf), + patch: newPart(patch, conf), + original: c, + } + + revision := part.NewParts(strings.TrimPrefix(m[6], "-")) + if revision.IsNull() && v.IsAny() { + revision = append(revision, part.Any(true)) + } + v.revision = revision + + return constraint{ + version: v, + operator: constraintOperators[m[1]], + original: c, + }, nil +} + +func newPart(p string, conf conf) part.Part { + if p == "" { + return part.NewEmpty(!conf.zeroPadding) + } + return part.NewPart(p) +} + +func (c constraint) String() string { + return c.original +} + +// Check tests if a version satisfies all the constraints. +func (cs Constraints) Check(v Version) bool { + for _, c := range cs.constraints { + if andCheck(v, c, cs.conf) { + return true + } + } + + return false +} + +func (c constraint) check(v Version, conf conf) bool { + return c.operator(v, c.version) +} + +func andCheck(v Version, constraints []constraint, conf conf) bool { + for _, c := range constraints { + if !c.check(v, conf) { + return false + } + } + return true +} + +//------------------------------------------------------------------- +// Constraint functions +//------------------------------------------------------------------- + +func constraintEqual(v, c Version) bool { + return v.Equal(c) +} + +func constraintNotEqual(v, c Version) bool { + return !v.Equal(c) +} + +func constraintGreaterThan(v, c Version) bool { + return v.GreaterThan(c) +} + +func constraintLessThan(v, c Version) bool { + return v.LessThan(c.Min()) +} + +func constraintGreaterThanEqual(v, c Version) bool { + return v.GreaterThanOrEqual(c) +} + +func constraintLessThanEqual(v, c Version) bool { + return v.LessThanOrEqual(c) +} + +func constraintTilde(v, c Version) bool { + return v.GreaterThanOrEqual(c) && v.LessThan(c.TildeBump()) +} + +func constraintCaret(v, c Version) bool { + return v.GreaterThanOrEqual(c) && v.LessThan(c.CaretBump()) +} diff --git a/pkg/version/constraint_option.go b/pkg/version/constraint_option.go new file mode 100644 index 0000000..b5fab7c --- /dev/null +++ b/pkg/version/constraint_option.go @@ -0,0 +1,15 @@ +package version + +type conf struct { + zeroPadding bool +} + +type ConstraintOption interface { + apply(*conf) +} + +type WithZeroPadding bool + +func (o WithZeroPadding) apply(c *conf) { + c.zeroPadding = bool(o) +} diff --git a/pkg/version/constraint_test.go b/pkg/version/constraint_test.go new file mode 100644 index 0000000..0b00a06 --- /dev/null +++ b/pkg/version/constraint_test.go @@ -0,0 +1,430 @@ +package version + +import ( + "testing" + + "github.com/aquasecurity/go-version/pkg/part" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewConstraints(t *testing.T) { + tests := []struct { + input string + opts []ConstraintOption + want Constraints + wantErr bool + }{ + { + ">= 1.1", + nil, + Constraints{ + constraints: [][]constraint{{{ + version: Version{ + major: part.NewPart("1"), + minor: part.NewPart("1"), + patch: part.NewEmpty(true), + revision: part.Parts{ + part.Any(true), + }, + original: ">= 1.1", + }, + operator: constraintGreaterThanEqual, + original: ">= 1.1", + }}}, + }, + false, + }, + { + ">= 1.1", + []ConstraintOption{ + WithZeroPadding(true), + }, + Constraints{ + constraints: [][]constraint{{{ + version: Version{ + major: part.NewPart("1"), + minor: part.NewPart("1"), + patch: part.NewEmpty(false), + revision: nil, + original: ">= 1.1", + }, + operator: constraintGreaterThanEqual, + original: ">= 1.1", + }}}, + }, + false, + }, + { + ">40.50.60, < 50.70", + nil, + Constraints{ + constraints: [][]constraint{{{ + version: Version{ + major: part.NewPart("40"), + minor: part.NewPart("50"), + patch: part.NewPart("60"), + revision: nil, + original: ">40.50.60", + }, + operator: constraintGreaterThan, + original: ">40.50.60", + }, { + version: Version{ + major: part.NewPart("50"), + minor: part.NewPart("70"), + patch: part.NewEmpty(true), + revision: part.Parts{ + part.Any(true), + }, + original: "< 50.70", + }, + operator: constraintLessThan, + original: "< 50.70", + }}}, + }, + false, + }, + { + ">= bar", + nil, + Constraints{}, + true, + }, + } + t.Parallel() + for _, testToRun := range tests { + test := testToRun + t.Run(test.input, func(tt *testing.T) { + tt.Parallel() + got, err := NewConstraints(test.input, test.opts...) + if test.wantErr { + assert.NotNil(tt, err) + } else { + assert.NoError(tt, err) + assert.Len(tt, got.constraints, len(test.want.constraints)) + for i, c := range got.constraints { + for j, cc := range c { + assert.Equal(tt, test.want.constraints[i][j].version, cc.version) + assert.Equal(tt, test.want.constraints[i][j].original, cc.original) + } + } + } + }) + } +} + +func TestConstraints_Check(t *testing.T) { + tests := []struct { + constraint string + version string + want bool + }{ + // Equal: = + {"=2.0.0", "1.2.3", false}, + {"=2.0.0", "2.0.0", true}, + {"=2.0", "1.2.3", false}, + {"=2.0", "2.0.0", true}, + {"=2.0", "2.0.1", true}, + {"=0", "1.0.0", false}, + // Equal: == + {"== 2.0.0", "1.2.3", false}, + {"==2.0.0", "2.0.0", true}, + {"== 2.0", "1.2.3", false}, + {"==2.0", "2.0.0", true}, + {"== 2.0", "2.0.1", true}, + {"==0", "1.0.0", false}, + // Equal without "=" + {"4.1", "4.1.0", true}, + {"2", "1.0.0", false}, + {"2", "3.4.5", false}, + {"2", "2.1.1", true}, + {"2.1", "2.1.1", true}, + {"2.1", "2.2.1", false}, + // Not equal + {"!=4.1.0", "4.1.0", false}, + {"!=4.1.0", "4.1.1", true}, + {"!=4.1", "4.1.0", false}, + {"!=4.1", "4.1.1", false}, + {"!=4.1", "5.1.0", true}, + // Less than + {"<11", "0.1.0", true}, + {"<11", "11.1.0", false}, + {"<1.1", "0.1.0", true}, + {"<1.1", "1.1.0", false}, + {"<1.1", "1.1.1", false}, + // Less than or equal + {"<=11", "1.2.3", true}, + {"<=11", "12.2.3", false}, + {"<=11", "11.2.3", true}, + {"<=1.1", "1.2.3", false}, + {"<=1.1", "0.1.0", true}, + {"<=1.1", "1.1.0", true}, + {"<=1.1", "1.1.1", true}, + // Greater than + {">1.1", "4.1.0", true}, + {">1.1", "1.1.0", false}, + {">0", "0.0.0", false}, + {">0", "1.0.0", true}, + {">11", "11.1.0", false}, + {">11.1", "11.1.0", false}, + {">11.1", "11.1.1", false}, + {">11.1", "11.2.1", true}, + // Greater than or equal + {">=11", "11.1.2", true}, + {">=11.1", "11.1.2", true}, + {">=11.1", "11.0.2", false}, + {">=1.1", "4.1.0", true}, + {">=1.1", "1.1.0", true}, + {">=1.1", "0.0.9", false}, + {">=0", "0.0.0", true}, + {"=0", "1.0.0", false}, + // Asterisk + {"*", "1.0.0", true}, + {"*", "4.5.6", true}, + {"2.*", "1.0.0", false}, + {"2.*", "3.4.5", false}, + {"2.*", "2.1.1", true}, + {"2.1.*", "2.1.1", true}, + {"2.1.*", "2.2.1", false}, + // Empty + {"", "1.0.0", true}, + {"", "4.5.6", true}, + {"2", "1.0.0", false}, + {"2", "3.4.5", false}, + {"2", "2.1.1", true}, + {"2.1", "2.1.1", true}, + {"2.1", "2.2.1", false}, + // Tilde + {"~1.2.3", "1.2.4", true}, + {"~1.2.3", "1.3.4", false}, + {"~1.2", "1.2.4", true}, + {"~1.2", "1.3.4", false}, + {"~1", "1.2.4", true}, + {"~1", "2.3.4", false}, + {"~0.2.3", "0.2.5", true}, + {"~0.2.3", "0.3.5", false}, + {"^1.2.3", "1.8.9", true}, + {"^1.2.3", "2.8.9", false}, + {"^1.2.3", "1.2.1", false}, + {"^1.1.0", "2.1.0", false}, + {"^1.2.0", "2.2.1", false}, + {"^1.2", "1.8.9", true}, + {"^1.2", "2.8.9", false}, + {"^1", "1.8.9", true}, + {"^1", "2.8.9", false}, + {"^0.2.3", "0.2.5", true}, + {"^0.2.3", "0.5.6", false}, + {"^0.2", "0.2.5", true}, + {"^0.2", "0.5.6", false}, + {"^0.0.3", "0.0.3", true}, + {"^0.0.3", "0.0.4", false}, + {"^0.0", "0.0.3", true}, + {"^0.0", "0.1.4", false}, + {"^0.0", "1.0.4", false}, + {"^0", "0.2.3", true}, + {"^0", "1.1.4", false}, + // revision: Not equal + {"!=4.1", "5.1.0-1", true}, + {"!=4.1-1", "4.1.0", false}, + // revision: Greater than + {">0", "0.0.1-1", false}, + {">0.0", "0.0.1-1", false}, + {">0-0", "0.0.1-1", false}, + {">0.0-0", "0.0.1-1", false}, + {">0", "0.0.0-1", false}, + {">0-0", "0.0.0-1", false}, + {">0.0.0-0", "0.0.0-1", true}, + {">1.2.3-1", "1.2.3-2", true}, + {">1.2.3-1", "1.3.3-2", true}, + // revision: Less than + {"<0", "0.0.0-1", false}, + {"<0-2", "0.0.0-1", true}, + // revision: Greater than or equal + {">=0", "0.0.1-1", true}, + {">=0.0", "0.0.1-1", true}, + {">=0-0", "0.0.1-1", true}, + {">=0.0-0", "0.0.1", true}, + {">=0", "0.0.0-1", true}, + {">=0-0", "0.0.0-1", true}, + {">=0.0.0", "0.0.0-1", true}, + {">=0.0.0-0", "0.0.0-1", true}, + {">=0.0.0-2", "0.0.0-1", false}, + {">=0.0.0-0", "1.2.3", true}, + {">=0.0.0-0", "3.4.5-1", true}, + // revision: Asterisk + {"*", "1.2.3-1", true}, + // revision: Empty + {"", "1.2.3-1", true}, + // revision: Tilde + {"~1.2.3-1", "1.2.3-2", true}, + {"~1.2.3-1", "1.2.4-1", true}, + {"~1.2.3-1", "1.3.4-1", false}, + // revision: Caret + {"^1.2.0", "1.2.1-1", true}, + {"^1.2.0-0", "1.2.1-1", true}, + {"^1.2.0-0", "1.2.1-0", true}, + {"^1.2.0-2", "1.2.0-1", false}, + {"^0.2.3-3", "0.2.3-4", true}, + {"^0.2.3-3", "0.2.4-3", true}, + {"^0.2.3-3", "0.3.4-3", false}, + {"^0.2.3-3", "0.2.3-3", true}, + } + t.Parallel() + for _, testToRun := range tests { + test := testToRun + t.Run(test.constraint, func(tt *testing.T) { + tt.Parallel() + c, err := NewConstraints(test.constraint) + require.NoError(tt, err) + + v, err := Parse(test.version) + require.NoError(tt, err) + + got := c.Check(v) + assert.Equal(tt, test.want, got) + }) + } +} + +func TestConstraints_CheckWithZeroPadding(t *testing.T) { + tests := []struct { + constraint string + version string + want bool + }{ + // Equal + {"=2.0.0", "1.2.3", false}, + {"=2.0.0", "2.0.0", true}, + // Not equal + {"!=4.1.0", "4.1.0", false}, + {"!=4.1.0", "4.1.1", true}, + // Less than + {"<0.0.5", "0.1.0", false}, + {"<1.0.0", "0.1.0", true}, + // Less than or equal + {"<=0.2.3", "1.2.3", false}, + {"<=1.2.3", "1.2.3", true}, + // Greater than + {">5.0.0", "4.1.0", false}, + {">4.0.0", "4.1.0", true}, + // Greater than or equal + {">=11.1.3", "11.1.2", false}, + {">=11.1.2", "11.1.2", true}, + // Asterisk + {"*", "1.0.0", true}, + {"*", "4.5.6", true}, + {"2.*", "1.0.0", false}, + {"2.*", "3.4.5", false}, + {"2.*", "2.1.1", true}, + {"2.1.*", "2.1.1", true}, + {"2.1.*", "2.2.1", false}, + // Empty + {"", "1.0.0", true}, + {"", "4.5.6", true}, + {"2", "1.0.0", false}, + {"2", "3.4.5", false}, + {"2", "2.1.1", false}, + {"2.1", "2.1.1", false}, + {"2.1", "2.2.1", false}, + // Tilde + {"~1.2.3", "1.2.4", true}, + {"~1.2.3", "1.3.4", false}, + {"~1.2", "1.2.4", true}, + {"~1.2", "1.3.4", false}, + {"~1", "1.2.4", true}, + {"~1", "2.3.4", false}, + {"~0.2.3", "0.2.5", true}, + {"~0.2.3", "0.3.5", false}, + {"~1.2.3-beta.2", "1.2.3-beta.4", true}, + // Caret + {"^1.2.3", "1.8.9", true}, + {"^1.2.3", "2.8.9", false}, + {"^1.2.3", "1.2.1", false}, + {"^1.1.0", "2.1.0", false}, + {"^1.2.0", "2.2.1", false}, + {"^1.2", "1.8.9", true}, + {"^1.2", "2.8.9", false}, + {"^1", "1.8.9", true}, + {"^1", "2.8.9", false}, + {"^0.2.3", "0.2.5", true}, + {"^0.2.3", "0.5.6", false}, + {"^0.2", "0.2.5", true}, + {"^0.2", "0.5.6", false}, + {"^0.0.3", "0.0.3", true}, + {"^0.0.3", "0.0.4", false}, + {"^0.0", "0.0.3", true}, + {"^0.0", "0.1.4", false}, + {"^0.0", "1.0.4", false}, + {"^0", "0.2.3", true}, + {"^0", "1.1.4", false}, + // revision: Equal + {"=4.1", "4.1.0-1", false}, + {"=4.1-1", "4.1.0-1", true}, + {"== 4.1", "4.1.0-1", false}, + {"==4.1-1", "4.1.0-1", true}, + // revision: Not equal + {"!=4.1", "5.1.0-1", true}, + {"!=4.1-1", "4.1.0", true}, + // revision: Greater than + {">0", "0.0.1-1", true}, + {">0.0", "0.0.1-1", true}, + {">0-0", "0.0.1-1", true}, + {">0.0-0", "0.0.1-1", true}, + {">0", "0.0.0-1", true}, + {">0-0", "0.0.0-1", true}, + {">0.0.0-0", "0.0.0-1", true}, + {">1.2.3-1", "1.2.3-1", false}, + {">1.2.3-1", "1.2.3-2", true}, + {">1.2.3-1", "1.3.3-2", true}, + // revision: Less than + {"<0", "0.0.0-1", false}, + {"<0-2", "0.0.0-1", true}, + {"<0", "1.0.0-1", false}, + {"<1", "1.0.0-1", false}, + {"<2", "1.0.0-1", true}, + // revision: Greater than or equal + {">=0", "0.0.1-1", true}, + {">=0.0", "0.0.1-1", true}, + {">=0-0", "0.0.1-1", true}, + {">=0.0-0", "0.0.1-1", true}, + {">=0", "0.0.0-1", true}, + {">=0-0", "0.0.0-1", true}, + {">=0.0.0-1", "0.0.0-1", true}, + {">=0.0.0-2", "0.0.0-1", false}, + {">=0.0.0-0", "1.2.3", true}, + {">=0.0.0-0", "3.4.5-1", true}, + // revision: Asterisk + {"*", "1.2.3-1", true}, + // revision: Empty + {"", "1.2.3-1", true}, + // revision: Tilde + {"~1.2.3-1", "1.2.3-2", true}, + {"~1.2.3-1", "1.2.4-1", true}, + {"~1.2.3-1", "1.3.4-1", false}, + // revision: Caret + {"^1.2.0", "1.2.1-alpha.1", true}, + {"^1.2.0-0", "1.2.1-1", true}, + {"^1.2.0-0", "1.2.1-0", true}, + {"^1.2.0-2", "1.2.0-1", false}, + {"^0.2.3-2", "0.2.3-4", true}, + {"^0.2.3-2", "0.2.4-2", true}, + {"^0.2.3-2", "0.3.4-2", false}, + {"^0.2.3-2", "0.2.3-2", true}, + } + t.Parallel() + for _, testToRun := range tests { + test := testToRun + t.Run(test.constraint, func(tt *testing.T) { + tt.Parallel() + c, err := NewConstraints(test.constraint, WithZeroPadding(true)) + require.NoError(tt, err) + + v, err := Parse(test.version) + require.NoError(tt, err) + + got := c.Check(v) + assert.Equal(tt, test.want, got) + }) + } +} diff --git a/pkg/version/version.go b/pkg/version/version.go new file mode 100644 index 0000000..d866b91 --- /dev/null +++ b/pkg/version/version.go @@ -0,0 +1,295 @@ +package version + +import ( + "bytes" + "errors" + "fmt" + "math" + "regexp" + + "github.com/aquasecurity/go-version/pkg/part" + "github.com/aquasecurity/go-version/pkg/prerelease" +) + +var ( + // ErrInvalidSemVer is returned when a given version is invalid + ErrInvalidSemVer = errors.New("invalid semantic version") +) + +var versionRegex *regexp.Regexp + +// regex is the regular expression used to parse a SemVer string. +// See: https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +const regex string = `^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)` + + `(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))` + + `?(?:\+(?P[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$` + +func init() { + versionRegex = regexp.MustCompile(regex) +} + +// Version represents a semantic version. +type Version struct { + major, minor, patch part.Part + revision part.Parts + buildMetadata string + original string +} + +// New returns an instance of Version +func New(major, minor, patch part.Part, pre part.Parts, metadata string) Version { + return Version{ + major: major, + minor: minor, + patch: patch, + revision: pre, + buildMetadata: metadata, + } +} + +// Parse parses a given version and returns a new instance of Version +func Parse(v string) (Version, error) { + m := versionRegex.FindStringSubmatch(v) + if m == nil { + return Version{}, ErrInvalidSemVer + } + + major, err := part.NewUint64(m[versionRegex.SubexpIndex("major")]) + if err != nil { + return Version{}, fmt.Errorf("invalid major version: %w", err) + } + + minor, err := part.NewUint64(m[versionRegex.SubexpIndex("minor")]) + if err != nil { + return Version{}, fmt.Errorf("invalid minor version: %w", err) + } + + patch, err := part.NewUint64(m[versionRegex.SubexpIndex("patch")]) + if err != nil { + return Version{}, fmt.Errorf("invalid patch version: %w", err) + } + + return Version{ + major: major, + minor: minor, + patch: patch, + revision: part.NewParts(m[versionRegex.SubexpIndex("revision")]), + buildMetadata: m[versionRegex.SubexpIndex("buildmetadata")], + original: v, + }, nil +} + +// String converts a Version object to a string. +func (v Version) String() string { + var buf bytes.Buffer + + fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) + if !v.revision.IsNull() { + fmt.Fprintf(&buf, "-%s", v.revision) + } + if v.buildMetadata != "" { + fmt.Fprintf(&buf, "+%s", v.buildMetadata) + } + + return buf.String() +} + +// IsAny returns true if major, minor or patch is wild card +func (v Version) IsAny() bool { + return v.major.IsAny() || v.minor.IsAny() || v.patch.IsAny() +} + +// IncMajor produces the next major version. +// e.g. 1.2.3 => 2.0.0 +func (v Version) IncMajor() Version { + v.major = v.major.(part.Uint64) + 1 + v.minor = part.Zero + v.patch = part.Zero + v.revision = part.Parts{} + v.buildMetadata = "" + v.original = v.String() + return v +} + +// IncMinor produces the next minor version. +func (v Version) IncMinor() Version { + v.minor = v.minor.(part.Uint64) + 1 + v.patch = part.Zero + v.revision = part.Parts{} + v.buildMetadata = "" + v.original = v.String() + return v +} + +// IncPatch produces the next patch version. +func (v Version) IncPatch() Version { + v.patch = v.patch.(part.Uint64) + 1 + v.revision = part.Parts{} + v.buildMetadata = "" + v.original = v.String() + return v +} + +// Min produces the minimum version if it includes wild card. +// 1.2.* => 1.2.0 +// 1.*.* => 1.0.0 +func (v Version) Min() Version { + if v.major.IsAny() { + v.major = part.Zero + } + if v.minor.IsAny() { + v.minor = part.Zero + } + if v.patch.IsAny() { + v.patch = part.Zero + } + if v.revision.IsAny() { + v.revision = part.Parts{} + } + v.buildMetadata = "" + v.original = v.String() + return v +} + +// Original returns the original value. +func (v Version) Original() string { + return v.original +} + +// Major returns the major version. +func (v Version) Major() part.Part { + return v.major +} + +// Minor returns the minor version. +func (v Version) Minor() part.Part { + return v.minor +} + +// Patch returns the patch version. +func (v Version) Patch() part.Part { + return v.patch +} + +// Revision returns the revision. +func (v Version) Revision() part.Parts { + return v.revision +} + +// HasRevision returns if version has revision. +// 1.2.3 => false +// 1.2.3-1 => true +func (v Version) HasRevision() bool { + return !v.revision.IsNull() +} + +// Metadata returns the metadata on the version. +func (v Version) Metadata() string { + return v.buildMetadata +} + +// LessThan tests if one version is less than another one. +func (v Version) LessThan(o Version) bool { + return v.Compare(o) < 0 +} + +// LessThanOrEqual tests if this version is less than or equal to another version. +func (v Version) LessThanOrEqual(o Version) bool { + return v.Compare(o) <= 0 +} + +// GreaterThan tests if one version is greater than another one. +func (v Version) GreaterThan(o Version) bool { + return v.Compare(o) > 0 +} + +// GreaterThanOrEqual tests if this version is greater than or equal to another version. +func (v Version) GreaterThanOrEqual(o Version) bool { + return v.Compare(o) >= 0 +} + +// Equal tests if two versions are equal to each other. +// Note, versions can be equal with different metadata since metadata +// is not considered part of the comparable version. +func (v Version) Equal(o Version) bool { + return v.Compare(o) == 0 +} + +// Compare compares this version to another one. It returns -1, 0, or 1 if +// the version smaller, equal, or larger than the other version. +// +// Versions are compared by X.Y.Z. Build metadata is ignored. Revision is +// greater than the version without a revision. +func (v Version) Compare(o Version) int { + // Compare the major, minor, and patch version for differences. If a + // difference is found return the comparison. + result := v.major.Compare(o.major) + if result != 0 || v.major.IsAny() || o.major.IsAny() { + return result + } + result = v.minor.Compare(o.minor) + if result != 0 || v.minor.IsAny() || o.minor.IsAny() { + return result + } + result = v.patch.Compare(o.patch) + if result != 0 || v.patch.IsAny() || o.patch.IsAny() { + return result + } + + // At this point the major, minor, and patch versions are the same. + // We consider any revision to be greater than a version without a revision. + if v.HasRevision() && !o.HasRevision() { + return 1 + } else if !v.HasRevision() && o.HasRevision() { + return -1 + } + return prerelease.Compare(v.revision, o.revision) +} + +// TildeBump returns the maximum version of tilde ranges +// e.g. ~1.2.3 := >=1.2.3 <1.3.0 +// In this case, it returns 1.3.0 +// ref. https://docs.npmjs.com/cli/v6/using-npm/semver#tilde-ranges-123-12-1 +func (v Version) TildeBump() Version { + switch { + case v.major.IsAny(), v.major.IsEmpty(): + v.major = part.Uint64(math.MaxUint64) + return v + case v.minor.IsAny(), v.minor.IsEmpty(): + // e.g. 1 => 2.0.0 + return v.IncMajor() + case v.patch.IsAny(), v.patch.IsEmpty(): + // e.g. 1.2 => 1.3.0 + return v.IncMinor() + default: + // e.g. 1.2.3 => 1.3.0 + return v.IncMinor() + } +} + +// CaretBump returns the maximum version of caret ranges +// e.g. ^1.2.3 := >=1.2.3 <2.0.0 +// In this case, it returns 2.0.0 +// ref. https://docs.npmjs.com/cli/v6/using-npm/semver#caret-ranges-123-025-004 +func (v Version) CaretBump() Version { + switch { + case v.major.IsAny(), v.major.IsEmpty(): + v.major = part.Uint64(math.MaxUint64) + return v + case v.major.(part.Uint64) != 0: + // e.g. 1 => 2.0.0 + return v.IncMajor() + case v.minor.IsAny(), v.minor.IsEmpty(): + // e.g. 0 => 1.0.0 + return v.IncMajor() + case v.minor.(part.Uint64) != 0: + // e.g. 0.2.3 => 0.3.0 + return v.IncMinor() + case v.patch.IsAny(), v.patch.IsEmpty(): + // e.g. 0.0 => 0.1.0 + return v.IncMinor() + default: + // e.g. 0.0.3 => 0.0.4 + return v.IncPatch() + } +} diff --git a/pkg/version/version_test.go b/pkg/version/version_test.go new file mode 100644 index 0000000..5a8bcac --- /dev/null +++ b/pkg/version/version_test.go @@ -0,0 +1,92 @@ +package version + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParse(t *testing.T) { + tests := []struct { + version string + wantErr bool + }{ + {"1.2.3", false}, + {"1.2.3-alpha.01", true}, + {"1.2.3+test.01", false}, + {"1.2.3-alpha.-1", false}, + {"1.0", true}, + {"1", true}, + {"1.2.beta", true}, + {"foo", true}, + {"1.2-5", true}, + {"1.2-beta.5", true}, + {"\n1.2", true}, + {"1.2.0-x.Y.0+metadata", false}, + {"1.2.0-x.Y.0+metadata-width-hypen", false}, + {"1.2.3-rc1-with-hypen", false}, + {"1.2.3.4", true}, + {"1.2.2147483648", false}, + {"1.2147483648.3", false}, + {"2147483648.3.0", false}, + {"1.0.0-alpha", false}, + {"1.0.0-alpha.1", false}, + {"1.0.0-0.3.7", false}, + {"1.0.0-x.7.z.92", false}, + {"1.0.0-x-y-z.-", false}, + {"1.2.3.4", true}, + {"foo1.2.3", true}, + {"1.7rc2", true}, + {"1.0-", true}, + {"v1.2.3", true}, + } + t.Parallel() + for _, testToRun := range tests { + test := testToRun + t.Run(test.version, func(tt *testing.T) { + tt.Parallel() + _, err := Parse(test.version) + if test.wantErr { + assert.NotNil(tt, err) + } else { + assert.NoError(tt, err) + } + }) + } +} + +func TestVersion_Compare(t *testing.T) { + tests := []struct { + v1 string + v2 string + expected int + }{ + {"1.2.3", "1.4.5", -1}, + {"2.2.3", "1.5.1", 1}, + {"2.2.3", "2.2.2", 1}, + {"1.0.0-1", "1.0.0-2", -1}, + {"1.0.0-2", "1.0.0-1", 1}, + {"1.2.3-1", "1.2.3-1", 0}, + {"1.2.3", "1.2.3-1", -1}, + {"1.2.3-1", "1.2.3", 1}, + {"1.2.3+foo", "1.2.3+bar", 0}, + {"1.2.3+foo", "1.2.3+bar", 0}, + {"1.2.0", "1.2.0-1+metadata", -1}, + } + t.Parallel() + for _, testToRun := range tests { + test := testToRun + t.Run(fmt.Sprintf("%s vs %s", test.v1, test.v2), func(tt *testing.T) { + tt.Parallel() + v1, err := Parse(test.v1) + require.NoError(tt, err, test.v1) + + v2, err := Parse(test.v2) + require.NoError(tt, err, test.v2) + + assert.Equal(tt, test.expected, v1.Compare(v2)) + }) + } +}