From 1be0fb627ecb9ab6ee4a69cba8aadf252e3f8b7e Mon Sep 17 00:00:00 2001 From: Joel Chen Date: Wed, 28 Dec 2016 16:24:43 -0800 Subject: [PATCH] enhance nvm-exec add -v option; try to use realpath to find nvm's dir; support exec nvm itself --- nvm-exec | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/nvm-exec b/nvm-exec index c47cd06..6ec7796 100755 --- a/nvm-exec +++ b/nvm-exec @@ -1,15 +1,85 @@ #!/usr/bin/env bash -DIR="$(command cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +# +# Regular commands can be executed as +# +# sudo nvm-exec [-v 6.9.2] npm install -g npm +# +# If no -v option provided, then try to use $NODE_VERSION, .nvmrc, default, and finally current +# +# When using sudo, use "sudo -E" to preserve env to pass NODE_VERSION. +# +# nvm commands can be executed as +# +# sudo nvm-exec nvm install 6.9.2 +# sudo nvm-exec nvm alias default 6.9.2 +# + +function nvm_fail() { + echo "$1" >&2 + exit 127 +} + +has_realpath="" + +function find_nvm_dir() { + if which realpath >& /dev/null; then + has_realpath=yes + dirname "$(realpath "$0")" + else + command cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd + fi +} + +DIR="$(find_nvm_dir)" + +function check_nvm_sh() { + if [ ! -f "$DIR/nvm.sh" ]; then + local rp_msg="" + [ "$has_realpath" == "yes" ] || rp_msg="; missing realpath command for finding nvm-exec's realpath to search for nvm.sh" + nvm_fail "Unable to find nvm.sh at $DIR$rp_msg" + fi +} + +check_nvm_sh + +function nvm_use() { + nvm use "$1" > /dev/null || nvm_fail "nvm use $2 failed" +} + +function nvm_use_v() { + [ -n "$1" ] && nvm_use "$1" "$2" +} + +opt_version="" + +if [ "$1" == "-v" ]; then + shift + opt_version=$1 + shift +fi + +function check_version() { + nvm_use_v "$opt_version" "(-v $opt_version)" && return + nvm_use_v "$NODE_VERSION" "(NODE_VERSION $NODE_VERSION)" && return + + local nvmrc + nvmrc=$(nvm which 2>&1 | grep ^Found | grep -o "\'.*\.nvmrc\'") + [ -n "$nvmrc" ] && nvm_use "" "with $nvmrc file" && return + + nvm which default >& /dev/null && nvm_use_v default default && return + nvm which current >& /dev/null && nvm_use_v current current && return + + nvm_fail "No -v option or NODE_VERSION provided; no .nvmrc file, no default, and no current found" +} # shellcheck disable=SC1090 \. "$DIR/nvm.sh" --no-use -if [ -n "$NODE_VERSION" ]; then - nvm use "$NODE_VERSION" > /dev/null || exit 127 -elif ! nvm use >/dev/null 2>&1; then - echo "No NODE_VERSION provided; no .nvmrc file found" >&2 - exit 127 +if [ "$1" == "nvm" ]; then + eval "$@" +else + check_version + exec "$@" fi -exec "$@"