Skip to content

Commit

Permalink
Improved coerce regex and added coerce to README.
Browse files Browse the repository at this point in the history
- updated README with new CLI usage and a section for the coerce function
- minimized how much was consumed by the coerce regex
- added all coercion examples from the README to the coerce tests
  • Loading branch information
joeledwards committed Nov 8, 2017
1 parent 68cef2d commit e7092b4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
18 changes: 18 additions & 0 deletions README.md
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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).
2 changes: 1 addition & 1 deletion semver.js
Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions test/coerce.js
Expand Up @@ -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'
Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit e7092b4

Please sign in to comment.