From 8a138d98ed40403f4fde70c80c677dc6bb04cac2 Mon Sep 17 00:00:00 2001 From: Jordan Harband Date: Thu, 5 May 2016 01:27:17 -0700 Subject: [PATCH] [Refactor] Use `awk` to improve version comparison performance --- nvm.sh | 39 +++++++++++++++++---------- test/fast/Unit tests/nvm_version_path | 5 +++- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/nvm.sh b/nvm.sh index 5c41c3a..a802dc7 100755 --- a/nvm.sh +++ b/nvm.sh @@ -166,19 +166,32 @@ nvm_rc_version() { } nvm_version_greater() { - local LHS - LHS="$(nvm_normalize_version "$1")" - local RHS - RHS="$(nvm_normalize_version "$2")" - [ "$LHS" -gt "$RHS" ]; + command awk 'BEGIN { + if (ARGV[1] == "" || ARGV[2] == "") exit(1) + split(ARGV[1], a, /\./); + split(ARGV[2], b, /\./); + for (i=1; i<=3; i++) { + if (a[i] && a[i] !~ /^[0-9]+$/) exit(2); + if (b[i] && b[i] !~ /^[0-9]+$/) { exit(0); } + if (a[i] < b[i]) exit(3); + else if (a[i] > b[i]) exit(0); + } + exit(4) + }' "${1#v}" "${2#v}"; } nvm_version_greater_than_or_equal_to() { - local LHS - LHS="$(nvm_normalize_version "$1")" - local RHS - RHS="$(nvm_normalize_version "$2")" - [ "$LHS" -ge "$RHS" ]; + command awk 'BEGIN { + if (ARGV[1] == "" || ARGV[2] == "") exit(1) + split(ARGV[1], a, /\./); + split(ARGV[2], b, /\./); + for (i=1; i<=3; i++) { + if (a[i] && a[i] !~ /^[0-9]+$/) exit(2); + if (a[i] < b[i]) exit(3); + else if (a[i] > b[i]) exit(0); + } + exit(0) + }' "${1#v}" "${2#v}"; } nvm_version_dir() { @@ -331,7 +344,7 @@ nvm_is_valid_version() { *) local VERSION VERSION="$(nvm_strip_iojs_prefix "$1")" - nvm_version_greater "$VERSION" + nvm_version_greater_than_or_equal_to "$VERSION" 0 ;; esac } @@ -398,9 +411,7 @@ nvm_prepend_path() { nvm_binary_available() { # binaries started with node 0.8.6 - local FIRST_VERSION_WITH_BINARY - FIRST_VERSION_WITH_BINARY="0.8.6" - nvm_version_greater_than_or_equal_to "$(nvm_strip_iojs_prefix "$1")" "$FIRST_VERSION_WITH_BINARY" + nvm_version_greater_than_or_equal_to "$(nvm_strip_iojs_prefix "${1-}")" v0.8.6 } nvm_print_formatted_alias() { diff --git a/test/fast/Unit tests/nvm_version_path b/test/fast/Unit tests/nvm_version_path index 547ceb8..b8ae685 100755 --- a/test/fast/Unit tests/nvm_version_path +++ b/test/fast/Unit tests/nvm_version_path @@ -4,7 +4,10 @@ die () { echo $@ ; exit 1; } . ../../../nvm.sh -[ "$(nvm_version_path foo)" = "$NVM_DIR/foo" ] || die '"nvm_version_path foo" did not return correct location' +OUTPUT="$(nvm_version_path foo)" +EXPECTED_OUTPUT="$NVM_DIR/foo" +[ "$OUTPUT" = "$EXPECTED_OUTPUT" ] || die "'nvm_version_path foo' did not return correct location; expected '$EXPECTED_OUTPUT', got '$OUTPUT'" + [ "$(nvm_version_path 2>&1)" = "version is required" ] || die '"nvm_version_path" did not error out' [ "$(nvm_version_path v0.11.0)" = "$NVM_DIR/v0.11.0" ] || die 'old version has the wrong path' [ "$(nvm_version_path v0.12.0)" = "$NVM_DIR/versions/node/v0.12.0" ] || die 'new version has the wrong path'