Buy Me a Coffee

[Golang] Code snippets - Semver comparison

To make the project backward-compatible, a common util function for comparing the semantic version is indispensable. Here is a Golang solution implemented by leveraging go-semver package.

package utils

import "github.com/coreos/go-semver/semver"

// CompareSemanticVersion compares two string written in semver format
// return 0 indicates that the first version equals to the second version
// return 1 indicates that the first version is greater than the second version
// return -1 indicates that the first version is less than the second version
func CompareSemanticVersion(current, last string) int {
	if current == last {
		return 0
	}

	currentVersion := semver.New(current)
	lastVersion := semver.New(last)
	if currentVersion.LessThan(*lastVersion) {
		return -1
	}
	return 1
}

The unit test:

package utils

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func Test_CompareSemanticVersion(t *testing.T) {
	tests := []struct {
		name     string
		current  string
		last     string
		expected int
	}{
		{
			name:     "current version = last version",
			current:  "2.15.0",
			last:     "2.15.0",
			expected: 0,
		},
		{
			name:     "current version < last version",
			current:  "2.15.0",
			last:     "2.15.1",
			expected: -1,
		},
		{
			name:     "current version > last version",
			current:  "2.15.0",
			last:     "2.14.1",
			expected: 1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			actual := CompareSemanticVersion(tt.current, tt.last)
			require.Equal(t, tt.expected, actual)
		})
	}
}

Enjoyed this article? Support my work with a coffee ☕ on Ko-fi.
Buy Me a Coffee at ko-fi.com
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !