diff --git a/README.md b/README.md index df54e7a0..471c153f 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') +const semverIdentifier = require('semver/functions/identifier') // low-level comparators between versions const semverGt = require('semver/functions/gt') @@ -400,6 +401,7 @@ strings that they parse. or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. +* `identifier(v)`: Return a valid prerelease identifier, or null if it's not valid. ### Comparison diff --git a/functions/identifier.js b/functions/identifier.js new file mode 100644 index 00000000..ae4b480c --- /dev/null +++ b/functions/identifier.js @@ -0,0 +1,10 @@ +const {t, src} = require('../internal/re') +const identifier = (version) => { + const split = version.split('\.'); + const valid = split.every(part => new RegExp(`^${src[t.PRERELEASEIDENTIFIER]}$`).test(part)); + if (!valid) { + return null; + } + return version; +} +module.exports = identifier diff --git a/index.js b/index.js index 4a342c6a..5fe844f5 100644 --- a/index.js +++ b/index.js @@ -26,6 +26,7 @@ const gte = require('./functions/gte') const lte = require('./functions/lte') const cmp = require('./functions/cmp') const coerce = require('./functions/coerce') +const identifier = require('./functions/identifier') const Comparator = require('./classes/comparator') const Range = require('./classes/range') const satisfies = require('./functions/satisfies') @@ -64,6 +65,7 @@ module.exports = { lte, cmp, coerce, + identifier, Comparator, Range, satisfies, @@ -85,4 +87,4 @@ module.exports = { SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, -} +} \ No newline at end of file diff --git a/test/functions/identifier.js b/test/functions/identifier.js new file mode 100644 index 00000000..0e121f8c --- /dev/null +++ b/test/functions/identifier.js @@ -0,0 +1,10 @@ +const {test} = require('tap') +const identifier = require('../../functions/identifier.js') + +test('identifier tests', t => { + t.equal(identifier('hotfix-410'), 'hotfix-410') + t.equal(identifier('hotfix/410'), null) + t.equal(identifier('123.123.123'), '123.123.123') + t.equal(identifier('007.james.bond'), null) + t.end() +})