nvm.plugin.zsh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # See https://github.com/nvm-sh/nvm#installation-and-update
  2. if [[ -z "$NVM_DIR" ]]; then
  3. if [[ -d "$HOME/.nvm" ]]; then
  4. export NVM_DIR="$HOME/.nvm"
  5. elif [[ -d "${XDG_CONFIG_HOME:-$HOME/.config}/nvm" ]]; then
  6. export NVM_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/nvm"
  7. fi
  8. fi
  9. # Don't try to load nvm if command already available
  10. # Note: nvm is a function so we need to use `which`
  11. ! which nvm &>/dev/null || return
  12. if [[ -f "$NVM_DIR/nvm.sh" ]]; then
  13. # Load nvm if it exists in $NVM_DIR
  14. source "$NVM_DIR/nvm.sh" ${NVM_LAZY+"--no-use"}
  15. elif (( $+commands[brew] )); then
  16. # Otherwise try to load nvm installed via Homebrew
  17. # User can set this if they have an unusual Homebrew setup
  18. NVM_HOMEBREW="${NVM_HOMEBREW:-${HOMEBREW_PREFIX:-$(brew --prefix)}/opt/nvm}"
  19. # Load nvm from Homebrew location if it exists
  20. if [[ -f "$NVM_HOMEBREW/nvm.sh" ]]; then
  21. source "$NVM_HOMEBREW/nvm.sh" ${NVM_LAZY+"--no-use"}
  22. else
  23. return
  24. fi
  25. else
  26. return
  27. fi
  28. # Call nvm when first using node, npm or yarn
  29. if (( $+NVM_LAZY )); then
  30. function node npm yarn $NVM_LAZY_CMD {
  31. unfunction node npm yarn $NVM_LAZY_CMD
  32. nvm use default
  33. command "$0" "$@"
  34. }
  35. fi
  36. # Autoload nvm when finding a .nvmrc file in the current directory
  37. # Adapted from: https://github.com/nvm-sh/nvm#zsh
  38. if (( $+NVM_AUTOLOAD )); then
  39. load-nvmrc() {
  40. local node_version="$(nvm version)"
  41. local nvmrc_path="$(nvm_find_nvmrc)"
  42. if [[ -n "$nvmrc_path" ]]; then
  43. local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
  44. if [[ "$nvmrc_node_version" = "N/A" ]]; then
  45. nvm install
  46. elif [[ "$nvmrc_node_version" != "$node_version" ]]; then
  47. nvm use
  48. fi
  49. elif [[ "$node_version" != "$(nvm version default)" ]]; then
  50. echo "Reverting to nvm default version"
  51. nvm use default
  52. fi
  53. }
  54. autoload -U add-zsh-hook
  55. add-zsh-hook chpwd load-nvmrc
  56. load-nvmrc
  57. fi
  58. # Load nvm bash completion
  59. for nvm_completion in "$NVM_DIR/bash_completion" "$NVM_HOMEBREW/etc/bash_completion.d/nvm"; do
  60. if [[ -f "$nvm_completion" ]]; then
  61. # Load bashcompinit
  62. autoload -U +X bashcompinit && bashcompinit
  63. # Bypass compinit call in nvm bash completion script. See:
  64. # https://github.com/nvm-sh/nvm/blob/4436638/bash_completion#L86-L93
  65. ZSH_VERSION= source "$nvm_completion"
  66. break
  67. fi
  68. done
  69. unset NVM_HOMEBREW NVM_LAZY NVM_AUTOLOAD nvm_completion