Skip to content

Commit c6b0ce1

Browse files
committed
fix: throw on bad version
1 parent 503a4e5 commit c6b0ce1

File tree

4 files changed

+37
-15
lines changed

4 files changed

+37
-15
lines changed

functions/diff.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
const parse = require('./parse')
1+
const parse = require('./parse.js')
22

33
const diff = (version1, version2) => {
4-
const v1 = parse(version1)
5-
const v2 = parse(version2)
4+
const v1 = parse(version1, null, true)
5+
const v2 = parse(version2, null, true)
66
const comparison = v1.compare(v2)
77

88
if (comparison === 0) {

functions/parse.js

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
const { MAX_LENGTH } = require('../internal/constants')
22
const SemVer = require('../classes/semver')
3-
const parse = (version, options) => {
3+
const parse = (version, options, throwErrors = false) => {
44
if (version instanceof SemVer) {
55
return version
66
}
7+
if (!throwErrors) {
8+
if (typeof version !== 'string') {
9+
return null
10+
}
711

8-
if (typeof version !== 'string') {
9-
return null
10-
}
11-
12-
if (version.length > MAX_LENGTH) {
13-
return null
14-
}
12+
if (version.length > MAX_LENGTH) {
13+
return null
14+
}
1515

16-
try {
17-
return new SemVer(version, options)
18-
} catch (er) {
19-
return null
16+
try {
17+
return new SemVer(version, options)
18+
} catch (er) {
19+
return null
20+
}
2021
}
22+
return new SemVer(version, options)
2123
}
2224

2325
module.exports = parse

test/functions/diff.js

+10
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,13 @@ test('diff versions test', (t) => {
4343

4444
t.end()
4545
})
46+
47+
test('throws on bad version', (t) => {
48+
t.throws(() => {
49+
diff('bad', '1.2.3')
50+
}, {
51+
message: 'Invalid Version: bad',
52+
name: 'TypeError',
53+
})
54+
t.end()
55+
})

test/functions/parse.js

+10
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ t.test('returns null instead of throwing when presented with garbage', t => {
99
t.equal(parse(v, opts), null, msg))
1010
})
1111

12+
t.test('throw errors if asked to', t => {
13+
t.throws(() => {
14+
parse('bad', null, true)
15+
})
16+
t.throws(() => {
17+
parse([], null, true)
18+
})
19+
t.end()
20+
})
21+
1222
t.test('parse a version into a SemVer object', t => {
1323
t.match(parse('1.2.3'), new SemVer('1.2.3'))
1424
const s = new SemVer('4.5.6')

0 commit comments

Comments
 (0)