Created
October 8, 2021 16:09
-
-
Save davisshaver/d94057a051e8bc263a13ecea1e9b3c33 to your computer and use it in GitHub Desktop.
zsh nvm autoload
This file contains hidden or 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
autoload -U add-zsh-hook | |
load-nvmrc() { | |
local node_version="$(nvm version)" | |
local nvmrc_path="$(nvm_find_nvmrc)" | |
if [ -n "$nvmrc_path" ]; then | |
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")") | |
if [ "$nvmrc_node_version" = "N/A" ]; then | |
nvm install | |
elif [ "$nvmrc_node_version" != "$node_version" ]; then | |
nvm use | |
fi | |
else | |
if ! command -v jq &> /dev/null | |
then | |
echo "This command requires jq" | |
echo "See https://stedolan.github.io/jq/" | |
echo "Reverting to nvm default version" | |
nvm use default | |
return 1 | |
fi | |
if [[ ! -r package.json ]] | |
then | |
echo 'Can not read package.json in this directory' | |
echo "Reverting to nvm default version" | |
nvm use default | |
return 1 | |
fi | |
node_ver=$(jq -r '.engines.node' package.json) | |
if [[ $node_ver -eq '' ]] | |
then | |
echo "package.json does not contain an .engines.node entry" | |
echo "Reverting to nvm default version" | |
nvm use default | |
return 1 | |
fi | |
nvm use $node_ver | |
fi | |
} | |
add-zsh-hook chpwd load-nvmrc | |
load-nvmrc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment