Skip to content

Instantly share code, notes, and snippets.

@yuanoook
Last active July 12, 2023 01:37
Show Gist options
  • Save yuanoook/9e363ec2620d0b0e33c41e047dd25580 to your computer and use it in GitHub Desktop.
Save yuanoook/9e363ec2620d0b0e33c41e047dd25580 to your computer and use it in GitHub Desktop.
nvm-windows auto switch node version by current working directory for git-bash
# Put this in your ~/.bashrc please
# To set node version by folder
# run: echo "v8.5.0" > .nvmrc
nvm_echo() {
command printf %s\\n "$*" 2>/dev/null
}
# Traverse up in directory tree to find containing folder
nvm_find_up() {
local path_
path_="${PWD}"
while [ "${path_}" != "" ] && [ ! -f "${path_}/${1-}" ]; do
path_=${path_%/*}
done
nvm_echo "${path_}"
}
nvm_find_nvmrc() {
local dir
dir="$(nvm_find_up '.nvmrc')"
if [ -e "${dir}/.nvmrc" ]; then
nvm_echo "${dir}/.nvmrc"
fi
}
load-nvmrc() {
local node_version="$(node -v)"
local nvmrc_path="$(nvm_find_nvmrc)"
if [ ! -z "$nvmrc_path" ]; then
local nvmrc_node_version=$(cat "${nvmrc_path}")
fi
local target_version="${nvmrc_node_version:-v14.15.4}"
if [ "$target_version" != "$node_version" ]; then
echo "Switch node from $node_version to $target_version"
nvm use $target_version
else
echo "node in use $target_version"
fi
}
# create a PROPMT_COMMAND equivalent to store chpwd functions
typeset -g CHPWD_COMMAND="load-nvmrc"
_chpwd_hook() {
shopt -s nullglob
local f
# run commands in CHPWD_COMMAND variable on dir change
if [[ "$PREVPWD" != "$PWD" ]]; then
local IFS=$';'
for f in $CHPWD_COMMAND; do
"$f"
done
unset IFS
fi
# refresh last working dir record
export PREVPWD="$PWD"
}
# add `;` after _chpwd_hook if PROMPT_COMMAND is not empty
PROMPT_COMMAND="_chpwd_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment