Skip to content

Commit c81378f

Browse files
fix(version): prevent panic on empty or invalid version string in Compare
Signed-off-by: Satyam Pandey <satyam53@tsecol.onmicrosoft.com>
1 parent cdc1824 commit c81378f

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

operator/internal/version/version.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,12 @@ func IsValid(version string) bool {
3939
return semver.IsValid(version)
4040
}
4141

42-
// Compare compares two versions and returns 0 if they are equal, 1 if version1 is greater than version2, -1 if version1 is less than version2
42+
// Compare compares two versions and returns 0 if they are equal, 1 if version1 is greater than version2, -1 if version1 is less than version2,
43+
// or -2 if either version is invalid or empty.
4344
func Compare(version1, version2 string) int {
45+
if !IsValid(version1) || !IsValid(version2) {
46+
return -2
47+
}
4448
if version1[0] != 'v' {
4549
version1 = "v" + version1
4650
}

operator/internal/version/version_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ var _ = Describe("version", func() {
6666
Entry("left is older", "v1.2.3", "v1.3.0", -1),
6767
Entry("left is newer", "v2.0.0", "v1.9.9", 1),
6868
Entry("prerelease sorts before its release", "v1.2.3-rc.1", "v1.2.3", -1),
69+
Entry("empty on the right returns -2", "v1.2.3", "", -2),
70+
Entry("empty on the left returns -2", "", "v1.2.3", -2),
71+
Entry("empty on both sides returns -2", "", "", -2),
72+
Entry("invalid on the left returns -2", "dev", "v1.2.3", -2),
73+
Entry("invalid on the right returns -2", "v1.2.3", "dev", -2),
6974
)
7075
})
7176

0 commit comments

Comments
 (0)