Last active
March 28, 2024 09:16
-
-
Save karfau/dcf98c6eefc2f2132c160f5c14d2112f to your computer and use it in GitHub Desktop.
A script that can be sourced in shell scripts to enable nvm support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# shellcheck shell=sh | |
# https://gist.github.com/karfau/dcf98c6eefc2f2132c160f5c14d2112f | |
# needs to be sourced as part of your script | |
# 1. tries to configure nvm and run `nvm install` | |
# 2. checks if the node version is correct based on ./.nvmrc (`v` prefix not supported) | |
# if both doesn't work, exits with code 1 and some helpful messages | |
# Sometimes we prefer `nvm use` over `nvm install` | |
# you can basically put anything you want here, but the default is `install` | |
NVM_SETUP_COMMAND=${NVM_SETUP_COMMAND:-install} | |
NVM_DIR=${NVM_DIR:-$HOME}/.nvm} | |
# https://unix.stackexchange.com/a/184512/194420 | |
# https://github.com/nvm-sh/nvm/issues/1290 | |
if [ -f ${NVM_DIR}/nvm.sh ]; then | |
echo "sourcing nvm from NVM_DIR:${NVM_DIR}" | |
. ${NVM_DIR}/nvm.sh | |
elif command -v brew; then | |
# https://docs.brew.sh/Manpage#--prefix-formula | |
BREW_PREFIX=$(brew --prefix nvm) | |
if [ -f "$BREW_PREFIX/nvm.sh" ]; then | |
echo "sourcing nvm from brew ($BREW_PREFIX)" | |
. $BREW_PREFIX/nvm.sh | |
fi | |
fi | |
if command -v nvm ; then | |
echo "NVM_SETUP_COMMAND is ${NVM_SETUP_COMMAND}" | |
nvm ${NVM_SETUP_COMMAND} | |
else | |
echo "WARN: not able to configure nvm" | |
fi | |
NODE_VERSION="v$(cat .nvmrc)" | |
which node | |
ACTIVE_VERSION=$(node --version) | |
GLOBAL_NPM=$(which npm || echo "not found on PATH") | |
# .nvmrc can contain only major or major.minor or full version | |
# so we replace active version with node version and anything afterwards | |
# if something is left, it's not a match | |
if [ "${ACTIVE_VERSION%%$NODE_VERSION*}" ] || [ ! -e "$GLOBAL_NPM" ]; then | |
echo "expected node '$NODE_VERSION' and npm on path" | |
echo "but was '$ACTIVE_VERSION' and npm:'$GLOBAL_NPM'" | |
return 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Makes total sense, especially if nvm is installed via brew in which case NVM_DIR might not be set.
Update: changed it with a small tweak to keep the original value if it is present, in the same way it is done for NVM_INSTALL_COMMAND