Skip to content

Instantly share code, notes, and snippets.

@quchao
Created January 23, 2019 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save quchao/3ecfda4602c0342cd47861d094bbc261 to your computer and use it in GitHub Desktop.
Save quchao/3ecfda4602c0342cd47861d094bbc261 to your computer and use it in GitHub Desktop.
Calling `nvm use` automatically in a directory with a .nvmrc file
#! /usr/bin/env zsh
# Ref: https://github.com/creationix/nvm#calling-nvm-use-automatically-in-a-directory-with-a-nvmrc-file
# place this after nvm initialization!
autoload -Uz add-zsh-hook
# Function: load-nvmrc
load-nvmrc() {
local _CUR_NODE_VER="$(nvm version)"
local _NVMRC_PATH="$(nvm_find_nvmrc)"
if [[ -n "${_NVMRC_PATH}" ]]; then
local _NVMRC_NODE_VER="$(nvm version "$(cat "${_NVMRC_PATH}")")"
if [[ "${_NVMRC_NODE_VER}" == 'N/A' ]]; then
local compcontext='yn:yes or no:(y n)'
vared -cp "Install the unmet version ($(cat "${_NVMRC_PATH}")) in nvm (y/n) ?" _ANSWER
if [[ "${_ANSWER}" =~ '^y(es)?$' ]] ; then
nvm install
fi
elif [[ "${_NVMRC_NODE_VER}" != "${_CUR_NODE_VER}" ]]; then
nvm use
fi
elif [[ "${_CUR_NODE_VER}" != "$(nvm version default)" ]]; then
echo -e "Reverting to the default version in nvm"
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