diff --git a/NOTICE b/NOTICE index 7cf2dde..dc3b904 100644 --- a/NOTICE +++ b/NOTICE @@ -9,3 +9,7 @@ This product's design is informed by the Astral `uv` project PEP 440 and PEP 508. No source from those projects is incorporated at this time; attribution for any incorporated material is added when that material lands. + +The version/ package is derived from rstudio/go-pep440-version, itself a fork of +aquasecurity/go-pep440-version (https://github.com/aquasecurity/go-pep440-version), +licensed under the Apache License, Version 2.0. diff --git a/README.md b/README.md index 79787c1..2451ab8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Part of [RFD 0001 — Native Go PyPI Dependency Resolution](https://github.com/r | Package | Scope | |---|---| -| `version/` | PEP 440 versions and specifiers *(added by migration #18629)* | +| [`version/`](https://github.com/rstudio/go-pep440-version) | PEP 440 versions and specifiers | | `requirement/` | PEP 508 dependency specifiers | | `marker/` | PEP 508 environment markers | | `extras/` | PEP 685 extra-name normalization | diff --git a/go.mod b/go.mod index 8c37cb6..59b9737 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,14 @@ module github.com/posit-dev/go-python-packaging go 1.25 + +require ( + github.com/rstudio/go-version v0.0.2 + github.com/stretchr/testify v1.9.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..0f1654a --- /dev/null +++ b/go.sum @@ -0,0 +1,12 @@ +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/rstudio/go-version v0.0.2 h1:ihU0xaF+Yuya0p2J6C8dfyB4gu/YehM1d6cTpabf/7A= +github.com/rstudio/go-version v0.0.2/go.mod h1:Xfuma+m4R9L0P+Hof8iDDiL4/TJ8VjpdDXWq8qGXHL4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +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.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/version/doc.go b/version/doc.go new file mode 100644 index 0000000..ad0e818 --- /dev/null +++ b/version/doc.go @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package version implements PEP 440 version parsing, comparison, and +// version-specifier matching. +// +// Ported from rstudio/go-pep440-version (a fork of aquasecurity/go-pep440-version). +package version diff --git a/version/specifier.go b/version/specifier.go new file mode 100644 index 0000000..a189ac9 --- /dev/null +++ b/version/specifier.go @@ -0,0 +1,457 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "errors" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" +) + +var ( + specifierOperators = map[string]operatorFunc{ + "": specifierEqual, // not defined in PEP 440 + "=": specifierEqual, // not defined in PEP 440 + "==": specifierEqual, + "!=": specifierNotEqual, + ">": specifierGreaterThan, + "<": specifierLessThan, + ">=": specifierGreaterThanEqual, + "<=": specifierLessThanEqual, + "~=": specifierCompatible, + "===": specifierArbitrary, + } + + specifierRegexp *regexp.Regexp + validConstraintRegexp *regexp.Regexp + prefixRegexp *regexp.Regexp +) + +func init() { + ops := make([]string, 0, len(specifierOperators)) + for k := range specifierOperators { + ops = append(ops, regexp.QuoteMeta(k)) + } + + specifierRegexp = regexp.MustCompile( + fmt.Sprintf( + `(?i)(?P(%s))\s*(?P%s(\.\*)?)`, + strings.Join(ops, "|"), + regex, + ), + ) + + validConstraintRegexp = regexp.MustCompile( + fmt.Sprintf( + `^\s*(\s*(%s)\s*(%s(\.\*)?)\s*\,?)*\s*$`, + strings.Join(ops, "|"), + regex, + ), + ) + + prefixRegexp = regexp.MustCompile(`^([0-9]+)((?:a|b|c|rc)[0-9]+)$`) +} + +type operatorFunc func(v Version, c string) bool + +type Specifiers struct { + specifiers [][]specifier + conf conf +} + +type specifier struct { + version string + operator operatorFunc + original string +} + +// NewSpecifiersWithSanitizer parses a given specifier and returns a new instance of Specifiers +// it sanitizes the version string before parsing it with the given function. +func NewSpecifiersWithSanitizer(v string, sanitizer func(string) string, opts ...SpecifierOption) (Specifiers, error) { + return newSpecifiers(v, sanitizer, opts...) +} + +// NewRSpecifiers parses a given specifier and returns a new instance of Specifiers intended for +// working with R package versions. +func NewRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOption) (Specifiers, error) { + return newRSpecifiers(v, sanitizer, opts...) +} + +// NewSpecifiers parses a given specifier and returns a new instance of Specifiers +func NewSpecifiers(v string, opts ...SpecifierOption) (Specifiers, error) { + return newSpecifiers(v, func(s string) string { return s }, opts...) +} + +// NewSpecifiers parses a given specifier and returns a new instance of Specifiers +func newRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOption) (Specifiers, error) { + c := new(conf) + + // Apply options + for _, o := range opts { + o.apply(c) + } + + var sss [][]specifier + for _, vv := range strings.Split(v, "||") { + if strings.TrimSpace(vv) == "*" { + vv = ">=0.0.0" + } + vv = strings.ReplaceAll(vv, "-", ".") + + // Validate the segment + if !validConstraintRegexp.MatchString(vv) { + return Specifiers{}, fmt.Errorf("improper constraint: %s", vv) + } + + ss := specifierRegexp.FindAllString(vv, -1) + if ss == nil { + ss = append(ss, strings.TrimSpace(vv)) + } + + var specs []specifier + for _, single := range ss { + s, err := newSpecifier(single, sanitizer) + if err != nil { + return Specifiers{}, err + } + specs = append(specs, s) + } + sss = append(sss, specs) + } + + return Specifiers{ + specifiers: sss, + conf: *c, + }, nil + +} + +// NewSpecifiers parses a given specifier and returns a new instance of Specifiers +func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOption) (Specifiers, error) { + c := new(conf) + + // Apply options + for _, o := range opts { + o.apply(c) + } + + var sss [][]specifier + for _, vv := range strings.Split(v, "||") { + if strings.TrimSpace(vv) == "*" { + vv = ">=0.0.0" + } + + // Validate the segment + if !validConstraintRegexp.MatchString(vv) { + return Specifiers{}, fmt.Errorf("improper constraint: %s", vv) + } + + ss := specifierRegexp.FindAllString(vv, -1) + if ss == nil { + ss = append(ss, strings.TrimSpace(vv)) + } + + var specs []specifier + for _, single := range ss { + s, err := newSpecifier(single, sanitizer) + if err != nil { + return Specifiers{}, err + } + specs = append(specs, s) + } + sss = append(sss, specs) + } + + return Specifiers{ + specifiers: sss, + conf: *c, + }, nil + +} + +func newSpecifier(s string, sanitizer func(s string) string) (specifier, error) { + m := specifierRegexp.FindStringSubmatch(s) + if m == nil { + return specifier{}, fmt.Errorf("improper specifier: %s", s) + } + + operator := m[specifierRegexp.SubexpIndex("operator")] + version := m[specifierRegexp.SubexpIndex("version")] + version = sanitizer(version) + + if operator != "===" { + if err := validate(operator, version); err != nil { + return specifier{}, err + } + } + + return specifier{ + version: version, + operator: specifierOperators[operator], + original: s, + }, nil +} + +func validate(operator, version string) error { + hasWildcard := false + if strings.HasSuffix(version, ".*") { + hasWildcard = true + version = strings.TrimSuffix(version, ".*") + } + v, err := Parse(version) + if err != nil { + return fmt.Errorf("version parse error (%s): %w", v, err) + } + + switch operator { + case "", "=", "==", "!=": + if hasWildcard && (!v.dev.isNull() || v.local != "") { + return errors.New( + "the (non)equality operators don't allow to use a wild card and a dev or local version together", + ) + } + case "~=": + if hasWildcard { + return errors.New("a wild card is not allowed") + } else if len(v.release) < 2 { + return errors.New("the compatible operator requires at least two digits in the release segment") + } else if v.local != "" { + return errors.New("local versions cannot be specified") + } + default: + if hasWildcard { + return errors.New("a wild card is not allowed") + } else if v.local != "" { + return errors.New("local versions cannot be specified") + } + } + return nil +} + +// Check tests if a version satisfies all the specifiers. +func (ss Specifiers) Check(v Version) bool { + if ss.conf.includePreRelease { + v.preReleaseIncluded = true + } + + for _, s := range ss.specifiers { + if andCheck(v, s) { + return true + } + } + + return false +} + +func (s specifier) check(v Version) bool { + return s.operator(v, s.version) +} + +func (s specifier) String() string { + return s.original +} + +// String returns the string format of the specifiers +func (ss Specifiers) String() string { + var ssStr []string + for _, orS := range ss.specifiers { + var sstr []string + for _, andS := range orS { + sstr = append(sstr, andS.String()) + } + ssStr = append(ssStr, strings.Join(sstr, ",")) + } + + return strings.Join(ssStr, "||") +} + +func andCheck(v Version, specifiers []specifier) bool { + for _, c := range specifiers { + if !c.check(v) { + return false + } + } + return true +} + +func versionSplit(version string) []string { + var result []string + for _, v := range strings.Split(version, ".") { + m := prefixRegexp.FindStringSubmatch(v) + if m != nil { + result = append(result, m[1:]...) + } else { + result = append(result, v) + } + } + return result +} + +func isDigist(s string) bool { + if _, err := strconv.Atoi(s); err == nil { + return true + } + return false +} + +func padVersion(left, right []string) ([]string, []string) { + var leftRelease, rightRelease []string + for _, l := range left { + if isDigist(l) { + leftRelease = append(leftRelease, l) + } + } + + for _, r := range right { + if isDigist(r) { + rightRelease = append(rightRelease, r) + } + } + + // Get the rest of our versions + leftRest := left[len(leftRelease):] + rightRest := right[len(rightRelease):] + + for i := 0; i < len(leftRelease)-len(rightRelease); i++ { + rightRelease = append(rightRelease, "0") + } + for i := 0; i < len(rightRelease)-len(leftRelease); i++ { + leftRelease = append(leftRelease, "0") + } + + return append(leftRelease, leftRest...), append(rightRelease, rightRest...) +} + +//------------------------------------------------------------------- +// Specifier functions +//------------------------------------------------------------------- + +func specifierCompatible(prospective Version, spec string) bool { + // Compatible releases have an equivalent combination of >= and ==. That is that ~=2.2 is equivalent to >=2.2,==2.*. + // This allows us to implement this in terms of the other specifiers instead of implementing it ourselves. + // The only thing we need to do is construct the other specifiers. + + var prefixElements []string + for _, s := range versionSplit(spec) { + if strings.HasPrefix(s, "post") || strings.HasPrefix(s, "dev") { + break + } + prefixElements = append(prefixElements, s) + } + + // We want everything but the last item in the version, but we want to ignore post and dev releases, and + // we want to treat the pre-release as its own separate segment. + prefix := strings.Join(prefixElements[:len(prefixElements)-1], ".") + + // Add the prefix notation to the end of our string + prefix += ".*" + + return specifierGreaterThanEqual(prospective, spec) && specifierEqual(prospective, prefix) +} + +func specifierEqual(prospective Version, spec string) bool { + // https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/specifiers.py#L476 + // We need special logic to handle prefix matching + if strings.HasSuffix(spec, ".*") { + // In the case of prefix matching we want to ignore local segment. + prospective = MustParse(prospective.Public()) + + // Split the spec out by dots, and pretend that there is an implicit + // dot in between a release segment and a pre-release segment. + splitSpec := versionSplit(strings.TrimSuffix(spec, ".*")) + + // Split the prospective version out by dots, and pretend that there is an implicit dot + // in between a release segment and a pre-release segment. + splitProspective := versionSplit(prospective.String()) + + // Shorten the prospective version to be the same length as the spec + // so that we can determine if the specifier is a prefix of the + // prospective version or not. + if len(splitProspective) > len(splitSpec) { + splitProspective = splitProspective[:len(splitSpec)] + } + + paddedSpec, paddedProspective := padVersion(splitSpec, splitProspective) + return reflect.DeepEqual(paddedSpec, paddedProspective) + } + + specVersion := MustParse(spec) + if specVersion.local == "" { + prospective = MustParse(prospective.Public()) + } + + return specVersion.Equal(prospective) +} + +func specifierNotEqual(prospective Version, spec string) bool { + return !specifierEqual(prospective, spec) +} + +func specifierLessThan(prospective Version, spec string) bool { + // Convert our spec to a Version instance, since we'll want to work with it as a version. + s := MustParse(spec) + + // Check to see if the prospective version is less than the spec version. + // If it's not we can short circuit and just return False now instead of doing extra unneeded work. + if !prospective.LessThan(s) { + return false + } + + // This special case is here so that, unless the specifier itself includes is a pre-release version, + // that we do not accept pre-release versions for the version mentioned in the specifier + // (e.g. <3.1 should not match 3.1.dev0, but should match 3.0.dev0). + if !s.IsPreRelease() && prospective.IsPreRelease() { + if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + return false + } + } + return true +} + +func specifierGreaterThan(prospective Version, spec string) bool { + // Convert our spec to a Version instance, since we'll want to work with it as a version. + s := MustParse(spec) + + // Check to see if the prospective version is greater than the spec version. + // If it's not we can short circuit and just return False now instead of doing extra unneeded work. + if !prospective.GreaterThan(s) { + return false + } + + // This special case is here so that, unless the specifier itself includes is a post-release version, + // that we do not accept post-release versions for the version mentioned in the specifier + // (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if !s.IsPostRelease() && prospective.IsPostRelease() { + if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + return false + } + } + + // Ensure that we do not allow a local version of the version mentioned + // in the specifier, which is technically greater than, to match. + if prospective.local != "" { + if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + return false + } + } + return true +} + +func specifierArbitrary(prospective Version, spec string) bool { + return strings.EqualFold(prospective.String(), spec) +} + +func specifierLessThanEqual(prospective Version, spec string) bool { + p := MustParse(prospective.Public()) + s := MustParse(spec) + return p.LessThanOrEqual(s) +} + +func specifierGreaterThanEqual(prospective Version, spec string) bool { + p := MustParse(prospective.Public()) + s := MustParse(spec) + return p.GreaterThanOrEqual(s) +} diff --git a/version/specifier_option.go b/version/specifier_option.go new file mode 100644 index 0000000..0207768 --- /dev/null +++ b/version/specifier_option.go @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +type conf struct { + includePreRelease bool +} + +type SpecifierOption interface { + apply(*conf) +} + +type WithPreRelease bool + +func (o WithPreRelease) apply(c *conf) { + c.includePreRelease = bool(o) +} diff --git a/version/specifier_test.go b/version/specifier_test.go new file mode 100644 index 0000000..8653b05 --- /dev/null +++ b/version/specifier_test.go @@ -0,0 +1,488 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewConstraints(t *testing.T) { + tests := []struct { + constraint string + wantErr bool + }{ + // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L31-L42 + {"~=2.0", false}, + {"==2.1.*", false}, + {"==2.1.0.3", false}, + {"!=2.2.*", false}, + {"!=2.2.0.5", false}, + {"<=5", false}, + {">=7.9a1", false}, + {"<1.0.dev1", false}, + {">2.0.post1", false}, + + // TODO + // {"===lolwat", false}, + + // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L50-L86 + // Operator-less specifier + {"2.0", false}, // go-pep-440-version permits this case + + // Invalid operator + {"=>2.0", true}, + + //Version-less specifier + {"==", true}, + + // Local segment on operators which don't support them + {"~=1.0+5", true}, + {">=1.0+deadbeef", true}, + {"<=1.0+abc123", true}, + {">1.0+watwat", true}, + {"<1.0+1.0", true}, + + // Prefix matching on operators which don't support them + {"~=1.0.*", true}, + {">=1.0.*", true}, + {"<=1.0.*", true}, + {">1.0.*", true}, + {"<1.0.*", true}, + + // Combination of local and prefix matching on operators which do + // support one or the other + {"==1.0.*+5", true}, + {"!=1.0.*+deadbeef", true}, + + // Prefix matching cannot be used inside of a local version + {"==1.0+5.*", true}, + {"!=1.0+deadbeef.*", true}, + + // Prefix matching must appear at the end + {"==1.0.*.5", true}, + + // Compatible operator requires 2 digits in the release operator + {"~=1", true}, + + // Cannot use a prefix matching after a .devN version + {"==1.0.dev1.*", true}, + {"!=1.0.dev1.*", true}, + + // Versions with dashes '-' should return an error + {"== 3.99-0.14", true}, + {"==3.99-0.14", true}, + {"==3.99.0.14", false}, + {"== 3.99.0.14", false}, + } + for _, tt := range tests { + t.Run(tt.constraint, func(t *testing.T) { + _, err := NewSpecifiers(tt.constraint) + if tt.wantErr { + assert.NotNil(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestNewRSpecifiers(t *testing.T) { + tests := []struct { + constraint string + wantErr bool + }{ + // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L31-L42 + {"~=2.0", false}, + {"==2.1.*", false}, + {"==2.1.0.3", false}, + {"!=2.2.*", false}, + {"!=2.2.0.5", false}, + {"<=5", false}, + {">=7.9a1", false}, + {"<1.0.dev1", false}, + {">2.0.post1", false}, + + // TODO + // {"===lolwat", false}, + + // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L50-L86 + // Operator-less specifier + {"2.0", false}, // go-pep-440-version permits this case + + // Invalid operator + {"=>2.0", true}, + + //Version-less specifier + {"==", true}, + + // Local segment on operators which don't support them + {"~=1.0+5", true}, + {">=1.0+deadbeef", true}, + {"<=1.0+abc123", true}, + {">1.0+watwat", true}, + {"<1.0+1.0", true}, + + // Prefix matching on operators which don't support them + {"~=1.0.*", true}, + {">=1.0.*", true}, + {"<=1.0.*", true}, + {">1.0.*", true}, + {"<1.0.*", true}, + + // Combination of local and prefix matching on operators which do + // support one or the other + {"==1.0.*+5", true}, + {"!=1.0.*+deadbeef", true}, + + // Prefix matching cannot be used inside of a local version + {"==1.0+5.*", true}, + {"!=1.0+deadbeef.*", true}, + + // Prefix matching must appear at the end + {"==1.0.*.5", true}, + + // Compatible operator requires 2 digits in the release operator + {"~=1", true}, + + // Cannot use a prefix matching after a .devN version + {"==1.0.dev1.*", true}, + {"!=1.0.dev1.*", true}, + + // Versions containing dashes '-' should not return an error + {"== 3.99-0.14", false}, + {"==3.99-0.14", false}, + {"==3.99.0.14", false}, + {"== 3.99.0.14", false}, + } + for _, tt := range tests { + t.Run(tt.constraint, func(t *testing.T) { + _, err := NewRSpecifiers(tt.constraint, func(s string) string { return s }) + if tt.wantErr { + assert.NotNil(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestVersion_Check(t *testing.T) { + tests := []struct { + version string + spec string + want bool + }{ + // Test the equality operation + {"2.0", "==2", true}, + {"2.0", "==2.0", true}, + {"2.0", "==2.0.0", true}, + {"2.0+deadbeef", "==2", true}, + {"2.0+deadbeef", "==2.0", true}, + {"2.0+deadbeef", "==2.0.0", true}, + {"2.0+deadbeef", "==2+deadbeef", true}, + {"2.0+deadbeef", "==2.0+deadbeef", true}, + {"2.0+deadbeef", "==2.0.0+deadbeef", true}, + {"2.0+deadbeef.0", "==2.0.0+deadbeef.00", true}, + + // Test the equality operation with a prefix + {"2.dev1", "==2.*", true}, + {"2a1", "==2.*", true}, + {"2a1.post1", "==2.*", true}, + {"2b1", "==2.*", true}, + {"2b1.dev1", "==2.*", true}, + {"2c1", "==2.*", true}, + {"2c1.post1.dev1", "==2.*", true}, + {"2rc1", "==2.*", true}, + {"2", "==2.*", true}, + {"2.0", "==2.*", true}, + {"2.0.0", "==2.*", true}, + {"2.0.post1", "==2.0.post1.*", true}, + {"2.0.post1.dev1", "==2.0.post1.*", true}, + {"2.1+local.version", "==2.1.*", true}, + + // Test the in-equality operation + {"2.1", "!=2", true}, + {"2.1", "!=2.0", true}, + {"2.0.1", "!=2", true}, + {"2.0.1", "!=2.0", true}, + {"2.0.1", "!=2.0.0", true}, + {"2.0", "!=2.0+deadbeef", true}, + + // Test the in-equality operation with a prefix + {"2.0", "!=3.*", true}, + {"2.1", "!=2.0.*", true}, + + // Test the greater than equal operation + {"2.0", ">=2", true}, + {"2.0", ">=2.0", true}, + {"2.0", ">=2.0.0", true}, + {"2.0.post1", ">=2", true}, + {"2.0.post1.dev1", ">=2", true}, + {"3", ">=2", true}, + + // Test the less than equal operation + {"2.0", "<=2", true}, + {"2.0", "<=2.0", true}, + {"2.0", "<=2.0.0", true}, + {"2.0.dev1", "<=2", true}, + {"2.0a1", "<=2", true}, + {"2.0a1.dev1", "<=2", true}, + {"2.0b1", "<=2", true}, + {"2.0b1.post1", "<=2", true}, + {"2.0c1", "<=2", true}, + {"2.0c1.post1.dev1", "<=2", true}, + {"2.0rc1", "<=2", true}, + {"1", "<=2", true}, + + // Test the greater than operation + {"3", ">2", true}, + {"2.1", ">2.0", true}, + {"2.0.1", ">2", true}, + {"2.1.post1", ">2", true}, + {"2.1+local.version", ">2", true}, + + // Test the less than operation + {"1", "<2", true}, + {"2.0", "<2.1", true}, + {"2.0.dev0", "<2.1", true}, + + // Test the compatibility operation + {"1", "~=1.0", true}, + {"1.0.1", "~=1.0", true}, + {"1.1", "~=1.0", true}, + {"1.9999999", "~=1.0", true}, + + // Test that epochs are handled sanely + {"2!1.0", "~=2!1.0", true}, + {"2!1.0", "==2!1.*", true}, + {"2!1.0", "==2!1.0", true}, + {"2!1.0", "!=1.0", true}, + {"1.0", "!=2!1.0", true}, + {"1.0", "<=2!0.1", true}, + {"2!1.0", ">=2.0", true}, + {"1.0", "<2!0.1", true}, + {"2!1.0", ">2.0", true}, + + // Test some normalization rules + {"2.0.5", ">2.0dev", true}, + + // Test the equality operation + {"2.1", "==2", false}, + {"2.1", "==2.0", false}, + {"2.1", "==2.0.0", false}, + {"2.0", "==2.0+deadbeef", false}, + + //Test the equality operation with a prefix + {"2.0", "==3.*", false}, + {"2.1", "==2.0.*", false}, + + // Test the in-equality operation + {"2.0", "!=2", false}, + {"2.0", "!=2.0", false}, + {"2.0", "!=2.0.0", false}, + {"2.0+deadbeef", "!=2", false}, + {"2.0+deadbeef", "!=2.0", false}, + {"2.0+deadbeef", "!=2.0.0", false}, + {"2.0+deadbeef", "!=2+deadbeef", false}, + {"2.0+deadbeef", "!=2.0+deadbeef", false}, + {"2.0+deadbeef", "!=2.0.0+deadbeef", false}, + {"2.0+deadbeef.0", "!=2.0.0+deadbeef.00", false}, + + // Test the in-equality operation with a prefix + {"2.dev1", "!=2.*", false}, + {"2a1", "!=2.*", false}, + {"2a1.post1", "!=2.*", false}, + {"2b1", "!=2.*", false}, + {"2b1.dev1", "!=2.*", false}, + {"2c1", "!=2.*", false}, + {"2c1.post1.dev1", "!=2.*", false}, + {"2rc1", "!=2.*", false}, + {"2", "!=2.*", false}, + {"2.0", "!=2.*", false}, + {"2.0.0", "!=2.*", false}, + {"2.0.post1", "!=2.0.post1.*", false}, + {"2.0.post1.dev1", "!=2.0.post1.*", false}, + + //Test the greater than equal operation + {"2.0.dev1", ">=2", false}, + {"2.0a1", ">=2", false}, + {"2.0a1.dev1", ">=2", false}, + {"2.0b1", ">=2", false}, + {"2.0b1.post1", ">=2", false}, + {"2.0c1", ">=2", false}, + {"2.0c1.post1.dev1", ">=2", false}, + {"2.0rc1", ">=2", false}, + {"1", ">=2", false}, + + // Test the less than equal operation + {"2.0.post1", "<=2", false}, + {"2.0.post1.dev1", "<=2", false}, + {"3", "<=2", false}, + + // Test the greater than operation + {"1", ">2", false}, + {"2.0.dev1", ">2", false}, + {"2.0a1", ">2", false}, + {"2.0a1.post1", ">2", false}, + {"2.0b1", ">2", false}, + {"2.0b1.dev1", ">2", false}, + {"2.0c1", ">2", false}, + {"2.0c1.post1.dev1", ">2", false}, + {"2.0rc1", ">2", false}, + {"2.0", ">2", false}, + {"2.0.post1", ">2", false}, + {"2.0.post1.dev1", ">2", false}, + {"2.0+local.version", ">2", false}, + + // Test the less than operation + {"2.0.dev1", "<2", false}, + {"2.0a1", "<2", false}, + {"2.0a1.post1", "<2", false}, + {"2.0b1", "<2", false}, + {"2.0b2.dev1", "<2", false}, + {"2.0c1", "<2", false}, + {"2.0c1.post1.dev1", "<2", false}, + {"2.0rc1", "<2", false}, + {"2.0", "<2", false}, + {"2.post1", "<2", false}, + {"2.post1.dev1", "<2", false}, + {"3", "<2", false}, + + // Test the compatibility operation + {"2.0", "~=1.0", false}, + {"1.1.0", "~=1.0.0", false}, + {"1.1.post1", "~=1.0.0", false}, + + // Test that epochs are handled sanely + {"1.0", "~=2!1.0", false}, + {"2!1.0", "~=1.0", false}, + {"2!1.0", "==1.0", false}, + {"1.0", "==2!1.0", false}, + {"2!1.0", "==1.*", false}, + {"1.0", "==2!1.*", false}, + {"2!1.0", "!=2!1.0", false}, + + // local versions + {"1.0.0+local", "==1.0.0", true}, + {"1.0.0+local", "!=1.0.0", false}, + {"1.0.0+local", "<=1.0.0", true}, + {"1.0.0+local", ">=1.0.0", true}, + {"1.0.0+local", "<1.0.0", false}, + {"1.0.0+local", ">1.0.0", false}, + + // and operators + {"1.0", ">= 1.0, != 1.3.4.*, < 2.0", true}, + {"1.0", "~= 0.9, >= 1.0, != 1.3.4.*, < 2.0", false}, + {"0.9", "~= 0.9, != 1.3.4.*, < 2.0", true}, + {"2.0", ">= 1.0, != 1.3.4.*, < 2.0", false}, + {"1.3.4", ">= 1.0, != 1.3.4.*, < 2.0", false}, + + // or operators + {"1.0", "~= 0.9, >= 1.0, != 1.3.4.*, < 2.0 || ==1.0", true}, + {"1.0", "~= 0.9, >= 1.0, != 1.3.4.*, < 2.0 || !=1.0", false}, + + // Test the equality operation not defined in PEP 440 + {"2.0", "2", true}, + {"2.0", "2.0", true}, + {"2.0", "2.0.0", true}, + {"2.1", "2", false}, + {"2.1", "2.0", false}, + {"2.1", "2.0.0", false}, + {"2.0", "2.0+deadbeef", false}, + {"2.0", "=2", true}, + {"2.0", "=2.0", true}, + {"2.0", "=2.0.0", true}, + {"2.1", "=2", false}, + {"2.1", "=2.0", false}, + {"2.1", "=2.0.0", false}, + {"2.0", "=2.0+deadbeef", false}, + {"2.0", "*", true}, + + // space separated + {"1.0", ">= 1.0 != 1.3.4.* < 2.0", true}, + {"1.0", "~= 0.9 >= 1.0 != 1.3.4.* < 2.0", false}, + {"0.9", "~= 0.9 != 1.3.4.* < 2.0", true}, + {"2.0", ">= 1.0 != 1.3.4.* < 2.0", false}, + {"1.3.4", ">= 1.0 != 1.3.4.* < 2.0", false}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("%s %s", tt.version, tt.spec), func(t *testing.T) { + c, err := NewSpecifiers(tt.spec) + require.NoError(t, err) + + v, err := Parse(tt.version) + require.NoError(t, err) + + assert.Equal(t, tt.want, c.Check(v)) + }) + } +} + +// TestPadVersion_RightRestDerivesFromRight is a regression test for a bug where +// padVersion sliced left twice instead of slicing right for the "rest" of the +// right-hand version, so the returned right-hand segments were built from +// leftover pieces of the left-hand version instead of the right-hand version. +func TestPadVersion_RightRestDerivesFromRight(t *testing.T) { + // left's release segment ("2","0") is longer than right's ("3"), and each + // side has a distinct, differently-shaped non-numeric "rest" suffix, so a + // padVersion that mixes up which side the rest comes from is easy to spot. + left := []string{"2", "0", "rc1"} + right := []string{"3", "x"} + + _, gotRight := padVersion(left, right) + + // The right-hand rest must come from right (["x"]), not left (["rc1"]). + want := []string{"3", "0", "x"} + assert.Equal(t, want, gotRight) +} + +// TestNewRSpecifiers_UsesProvidedSanitizer is a regression test for a bug where +// NewRSpecifiers ignored the caller-supplied sanitizer and always forwarded an +// identity function to newRSpecifiers instead. +func TestNewRSpecifiers_UsesProvidedSanitizer(t *testing.T) { + // A sanitizer that rewrites "9" digits to "1" digits, simulating a caller + // normalizing a non-standard version token before PEP 440 parsing. + sanitizer := func(s string) string { + return strings.ReplaceAll(s, "9", "1") + } + + specs, err := NewRSpecifiers("==9.0.0", sanitizer) + require.NoError(t, err) + + v, err := Parse("1.0.0") + require.NoError(t, err) + + // If the sanitizer is honored, "==9.0.0" is rewritten to "==1.0.0" before + // being parsed, so 1.0.0 satisfies it. If the sanitizer is ignored (as with + // the identity-forwarding bug), the specifier stays "==9.0.0" and this + // version does not satisfy it. + assert.True(t, specs.Check(v)) +} + +func TestVersion_CheckWithPreRelease(t *testing.T) { + tests := []struct { + version string + spec string + want bool + }{ + {"1.3.4", "< 2.0", true}, + {"2.0a1", "<2", true}, + {"2.1a1", "<2", false}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("%s %s", tt.version, tt.spec), func(t *testing.T) { + c, err := NewSpecifiers(tt.spec, WithPreRelease(true)) + require.NoError(t, err) + + v, err := Parse(tt.version) + require.NoError(t, err) + + assert.Equal(t, tt.want, c.Check(v)) + }) + } +} diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..501687c --- /dev/null +++ b/version/version.go @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "bytes" + "fmt" + "regexp" + "strings" + + "github.com/rstudio/go-version/pkg/part" +) + +var ( + // The compiled regular expression used to test the validity of a version. + versionRegex *regexp.Regexp + + // https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/version.py#L459-L464 + preReleaseAliases = map[string]string{ + "a": "a", + "alpha": "a", + "b": "b", + "beta": "b", + "rc": "rc", + "c": "rc", + "pre": "rc", + "preview": "rc", + } + + // https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/version.py#L465-L466 + postReleaseAliases = map[string]string{ + "post": "post", + "rev": "post", + "r": "post", + } +) + +const ( + // The raw regular expression string used for testing the validity of a version. + regex = `v?` + + `(?:` + + `(?:(?P[0-9]+)!)?` + // epoch + `(?P[0-9]+(?:\.[0-9]+)*)` + // release segment + `(?P
[-_\.]?(?P(a|b|c|rc|alpha|beta|pre|preview))[-_\.]?(?P[0-9]+)?)?` + // pre-release
+		`(?P(?:-(?P[0-9]+))|(?:[-_\.]?(?Ppost|rev|r)[-_\.]?(?P[0-9]+)?))?` + // post release
+		`(?P[-_\.]?(?Pdev)[-_\.]?(?P[0-9]+)?)?)` + // dev release
+		`(?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?` // local version`
+)
+
+// Version represents a single version.
+type Version struct {
+	epoch              part.BigInt
+	release            []part.BigInt
+	pre                letterNumber
+	post               letterNumber
+	dev                letterNumber
+	local              string
+	key                key
+	preReleaseIncluded bool
+	original           string
+}
+
+type key struct {
+	epoch   part.BigInt
+	release part.Parts
+	pre     part.Part
+	post    part.Part
+	dev     part.Part
+	local   part.Part
+}
+
+func (k key) compare(o key) int {
+	p1 := part.Parts{k.epoch, k.release, k.pre, k.post, k.dev, k.local}
+	p2 := part.Parts{o.epoch, o.release, o.pre, o.post, o.dev, o.local}
+	return p1.Compare(p2)
+}
+
+type letterNumber struct {
+	letter part.String
+	number part.BigInt
+}
+
+func (ln letterNumber) isNull() bool {
+	return ln.letter.IsNull() && ln.number.IsNull()
+}
+
+func init() {
+	versionRegex = regexp.MustCompile(`(?i)^\s*` + regex + `\s*$`)
+}
+
+// MustParse is like Parse but panics if the version cannot be parsed.
+func MustParse(v string) Version {
+	ver, err := Parse(v)
+	if err != nil {
+		panic(err)
+	}
+	return ver
+}
+
+// Parse parses the given version and returns a new Version.
+func Parse(v string) (Version, error) {
+	matches := versionRegex.FindStringSubmatch(v)
+	if matches == nil {
+		return Version{}, fmt.Errorf("malformed version: %s", v)
+	}
+
+	var epoch, preN, postN, devN part.BigInt
+	var preL, postL, devL part.String
+	var release []part.BigInt
+	var local string
+	var err error
+
+	for i, name := range versionRegex.SubexpNames() {
+		m := matches[i]
+		if m == "" {
+			continue
+		}
+
+		switch name {
+		case "epoch":
+			epoch, err = part.NewBigInt(m)
+		case "release":
+			for _, str := range strings.Split(m, ".") {
+				val, err := part.NewBigInt(str)
+				if err != nil {
+					return Version{}, fmt.Errorf("error parsing version: %w", err)
+				}
+
+				release = append(release, val)
+			}
+		case "pre_l":
+			preL = part.String(preReleaseAliases[strings.ToLower(m)])
+		case "pre_n":
+			preN, err = part.NewBigInt(m)
+		case "post_l":
+			postL = part.String(postReleaseAliases[strings.ToLower(m)])
+		case "post_n1", "post_n2":
+			// https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/version.py#L469-L472
+			if postL == "" {
+				postL = "post"
+			}
+			postN, err = part.NewBigInt(m)
+		case "dev_l":
+			devL = part.String(strings.ToLower(m))
+		case "dev_n":
+			devN, err = part.NewBigInt(m)
+		case "local":
+			local = strings.ToLower(m)
+		}
+		if err != nil {
+			return Version{}, fmt.Errorf("failed to parse version (%s): %w", v, err)
+		}
+	}
+
+	pre := letterNumber{
+		letter: preL,
+		number: preN,
+	}
+	post := letterNumber{
+		letter: postL,
+		number: postN,
+	}
+	dev := letterNumber{
+		letter: devL,
+		number: devN,
+	}
+
+	return Version{
+		epoch:    epoch,
+		release:  release,
+		pre:      pre,
+		post:     post,
+		dev:      dev,
+		local:    local,
+		key:      cmpkey(epoch, release, pre, post, dev, local),
+		original: v,
+	}, nil
+}
+
+// ref. https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/version.py#L495
+func cmpkey(epoch part.BigInt, release []part.BigInt, pre, post, dev letterNumber, local string) key {
+	// Set default values
+	k := key{
+		epoch: epoch,
+		pre:   part.Parts{pre.letter, pre.number},
+		post:  part.Parts{post.letter, post.number},
+		dev:   part.Parts{dev.letter, dev.number},
+		local: part.NegativeInfinity,
+	}
+
+	// Remove trailing zeros
+	k.release = part.BigIntSliceToParts(release).Normalize()
+
+	// https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/version.py#L514-L517
+	if pre.isNull() && post.isNull() && !dev.isNull() {
+		k.pre = part.NegativeInfinity
+	} else if pre.isNull() {
+		k.pre = part.Infinity
+	}
+
+	// Versions without a post segment should sort before those with one.
+	if post.isNull() {
+		k.post = part.NegativeInfinity
+	}
+
+	// Versions without a development segment should sort after those with one.
+	if dev.isNull() {
+		k.dev = part.Infinity
+	}
+
+	// Versions with a local segment need that segment parsed to implement the sorting rules in PEP440.
+	//   - Alpha numeric segments sort before numeric segments
+	//   - Alpha numeric segments sort lexicographically
+	//   - Numeric segments sort numerically
+	//   - Shorter versions sort before longer versions when the prefixes match exactly
+	if local != "" {
+		var parts part.Parts
+		for _, l := range strings.Split(local, ".") {
+			if p, err := part.NewBigInt(l); err == nil {
+				parts = append(parts, p)
+			} else {
+				parts = append(parts, part.NewPreString(l))
+			}
+		}
+		k.local = parts
+	}
+
+	return k
+}
+
+// Compare compares this version to another version. This
+// returns -1, 0, or 1 if this version is smaller, equal,
+// or larger than the other version, respectively.
+func (v Version) Compare(other Version) int {
+	// A quick, efficient equality check
+	if v.String() == other.String() {
+		return 0
+	}
+
+	k1 := v.key
+	k2 := other.key
+
+	k1.release = k1.release.Padding(len(k2.release), part.Zero)
+	k2.release = k2.release.Padding(len(k2.release), part.Zero)
+
+	return k1.compare(k2)
+}
+
+// Equal tests if two versions are equal.
+func (v Version) Equal(o Version) bool {
+	return v.Compare(o) == 0
+}
+
+// GreaterThan tests if this version is greater than another version.
+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
+}
+
+// LessThan tests if this version is less than another version.
+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
+}
+
+// String returns the full version string included pre-release
+// and metadata information.
+func (v Version) String() string {
+	var buf bytes.Buffer
+
+	// Epoch
+	if v.epoch.Compare(part.Zero) == 1 {
+		fmt.Fprintf(&buf, "%s!", v.epoch)
+	}
+
+	// Release segment
+	fmt.Fprintf(&buf, "%s", v.release[0])
+	for _, r := range v.release[1:len(v.release)] {
+		fmt.Fprintf(&buf, ".%s", r)
+	}
+
+	// Pre-release
+	if !v.pre.isNull() {
+		fmt.Fprintf(&buf, "%s%s", v.pre.letter, v.pre.number)
+	}
+
+	// Post-release
+	if !v.post.isNull() {
+		fmt.Fprintf(&buf, ".post%s", v.post.number)
+	}
+
+	// Development release
+	if !v.dev.isNull() {
+		fmt.Fprintf(&buf, ".dev%s", v.dev.number)
+	}
+
+	// Local version segment
+	if v.local != "" {
+		fmt.Fprintf(&buf, "+%s", v.local)
+	}
+
+	return buf.String()
+}
+
+// BaseVersion returns the base version
+func (v Version) BaseVersion() string {
+	var buf bytes.Buffer
+
+	// Epoch
+	if v.epoch.Compare(part.Zero) == 1 {
+		fmt.Fprintf(&buf, "%s!", v.epoch.String())
+	}
+
+	// Release segment
+	fmt.Fprintf(&buf, "%s", v.release[0].String())
+	for _, r := range v.release[1:len(v.release)] {
+		fmt.Fprintf(&buf, ".%s", r.String())
+	}
+
+	return buf.String()
+}
+
+// Original returns the original parsed version as-is, including any
+// potential whitespace, `v` prefix, etc.
+func (v Version) Original() string {
+	return v.original
+}
+
+// Local returns the local version
+func (v Version) Local() string {
+	return v.local
+}
+
+// Public returns the public version
+func (v Version) Public() string {
+	return strings.SplitN(v.String(), "+", 2)[0]
+}
+
+// IsPreRelease returns if it is a pre-release
+func (v Version) IsPreRelease() bool {
+	if v.preReleaseIncluded {
+		return false
+	}
+	return !v.pre.isNull() || !v.dev.isNull()
+}
+
+// IsPostRelease returns if it is a post-release
+func (v Version) IsPostRelease() bool {
+	return !v.post.isNull()
+}
+
+type SortedVersions []Version
+
+func (s SortedVersions) Len() int {
+	return len(s)
+}
+func (s SortedVersions) Less(i, j int) bool {
+	a := s[i]
+	b := s[j]
+
+	return a.LessThan(b)
+}
+func (s SortedVersions) Swap(i, j int) {
+	s[i], s[j] = s[j], s[i]
+}
diff --git a/version/version_test.go b/version/version_test.go
new file mode 100644
index 0000000..75fee08
--- /dev/null
+++ b/version/version_test.go
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
+package version_test
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/posit-dev/go-python-packaging/version"
+)
+
+var (
+	versions = []string{
+		// Implicit epoch of 0
+		"1.0.dev456",
+		"1.0a1",
+		"1.0a2.dev456",
+		"1.0a12.dev456",
+		"1.0a12",
+		"1.0b1.dev456",
+		"1.0b2",
+		"1.0b2.post345.dev456",
+		"1.0b2.post345",
+		"1.0b2-346",
+		"1.0c1.dev456",
+		"1.0c1",
+		"1.0rc2",
+		"1.0c3",
+		"1.0",
+		"1.0.post456.dev34",
+		"1.0.post456",
+		"1.1.dev1",
+		"1.2+123abc",
+		"1.2+123abc456",
+		"1.2+abc",
+		"1.2+abc123",
+		"1.2+abc123def",
+		"1.2+1234.abc",
+		"1.2+123456",
+		"1.2.r32+123456",
+		"1.2.rev33+123456",
+		// Explicit epoch of 1
+		"1!1.0.dev456",
+		"1!1.0a1",
+		"1!1.0a2.dev456",
+		"1!1.0a12.dev456",
+		"1!1.0a12",
+		"1!1.0b1.dev456",
+		"1!1.0b2",
+		"1!1.0b2.post345.dev456",
+		"1!1.0b2.post345",
+		"1!1.0b2-346",
+		"1!1.0c1.dev456",
+		"1!1.0c1",
+		"1!1.0rc2",
+		"1!1.0c3",
+		"1!1.0",
+		"1!1.0.post456.dev34",
+		"1!1.0.post456",
+		"1!1.1.dev1",
+		"1!1.2+123abc",
+		"1!1.2+123abc456",
+		"1!1.2+abc",
+		"1!1.2+abc123",
+		"1!1.2+abc123def",
+		"1!1.2+1234.abc",
+		"1!1.2+123456",
+		"1!1.2.r32+123456",
+		"1!1.2.rev33+123456",
+	}
+)
+
+// https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/tests/test_version.py#L85-L87
+func TestParseValidVersion(t *testing.T) {
+	for _, v := range versions {
+		t.Run(v, func(t *testing.T) {
+			_, err := version.Parse(v)
+			assert.NoError(t, err)
+		})
+	}
+}
+
+// https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/tests/test_version.py#L102-L104
+func TestParseInvalidVersion(t *testing.T) {
+	versions := []string{
+		// Non sensical versions should be invalid
+		"french toast",
+		// Versions with invalid local versions
+		"1.0+a+",
+		"1.0++",
+		"1.0+_foobar",
+		"1.0+foo&asd",
+		"1.0+1+1",
+	}
+	for _, v := range versions {
+		t.Run(v, func(t *testing.T) {
+			_, err := version.Parse(v)
+			assert.Error(t, err)
+		})
+	}
+}
+
+func TestVersion_String(t *testing.T) {
+	tests := []struct {
+		version string
+		want    string
+	}{
+		// Various development release incarnations
+		{"1.0dev", "1.0.dev0"},
+		{"1.0.dev", "1.0.dev0"},
+		{"1.0dev1", "1.0.dev1"},
+		{"1.0-dev", "1.0.dev0"},
+		{"1.0-dev1", "1.0.dev1"},
+		{"1.0DEV", "1.0.dev0"},
+		{"1.0.DEV", "1.0.dev0"},
+		{"1.0DEV1", "1.0.dev1"},
+		{"1.0DEV", "1.0.dev0"},
+		{"1.0.DEV1", "1.0.dev1"},
+		{"1.0-DEV", "1.0.dev0"},
+		{"1.0-DEV1", "1.0.dev1"},
+		// Various alpha incarnations
+		{"1.0a", "1.0a0"},
+		{"1.0.a", "1.0a0"},
+		{"1.0.a1", "1.0a1"},
+		{"1.0-a", "1.0a0"},
+		{"1.0-a1", "1.0a1"},
+		{"1.0alpha", "1.0a0"},
+		{"1.0.alpha", "1.0a0"},
+		{"1.0.alpha1", "1.0a1"},
+		{"1.0-alpha", "1.0a0"},
+		{"1.0-alpha1", "1.0a1"},
+		{"1.0A", "1.0a0"},
+		{"1.0.A", "1.0a0"},
+		{"1.0.A1", "1.0a1"},
+		{"1.0-A", "1.0a0"},
+		{"1.0-A1", "1.0a1"},
+		{"1.0ALPHA", "1.0a0"},
+		{"1.0.ALPHA", "1.0a0"},
+		{"1.0.ALPHA1", "1.0a1"},
+		{"1.0-ALPHA", "1.0a0"},
+		{"1.0-ALPHA1", "1.0a1"},
+		// Various beta incarnations
+		{"1.0b", "1.0b0"},
+		{"1.0.b", "1.0b0"},
+		{"1.0.b1", "1.0b1"},
+		{"1.0-b", "1.0b0"},
+		{"1.0-b1", "1.0b1"},
+		{"1.0beta", "1.0b0"},
+		{"1.0.beta", "1.0b0"},
+		{"1.0.beta1", "1.0b1"},
+		{"1.0-beta", "1.0b0"},
+		{"1.0-beta1", "1.0b1"},
+		{"1.0B", "1.0b0"},
+		{"1.0.B", "1.0b0"},
+		{"1.0.B1", "1.0b1"},
+		{"1.0-B", "1.0b0"},
+		{"1.0-B1", "1.0b1"},
+		{"1.0BETA", "1.0b0"},
+		{"1.0.BETA", "1.0b0"},
+		{"1.0.BETA1", "1.0b1"},
+		{"1.0-BETA", "1.0b0"},
+		{"1.0-BETA1", "1.0b1"},
+		// Various release candidate incarnations
+		{"1.0c", "1.0rc0"},
+		{"1.0.c", "1.0rc0"},
+		{"1.0.c1", "1.0rc1"},
+		{"1.0-c", "1.0rc0"},
+		{"1.0-c1", "1.0rc1"},
+		{"1.0rc", "1.0rc0"},
+		{"1.0.rc", "1.0rc0"},
+		{"1.0.rc1", "1.0rc1"},
+		{"1.0-rc", "1.0rc0"},
+		{"1.0-rc1", "1.0rc1"},
+		{"1.0C", "1.0rc0"},
+		{"1.0.C", "1.0rc0"},
+		{"1.0.C1", "1.0rc1"},
+		{"1.0-C", "1.0rc0"},
+		{"1.0-C1", "1.0rc1"},
+		{"1.0RC", "1.0rc0"},
+		{"1.0.RC", "1.0rc0"},
+		{"1.0.RC1", "1.0rc1"},
+		{"1.0-RC", "1.0rc0"},
+		{"1.0-RC1", "1.0rc1"},
+		// Various post release incarnations
+		{"1.0post", "1.0.post0"},
+		{"1.0.post", "1.0.post0"},
+		{"1.0post1", "1.0.post1"},
+		{"1.0post", "1.0.post0"},
+		{"1.0-post", "1.0.post0"},
+		{"1.0-post1", "1.0.post1"},
+		{"1.0POST", "1.0.post0"},
+		{"1.0.POST", "1.0.post0"},
+		{"1.0POST1", "1.0.post1"},
+		{"1.0POST", "1.0.post0"},
+		{"1.0r", "1.0.post0"},
+		{"1.0rev", "1.0.post0"},
+		{"1.0.POST1", "1.0.post1"},
+		{"1.0.r1", "1.0.post1"},
+		{"1.0.rev1", "1.0.post1"},
+		{"1.0-POST", "1.0.post0"},
+		{"1.0-POST1", "1.0.post1"},
+		{"1.0-5", "1.0.post5"},
+		{"1.0-r5", "1.0.post5"},
+		{"1.0-rev5", "1.0.post5"},
+		// Local version case insensitivity
+		{"1.0+AbC", "1.0+abc"},
+		// Integer Normalization
+		{"1.01", "1.1"},
+		{"1.0a05", "1.0a5"},
+		{"1.0b07", "1.0b7"},
+		{"1.0c056", "1.0rc56"},
+		{"1.0rc09", "1.0rc9"},
+		{"1.0.post000", "1.0.post0"},
+		{"1.1.dev09000", "1.1.dev9000"},
+		{"00!1.2", "1.2"},
+		{"0100!0.0", "100!0.0"},
+		// Various other normalizations
+		{"v1.0", "1.0"},
+		{"   v1.0\t\n", "1.0"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.version, func(t *testing.T) {
+			v, err := version.Parse(tt.version)
+			require.NoError(t, err)
+
+			assert.Equal(t, tt.want, v.String())
+		})
+	}
+}
+
+func TestVersion_LessThan_LessThanOrEqual(t *testing.T) {
+	var tests [][2]string
+	for i, v1 := range versions {
+		for _, v2 := range versions[i+1:] {
+			tests = append(tests, [2]string{v1, v2})
+		}
+	}
+	for _, tt := range tests {
+		t.Run(tt[0]+" < "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.True(t, v1.LessThan(v2))
+		})
+		t.Run(tt[0]+" >= "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.False(t, v1.GreaterThanOrEqual(v2))
+		})
+	}
+}
+
+func TestVersion_LessThanOrEqual(t *testing.T) {
+	var tests [][2]string
+	for i, v1 := range versions {
+		for _, v2 := range versions[i:] {
+			tests = append(tests, [2]string{v1, v2})
+		}
+	}
+	for _, tt := range tests {
+		t.Run(tt[0]+" <= "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.True(t, v1.LessThanOrEqual(v2))
+		})
+		t.Run(tt[0]+" > "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.False(t, v1.GreaterThan(v2))
+		})
+	}
+}
+
+func TestVersion_Equal(t *testing.T) {
+	var tests [][2]string
+	for _, v := range versions {
+		tests = append(tests, [2]string{v, v})
+	}
+	for _, tt := range tests {
+		t.Run(tt[0]+" = "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.True(t, v1.Equal(v2))
+		})
+	}
+}
+
+func TestVersion_GreaterThan(t *testing.T) {
+	var tests [][2]string
+	for i, v1 := range versions {
+		for _, v2 := range versions[:i] {
+			tests = append(tests, [2]string{v1, v2})
+		}
+	}
+	for _, tt := range tests {
+		t.Run(tt[0]+" > "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.True(t, v1.GreaterThan(v2))
+		})
+		t.Run(tt[0]+" <= "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.False(t, v1.LessThanOrEqual(v2))
+		})
+	}
+}
+
+func TestVersion_GreaterThanOrEqual(t *testing.T) {
+	var tests [][2]string
+	for i, v1 := range versions {
+		for _, v2 := range versions[:i+1] {
+			tests = append(tests, [2]string{v1, v2})
+		}
+	}
+	for _, tt := range tests {
+		t.Run(tt[0]+" >= "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.True(t, v1.GreaterThanOrEqual(v2))
+		})
+		t.Run(tt[0]+" < "+tt[1], func(t *testing.T) {
+			v1, v2 := parseVersions(t, tt[0], tt[1])
+			assert.False(t, v1.LessThan(v2))
+		})
+	}
+}
+
+func parseVersions(t *testing.T, s1, s2 string) (version.Version, version.Version) {
+	t.Helper()
+
+	v1, err := version.Parse(s1)
+	require.NoError(t, err)
+
+	v2, err := version.Parse(s2)
+	require.NoError(t, err)
+
+	return v1, v2
+}