diff --git a/README.md b/README.md index fd5151ab..521aa458 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: @@ -52,6 +54,10 @@ Options: -l --loose Interpret versions and ranges loosely +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. @@ -364,3 +370,15 @@ satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver +string to semver. It looks for the first digit in a string, and +consumes all remaining characters which satisfy at least a partial semver +(e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). +Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). +All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). +Only text which lacks digits will fail coercion (`version one` is not valid). diff --git a/semver.js b/semver.js index d6b4fcd1..e5e1312f 100644 --- a/semver.js +++ b/semver.js @@ -1306,7 +1306,7 @@ function coerce(version) { if (version.length > MAX_LENGTH) return null; - var match = version.match(/([vV]?\d+(?:[.]\d+)*)/) + var match = version.match(/([vV]?\d+(?:[.]\d+){0,2})/) if (match == null) return null diff --git a/test/coerce.js b/test/coerce.js index eca6db0a..73e408f6 100644 --- a/test/coerce.js +++ b/test/coerce.js @@ -14,6 +14,7 @@ test('\ncoerce tests', function(t) { function () { return '1.2.3'; }, '', '.', + 'version one', tooLong ].forEach(function (input) { var msg = 'coerce(' + input + ') should be null' @@ -60,6 +61,10 @@ test('\ncoerce tests', function(t) { ['version1', '1.0.0'], ['version1.0', '1.0.0'], ['version1.1', '1.1.0'], + ['42.6.7.9.3-alpha', '42.6.7'], + ['v2', '2.0.0'], + ['v3.4 replaces v3.3.1', '3.4.0'], + ['4.6.3.9.2-alpha2', '4.6.3'], [justRight, '12.1.1'] ].forEach(function (tuple) { var input = tuple[0]