From 47a92ff273ced167388fe8f7b2bcb0b6da8333eb Mon Sep 17 00:00:00 2001 From: Alex Kocharin Date: Thu, 12 Dec 2013 00:51:48 +0400 Subject: [PATCH] fail-safe semver parsing + tests, ref #25 --- lib/storage.js | 14 ++++++++++++-- test/st_merge.js | 10 ++++++++++ test/start.sh | 2 +- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/storage.js b/lib/storage.js index e350bd7eb..b9f400874 100644 --- a/lib/storage.js +++ b/lib/storage.js @@ -467,7 +467,7 @@ Storage.prototype.get_package = function(name, callback) { if (!~whitelist.indexOf(i)) delete result[i] } - result['dist-tags'].latest = Object.keys(result.versions).sort(semver.compareLoose) + result['dist-tags'].latest = Storage._semver_sort(Object.keys(result.versions)) for (var i in result['dist-tags']) { if (Array.isArray(result['dist-tags'][i])) { result['dist-tags'][i] = result['dist-tags'][i][result['dist-tags'][i].length-1] @@ -505,10 +505,20 @@ Storage._merge_versions = function(local, up) { } if (local['dist-tags'][i].indexOf(up['dist-tags'][i]) === -1) { local['dist-tags'][i].push(up['dist-tags'][i]) - local['dist-tags'][i].sort(semver.compareLoose) + local['dist-tags'][i] = Storage._semver_sort(local['dist-tags'][i]) } } } +// function filters out bad semver versions and sorts the array +// exported for unit tests only +Storage._semver_sort = function semver_sort(array) { + return array + .map(function(x) { return semver.parse(x, true) }) + .filter(function(x) { return !!x }) + .sort(semver.compareLoose) + .map(String) +} + module.exports = Storage diff --git a/test/st_merge.js b/test/st_merge.js index 014d0c514..bd23d0620 100644 --- a/test/st_merge.js +++ b/test/st_merge.js @@ -1,4 +1,5 @@ var assert = require('assert') + , semver_sort = require('../lib/storage')._semver_sort , merge = require('../lib/storage')._merge_versions //require('../lib/logger').setup() @@ -41,3 +42,12 @@ exports['Merge'] = { }, } +exports['semver_sort'] = function() { + assert.deepEqual(semver_sort(['1.2.3','1.2','1.2.3a','1.2.3c','1.2.3-b']), + [ '1.2.3-a', + '1.2.3-b', + '1.2.3-c', + '1.2.3' ] + ) +} + diff --git a/test/start.sh b/test/start.sh index 9ad918076..d83982113 100755 --- a/test/start.sh +++ b/test/start.sh @@ -4,6 +4,6 @@ CWD=$(pwd) PATH='../node_modules/.bin':$PATH TESTDIR=$(dirname $0) cd $TESTDIR -mocha -R list --ui exports ./tests.js ./no_proxy.js +mocha -R list --ui exports ./tests.js ./no_proxy.js ./st_merge.js cd $CWD