Skip to content

Instantly share code, notes, and snippets.

@krry
Last active December 22, 2021 07:12
Show Gist options
  • Save krry/192f8ba639db3dd049c577ae6506f90d to your computer and use it in GitHub Desktop.
Save krry/192f8ba639db3dd049c577ae6506f90d to your computer and use it in GitHub Desktop.
Sets the node version automagically when changing dirs in fish shell with nvm when .nvmrc is present or in a parent dir
# use_nvmrc.fish
# TODO: save this in `$HOME/.config/fish/conf.d`
# `nvm use` whenever .nvmrc is present in $PWD when using fish shell
# when traveling deeper, use the parent .nvmrc unless otherwise set
# also go back to default nvm when leaving the nvmrc-specified zone
function set_nvm --on-event fish_prompt
# if the current directory hasn't changed, do nothing
string match -q $PWD $PREV_PWD; and return 1
# if the current directory is within the previous one where we found an nvmrc
# and there is no subsequent .nvmrc here, do nothing, we are in the same repo
string match -eq $PREV_PWD $PWD; and not test -e '.nvmrc'; and return 1
# if we clear those checks, keep track of where we are
set -g PREV_PWD $PWD
if test -e '.nvmrc'
# if we find .nvmrc, run nvm use
nvm use
# and remember that we used that node
set NVM_DIRTY true
else if not string match $NVM_DIRTY true
# if we have set nvm and have stepped out of that repo
# go back to default node, if not already on it
not string match -eq (nvm current) (nvm alias default); and nvm use default
# and clear the flag
set NVM_DIRTY
end
end
# inspired by the debate here: https://stackoverflow.com/questions/23556330/run-nvm-use-automatically-every-time-theres-a-nvmrc-file-on-the-directory/50378304#50378304
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment