| 1 | 'use strict'
|
|---|
| 2 |
|
|---|
| 3 | const SemVer = require('../classes/semver')
|
|---|
| 4 | const parse = require('./parse')
|
|---|
| 5 | const { safeRe: re, t } = require('../internal/re')
|
|---|
| 6 |
|
|---|
| 7 | const coerce = (version, options) => {
|
|---|
| 8 | if (version instanceof SemVer) {
|
|---|
| 9 | return version
|
|---|
| 10 | }
|
|---|
| 11 |
|
|---|
| 12 | if (typeof version === 'number') {
|
|---|
| 13 | version = String(version)
|
|---|
| 14 | }
|
|---|
| 15 |
|
|---|
| 16 | if (typeof version !== 'string') {
|
|---|
| 17 | return null
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | options = options || {}
|
|---|
| 21 |
|
|---|
| 22 | let match = null
|
|---|
| 23 | if (!options.rtl) {
|
|---|
| 24 | match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
|
|---|
| 25 | } else {
|
|---|
| 26 | // Find the right-most coercible string that does not share
|
|---|
| 27 | // a terminus with a more left-ward coercible string.
|
|---|
| 28 | // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
|
|---|
| 29 | // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
|
|---|
| 30 | //
|
|---|
| 31 | // Walk through the string checking with a /g regexp
|
|---|
| 32 | // Manually set the index so as to pick up overlapping matches.
|
|---|
| 33 | // Stop when we get a match that ends at the string end, since no
|
|---|
| 34 | // coercible string can be more right-ward without the same terminus.
|
|---|
| 35 | const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
|
|---|
| 36 | let next
|
|---|
| 37 | while ((next = coerceRtlRegex.exec(version)) &&
|
|---|
| 38 | (!match || match.index + match[0].length !== version.length)
|
|---|
| 39 | ) {
|
|---|
| 40 | if (!match ||
|
|---|
| 41 | next.index + next[0].length !== match.index + match[0].length) {
|
|---|
| 42 | match = next
|
|---|
| 43 | }
|
|---|
| 44 | coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
|
|---|
| 45 | }
|
|---|
| 46 | // leave it in a clean state
|
|---|
| 47 | coerceRtlRegex.lastIndex = -1
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | if (match === null) {
|
|---|
| 51 | return null
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | const major = match[2]
|
|---|
| 55 | const minor = match[3] || '0'
|
|---|
| 56 | const patch = match[4] || '0'
|
|---|
| 57 | const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
|
|---|
| 58 | const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
|
|---|
| 59 |
|
|---|
| 60 | return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
|
|---|
| 61 | }
|
|---|
| 62 | module.exports = coerce
|
|---|