mirror of
https://github.com/nvm-sh/nvm.git
synced 2025-05-10 22:31:51 +00:00
86 lines
1.8 KiB
Bash
Executable File
86 lines
1.8 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
#
|
|
# 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 [ "$1" == "nvm" ]; then
|
|
eval "$@"
|
|
else
|
|
check_version
|
|
exec "$@"
|
|
fi
|
|
|