diff --git a/nvm.sh b/nvm.sh index d4211830..230eb90d 100755 --- a/nvm.sh +++ b/nvm.sh @@ -913,6 +913,16 @@ nvm_version() { PATTERN="stable" ;; esac + + # Fast path: an exact, fully-qualified version that is installed resolves to + # itself, unless an alias of the same name takes precedence. Short-circuiting + # it here avoids the `nvm_ls` subprocess pipeline on shell startup; every + # other pattern falls through to `nvm_ls` unchanged. + if nvm_is_installed_exact_version "${PATTERN}"; then + nvm_echo "${PATTERN}" + return 0 + fi + VERSION="$(nvm_ls "${PATTERN}" | command tail -1)" case "${VERSION}" in system[[:blank:]]*) diff --git a/test/fast/Unit tests/nvm_version b/test/fast/Unit tests/nvm_version index 9334f40f..689bca02 100755 --- a/test/fast/Unit tests/nvm_version +++ b/test/fast/Unit tests/nvm_version @@ -2,7 +2,7 @@ die () { echo "$@" ; cleanup ; exit 1; } cleanup () { - unset -f nvm_ls_current nvm_ls + unset -f nvm_ls_current nvm_ls nvm_is_version_installed } : nvm.sh @@ -48,3 +48,30 @@ try nvm_version foo EXPECTED_OUTPUT="N/A" [ "_$CAPTURED_STDOUT" = "_$EXPECTED_OUTPUT" ] || die '"nvm_version" did not return N/A when nvm_ls returns nothing' [ "_$CAPTURED_EXIT_CODE" = "_3" ] || die '"nvm_version" returning N/A did not exit code with code 3' + +# an exact installed version resolves without forking "nvm_ls" +nvm_is_version_installed() { return 0; } +nvm_ls() { die '"nvm_version" must not call "nvm_ls" for an exact installed version'; } +try nvm_version v1.2.3 +EXPECTED_OUTPUT="v1.2.3" +[ "_$CAPTURED_STDOUT" = "_$EXPECTED_OUTPUT" ] || die '"nvm_version v1.2.3" did not return the version itself; got '"$CAPTURED_STDOUT" +[ "_$CAPTURED_EXIT_CODE" = "_0" ] || die '"nvm_version v1.2.3" did not exit 0; got '"$CAPTURED_EXIT_CODE" + +# an exact version that is not installed still falls back to "nvm_ls" +nvm_is_version_installed() { return 1; } +nvm_ls() { echo "pattern: $1"; } +try nvm_version v1.2.3 +EXPECTED_OUTPUT="pattern: v1.2.3" +[ "_$CAPTURED_STDOUT" = "_$EXPECTED_OUTPUT" ] || die '"nvm_version v1.2.3" did not fall back to "nvm_ls"; got '"$CAPTURED_STDOUT" +[ "_$CAPTURED_EXIT_CODE" = "_0" ] || die '"nvm_version v1.2.3" did not exit 0; got '"$CAPTURED_EXIT_CODE" + +# only exact, fully-qualified versions take the fast path +nvm_is_version_installed() { die '"nvm_version" must not call "nvm_is_version_installed" for non-exact versions'; } +nvm_ls() { echo "pattern: $1"; } +for PATTERN in v1.2 v1 1.2.3 v1.2.3-rc.1 v1.2.3.4 v1.2.3.; do + try nvm_version "$PATTERN" + EXPECTED_OUTPUT="pattern: $PATTERN" + [ "_$CAPTURED_STDOUT" = "_$EXPECTED_OUTPUT" ] || die "nvm_version $PATTERN did not fall back to nvm_ls; got $CAPTURED_STDOUT" + [ "_$CAPTURED_EXIT_CODE" = "_0" ] || die "nvm_version $PATTERN did not exit 0; got $CAPTURED_EXIT_CODE" +done +unset -f nvm_is_version_installed