From 731c2f3f70aa6fca1fa999967e072aeeeb76ee9d Mon Sep 17 00:00:00 2001 From: Jordan Harband Date: Thu, 4 Feb 2016 11:16:09 -0800 Subject: [PATCH] Add `nvm_get_minor_version` --- nvm.sh | 28 ++++++++++++++ test/fast/Unit tests/nvm_get_minor_version | 45 ++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100755 test/fast/Unit tests/nvm_get_minor_version diff --git a/nvm.sh b/nvm.sh index a74414d..2f3dc30 100755 --- a/nvm.sh +++ b/nvm.sh @@ -995,6 +995,34 @@ nvm_get_arch() { echo "$NVM_ARCH" } +nvm_get_minor_version() { + local VERSION + VERSION="$1" + + if [ -z "$VERSION" ]; then + echo 'a version is required' >&2 + return 1 + fi + + case "$VERSION" in + v | .* | *..* | v*[!.0123456789]* | [!v]*[!.0123456789]* | [!v0123456789]* | v[!0123456789]*) + echo 'invalid version number' >&2 + return 2 + ;; + esac + + local PREFIXED_VERSION + PREFIXED_VERSION="$(nvm_format_version "$VERSION")" + + local MINOR + MINOR="$(echo "$PREFIXED_VERSION" | command grep -e '^v' | command cut -c2- | command cut -d . -f 1,2)" + if [ -z "$MINOR" ]; then + echo 'invalid version number! (please report this)' >&2 + return 3 + fi + echo "$MINOR" +} + nvm_ensure_default_set() { local VERSION VERSION="$1" diff --git a/test/fast/Unit tests/nvm_get_minor_version b/test/fast/Unit tests/nvm_get_minor_version new file mode 100755 index 0000000..ebb63b3 --- /dev/null +++ b/test/fast/Unit tests/nvm_get_minor_version @@ -0,0 +1,45 @@ +#!/bin/sh + +die () { echo $@ ; exit 1; } + +. ../../../nvm.sh + +expect () { + INPUT="$1" + EXPECTED_OUTPUT="$2" + + OUTPUT="$(nvm_get_minor_version "$INPUT")" + [ "_$OUTPUT" = "_$EXPECTED_OUTPUT" ] || die "nvm_get_minor_version $INPUT did not return $EXPECTED_OUTPUT; got $OUTPUT" + + V_OUTPUT="$(nvm_get_minor_version "v$INPUT")" + [ "_$V_OUTPUT" = "_$EXPECTED_OUTPUT" ] || die "nvm_get_minor_version v$INPUT did not return $EXPECTED_OUTPUT; got $V_OUTPUT" +} + +fail_with () { + INPUT="$1" + EXPECTED_CODE="$2" + + EXIT_CODE="$(nvm_get_minor_version "$INPUT" >/dev/null 2>&1; echo $?)" + [ "_$EXIT_CODE" = "_$EXPECTED_CODE" ] || die "nvm_get_minor_version "$INPUT" did not fail with code "$EXPECTED_CODE"; got $EXIT_CODE" +} + +expect 1 1.0 +expect 1. 1.0 +expect 1.2 1.2 +expect 1.2. 1.2 +expect 1.2.3 1.2 +expect 1.2.3. 1.2 +expect 1.2.3.4 1.2 + +fail_with '' 1 +fail_with '.' 2 +fail_with '..' 2 +fail_with v 2 +fail_with .a 2 +fail_with .1 2 +fail_with v.1 2 +fail_with a.b 2 +fail_with 1.a 2 +fail_with a.1 2 +fail_with v1.a 2 +fail_with va.1 2