Skip to content

Commit

Permalink
Add automatic nvm use
Browse files Browse the repository at this point in the history
  • Loading branch information
kkrull committed Aug 12, 2019
1 parent 98e15fe commit a9f0c8a
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions bash_profile
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ then
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
[ -s "$HOME/git/dotfiles/bash_profile.d/nvm.sh" ] && \. "$HOME/git/dotfiles/bash_profile.d/nvm.sh"
fi

#RVM
Expand Down
55 changes: 55 additions & 0 deletions bash_profile.d/nvm.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@


# https://github.com/nvm-sh/nvm#bash

find-up () {
path=$(pwd)
while [[ "$path" != "" && ! -e "$path/$1" ]]; do
path=${path%/*}
done
echo "$path"
}

cdnvm(){
cd "$@";
nvm_path=$(find-up .nvmrc | tr -d '[:space:]')

# If there are no .nvmrc file, use the default nvm version
if [[ ! $nvm_path = *[^[:space:]]* ]]; then

declare default_version;
default_version=$(nvm version default);

# If there is no default version, set it to `node`
# This will use the latest version on your machine
if [[ $default_version == "N/A" ]]; then
nvm alias default node;
default_version=$(nvm version default);
fi

# If the current version is not the default version, set it to use the default version
if [[ $(nvm current) != "$default_version" ]]; then
nvm use default;
fi

elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then
declare nvm_version
nvm_version=$(<"$nvm_path"/.nvmrc)

declare locally_resolved_nvm_version
# `nvm ls` will check all locally-available versions
# If there are multiple matching versions, take the latest one
# Remove the `->` and `*` characters and spaces
# `locally_resolved_nvm_version` will be `N/A` if no local versions are found
locally_resolved_nvm_version=$(nvm ls --no-colors $(<"./.nvmrc") | tail -1 | tr -d '\->*' | tr -d '[:space:]')

# If it is not already installed, install it
# `nvm install` will implicitly use the newly-installed version
if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then
nvm install "$nvm_version";
elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then
nvm use "$nvm_version";
fi
fi
}
alias cd='cdnvm'

0 comments on commit a9f0c8a

Please sign in to comment.