Skip to content

Commit 2efe76d

Browse files
committed
Do not throw when testing invalid version strings
Range.test() and Comparator.test() would throw if passed an invalid SemVer string. It's better in those cases to just treat it as not a match. (This is what npm does internally when using those functions, wrapping in a try/catch.)
1 parent 0e3bced commit 2efe76d

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

semver.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -810,7 +810,11 @@ Comparator.prototype.test = function (version) {
810810
}
811811

812812
if (typeof version === 'string') {
813-
version = new SemVer(version, this.options)
813+
try {
814+
version = new SemVer(version, this.options)
815+
} catch (er) {
816+
return false
817+
}
814818
}
815819

816820
return cmp(version, this.operator, this.semver, this.options)
@@ -1261,7 +1265,11 @@ Range.prototype.test = function (version) {
12611265
}
12621266

12631267
if (typeof version === 'string') {
1264-
version = new SemVer(version, this.options)
1268+
try {
1269+
version = new SemVer(version, this.options)
1270+
} catch (er) {
1271+
return false
1272+
}
12651273
}
12661274

12671275
for (var i = 0; i < this.set.length; i++) {

test/index.js

+6
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,9 @@ test('negative range tests', function (t) {
335335
['^1.2.3', '2.0.0-pre'],
336336
['0.x', undefined],
337337
['*', undefined],
338+
// invalid versions never satisfy, but shouldn't throw
339+
['*', 'not a version'],
340+
['>=2', 'glorp'],
338341
].forEach(function (v) {
339342
var range = v[0]
340343
var ver = v[1]
@@ -1014,6 +1017,9 @@ test('comparator testing', function (t) {
10141017
t.ok(c2.test('1.2.4'))
10151018
var c3 = new Comparator(c, true)
10161019
t.ok(c3.test('1.2.4'))
1020+
// test an invalid version, should not throw
1021+
var c4 = new Comparator(c)
1022+
t.notOk(c4.test('not a version string'))
10171023
t.end()
10181024
})
10191025

0 commit comments

Comments
 (0)