fix nil version safety

This commit is contained in:
Aneurin Barker Snook
2024-07-12 11:42:48 +01:00
parent 01ca4b8660
commit cac475d2f2
2 changed files with 16 additions and 0 deletions
+13
View File
@@ -19,6 +19,10 @@ type Version struct {
//
// Extensions such as pre-release version or build metadata are ignored when comparing versions.
func (a *Version) Compare(b *Version) int {
if a == nil || b == nil {
return 0
}
if a.Major == b.Major {
if a.Minor == b.Minor {
if a.Patch == b.Patch {
@@ -48,12 +52,21 @@ func (a *Version) Less(b *Version) bool {
//
// See https://semver.org/#is-v123-a-semantic-version
func (v *Version) SemanticString() string {
if v == nil {
return ""
}
return fmt.Sprintf("%d.%d.%d%s", v.Major, v.Minor, v.Patch, v.Extension)
}
func (v *Version) String() string {
if v == nil {
return ""
}
if v.Text != "" {
return v.Text
}
return v.SemanticString()
}
+3
View File
@@ -55,6 +55,9 @@ func TestVersion_Compare(t *testing.T) {
{A: MustParse("1.20.0"), B: MustParse("1.2.0"), Expected: 1},
{A: MustParse("1.20.0"), B: MustParse("1.2.20"), Expected: 1},
{A: MustParse("1.20.0"), B: MustParse("1.20.1"), Expected: -1},
{A: MustParse("1.0.0"), Expected: 0},
{B: MustParse("1.0.0"), Expected: 0},
{Expected: 0},
}
for i, testCase := range testCases {