Skip to content

Instantly share code, notes, and snippets.

@equinusocio
Last active May 12, 2020 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save equinusocio/86fa3dbf9c0e9b36482a4743b1d9156d to your computer and use it in GitHub Desktop.
Save equinusocio/86fa3dbf9c0e9b36482a4743b1d9156d to your computer and use it in GitHub Desktop.
Automatic node switching for zsh and bash
# place this at the end
# ••••••••••••••••••••••••••••••••••••••••
_enter_dir() {
local git_root
git_root=$(git rev-parse --show-toplevel 2>/dev/null)
if [[ "$git_root" == "$PREV_PWD" ]]; then
return
elif [[ -n "$git_root" && -f "$git_root/.nvmrc" ]]; then
nvm use
NVM_DIRTY=1
elif [[ "$NVM_DIRTY" == 1 ]]; then
nvm use default
NVM_DIRTY=0
fi
PREV_PWD="$git_root"
}
export PROMPT_COMMAND=_enter_dir
#export PROMPT_COMMAND="$PROMPT_COMMAND;_enter_dir" # use this if PROMPT_COMMAND already defined
# place this after nvm initialization!
# ••••••••••••••••••••••••••••••••••••••••
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
elif [ "$node_version" != "$(nvm version default)" ]; then
echo "Reverting to nvm default version"
nvm use default
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