Skip to content

Instantly share code, notes, and snippets.

@jhob
Created August 6, 2018 20:56
Show Gist options
  • Save jhob/307bba0642e7a2051d4f808ccd8de468 to your computer and use it in GitHub Desktop.
Save jhob/307bba0642e7a2051d4f808ccd8de468 to your computer and use it in GitHub Desktop.
nish.sh
# inspired by https://gist.github.com/assaf/ee377a186371e2e269a7
# requires [n](https://github.com/tj/n) and [jq](https://stedolan.github.io/jq/)
# Install nodejs version specified in package.json via n, otherwise use a blessed version
#
# Exit code:
# 0 Successfully installed and using the desired version
# 1 No package.json in current directory
#
# See debug messages by setting DEBUG=nish in your environment
function __nish_needs_resolution() {
local semver=$1
if ! [[ "$semver" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
return 0
else
return 1
fi
}
function __nish_install_nodejs() {
local version="$1"
if __nish_needs_resolution "$version"; then
version=$(curl --silent --get --retry 5 --retry-max-time 15 --data-urlencode "range=${version}" https://semver.io/node/resolve)
fi
echo "Using node v$version"
n $version
return $?
}
function nish_debug () {
if [[ "${DEBUG}" == "nish" ]] ; then
echo "DEBUG: ${1}"
fi
}
function nish() {
if [[ ! -f package.json ]] ; then
nish_debug "No package.json in current directory"
return 0
fi
local blessed_nodejs_version=8
local desired_nodejs_version=$(cat package.json | jq --raw-output .engines.node)
[[ "$desired_nodejs_version" == "null" ]] && desired_nodejs_version="$blessed_nodejs_version"
__nish_install_nodejs "$desired_nodejs_version" || return $?
return 0
}
function cd() {
builtin cd "$@"
[ -z "$nish_NO_AUTO" ] && nish
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment