Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch Version Parsing Code #135

Merged
merged 1 commit into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"net/http"
"strings"

"github.com/Masterminds/semver/v3"
"github.com/chelnak/gh-changelog/internal/version"
"github.com/cli/go-gh"
"github.com/fatih/color"
)
Expand All @@ -24,8 +24,8 @@ func SliceContainsString(s []string, str string) bool {
return false
}

func IsValidSemanticVersion(version string) bool {
_, err := semver.NewVersion(version)
func IsValidSemanticVersion(v string) bool {
_, err := version.NormalizeVersion(v)
return err == nil
}

Expand All @@ -41,7 +41,7 @@ func CheckForUpdate(currentVersion string) bool {

currentVersion = parseLocalVersion(currentVersion)

if VersionIsGreaterThan(currentVersion, release.Version) {
if NextVersionIsGreaterThanCurrent(release.Version, currentVersion) {
color.Yellow("\nVersion %s is available ✨\n\n", release.Version)
fmt.Println("Run", color.GreenString(`gh extension upgrade chelnak/gh-changelog`), "to upgrade.")

Expand Down Expand Up @@ -73,17 +73,20 @@ func requestLatestRelease() (Release, error) {
return release, nil
}

func VersionIsGreaterThan(currentVersion, nextVersion string) bool {
currentSemVer, err := semver.NewVersion(currentVersion)
func NextVersionIsGreaterThanCurrent(nextVersion, currentVersion string) bool {
currentSemVer, err := version.NormalizeVersion(currentVersion)
if err != nil {
return false
}

// The nextVersion has already been validated by the builder
// so we can safely eat the error.
nextSemVer, _ := semver.NewVersion(nextVersion)
nextSemVer, err := version.NormalizeVersion(nextVersion)
if err != nil {
return false
}

return nextSemVer.Compare(currentSemVer) == 1
return nextSemVer.GreaterThan(currentSemVer)
}

func parseLocalVersion(version string) string {
Expand Down
77 changes: 76 additions & 1 deletion internal/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,82 @@ func TestVersionIsGreaterThan(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, utils.VersionIsGreaterThan("1.0.0", tt.value))
assert.Equal(t, tt.want, utils.NextVersionIsGreaterThanCurrent(tt.value, "1.0.0"))
})
}
}

func TestVersionIsGreaterThanPreRelease(t *testing.T) {
tests := []struct {
name string
value string
want bool
}{
{
name: "version is greater than and not a pre-release",
value: "7.0.0",
want: true,
},
{
name: "version is greater than and is a standard release",
value: "6.0.0",
want: true,
},
{
name: "version is greater than and is a pre-release",
value: "6.0.1-rc.1",
want: true,
},
{
name: "version is not greater than and not a pre-repease",
value: "0.1.0",
want: false,
},
{
name: "version is not greater than and is a pre-repease",
value: "v0.1.0-rc.1",
want: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, utils.NextVersionIsGreaterThanCurrent(tt.value, "6.0.0-rc.1"))
})
}
}

func TestVersionParsesWithDifferentPreReleaseDelimeters(t *testing.T) {
tests := []struct {
name string
value string
want bool
}{
{
name: "version is greater than and is a pre-release, using a -",
value: "6.0.1-rc.1",
want: true,
},
{
name: "version is greater than and is a pre-release, using a .",
value: "6.0.1-rc.1",
want: true,
},
{
name: "version is not greater than and is a pre-repease, using a -",
value: "v0.1.0-rc.1",
want: false,
},
{
name: "version is not greater than and is a pre-repease, using a .",
value: "v0.1.0.rc.1",
want: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, utils.NextVersionIsGreaterThanCurrent(tt.value, "6.0.0-rc.1"))
})
}
}
Expand Down
157 changes: 157 additions & 0 deletions internal/version/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Package version contains a wrapper for parsing semantic versions with the
// semver library.
// The code here will be removed if/when semver can handle pre-release versions with a dot.
// It's not ideal but a reasonable workaround for now.
package version

import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"

"github.com/Masterminds/semver/v3"
)

// The compiled version of the regex created at init() is cached here so it
// only needs to be created once.
var versionRegex *regexp.Regexp

// semVerRegex is the regular expression used to parse a semantic version.
const semVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` +
`((?:-|\.)([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?`

// Version represents a single semantic version.
type Version struct {
major, minor, patch uint64
pre string
metadata string
original string
}

func init() {
versionRegex = regexp.MustCompile("^" + semVerRegex + "$")
}

const (
num string = "0123456789"
allowed string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" + num
)

// NormalizeVersion is basically a copy of SemVers NewVersion. However, it's
// purpose is to normalize the version string to a semver compatible one.
func NormalizeVersion(v string) (*semver.Version, error) {
m := versionRegex.FindStringSubmatch(v)
if m == nil {
return nil, semver.ErrInvalidSemVer
}

sv := &Version{
metadata: m[8],
pre: m[5],
original: v,
}

var err error
sv.major, err = strconv.ParseUint(m[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing version segment: %s", err)
}

if m[2] != "" {
sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing version segment: %s", err)
}
} else {
sv.minor = 0
}

if m[3] != "" {
sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing version segment: %s", err)
}
} else {
sv.patch = 0
}

// Perform some basic due diligence on the extra parts to ensure they are
// valid.

if sv.pre != "" {
if err = validatePrerelease(sv.pre); err != nil {
return nil, err
}
}

if sv.metadata != "" {
if err = validateMetadata(sv.metadata); err != nil {
return nil, err
}
}

// Return the semver version.
return semver.NewVersion(sv.String())
}

// String converts a Version object to a string.
// Note, if the original version contained a leading v this version will not.
// See the Original() method to retrieve the original value. Semantic Versions
// don't contain a leading v per the spec. Instead it's optional on
// implementation.
func (v Version) String() string {
var buf bytes.Buffer

fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch)
if v.pre != "" {
fmt.Fprintf(&buf, "-%s", v.pre)
}
if v.metadata != "" {
fmt.Fprintf(&buf, "+%s", v.metadata)
}

return buf.String()
}

// Like strings.ContainsAny but does an only instead of any.
func containsOnly(s string, comp string) bool {
return strings.IndexFunc(s, func(r rune) bool {
return !strings.ContainsRune(comp, r)
}) == -1
}

// From the spec, "Identifiers MUST comprise only
// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
// Numeric identifiers MUST NOT include leading zeroes.". These segments can
// be dot separated.
func validatePrerelease(p string) error {
eparts := strings.Split(p, ".")
for _, p := range eparts {
if containsOnly(p, num) {
if len(p) > 1 && p[0] == '0' {
return semver.ErrSegmentStartsZero
}
} else if !containsOnly(p, allowed) {
return semver.ErrInvalidPrerelease
}
}

return nil
}

// From the spec, "Build metadata MAY be denoted by
// appending a plus sign and a series of dot separated identifiers immediately
// following the patch or pre-release version. Identifiers MUST comprise only
// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty."
func validateMetadata(m string) error {
eparts := strings.Split(m, ".")
for _, p := range eparts {
if !containsOnly(p, allowed) {
return semver.ErrInvalidMetadata
}
}
return nil
}
3 changes: 1 addition & 2 deletions pkg/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ func (b *builder) setNextVersion() error {
}
if len(b.tags) > 0 {
currentVersion := b.tags[0].Name

if !utils.VersionIsGreaterThan(currentVersion, b.nextVersion) {
if !utils.NextVersionIsGreaterThanCurrent(b.nextVersion, currentVersion) {
return fmt.Errorf("the next version should be greater than the former: '%s' ≤ '%s'", b.nextVersion, currentVersion)
}
}
Expand Down