From e8e5f89098b964c8f26a49ef7e4866479b5c9faa Mon Sep 17 00:00:00 2001 From: Ian MacLeod Date: Mon, 4 Sep 2017 11:19:52 -0700 Subject: [PATCH] Introduce NVM_PREFER_LOCAL_BINS Prepends `$(npm bin)` on `$PATH` whenever cding into directories with `package.json` (or anywhere up the tree) --- README.md | 11 +++++++++++ zsh-nvm.plugin.zsh | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/README.md b/README.md index 3899b8a..88f71be 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,17 @@ export NVM_AUTO_USE=true antigen bundle lukechilds/zsh-nvm ``` +### Local bins + +If your projects include dependencies with binaries, this ensures that they take precedence on your `$PATH` over globally installed ones. + +For example, if you are using antigen, you would put the following in your `.zshrc`: + +```shell +export NVM_PREFER_LOCAL_BINS=true +antigen bundle lukechilds/zsh-nvm +``` + ## Installation ### Using [Antigen](https://github.com/zsh-users/antigen) diff --git a/zsh-nvm.plugin.zsh b/zsh-nvm.plugin.zsh index 83967b7..68ec0fd 100644 --- a/zsh-nvm.plugin.zsh +++ b/zsh-nvm.plugin.zsh @@ -195,6 +195,27 @@ _zsh_nvm_install_wrapper() { esac } +_zsh_nvm_add_local_bin_path() { + local nearest_package=$(nvm_find_up package.json) + # Skip if we're moving within a project (npm bin is slow). + # + # Also notice that we prepend a value in front of the variable so that it + # isn't expanded by %~ prompts. + [[ "z$nearest_package" == "$NVM_CURRENT_PACKAGE_PATH" ]] && return + NVM_CURRENT_PACKAGE_PATH=z$nearest_package + + # Ensure a clean slate; so that we are not prepending paths forever. + if [[ -n "$NVM_PATH_WITHOUT_LOCAL_BINS" ]]; then + PATH=$NVM_PATH_WITHOUT_LOCAL_BINS + unset NVM_PATH_WITHOUT_LOCAL_BINS + fi + + if [[ -n "$nearest_package" ]]; then + NVM_PATH_WITHOUT_LOCAL_BINS=$PATH + PATH=$(npm bin):$PATH + fi +} + # Don't init anything if this is true (debug/testing only) if [[ "$ZSH_NVM_NO_LOAD" != true ]]; then @@ -209,6 +230,9 @@ if [[ "$ZSH_NVM_NO_LOAD" != true ]]; then # Auto use nvm on chpwd [[ "$NVM_AUTO_USE" == true ]] && add-zsh-hook chpwd _zsh_nvm_auto_use && _zsh_nvm_auto_use + + # Ensure that local bins take precedence on $PATH. + [[ "$NVM_PREFER_LOCAL_BINS" == true ]] && add-zsh-hook chpwd _zsh_nvm_add_local_bin_path && _zsh_nvm_add_local_bin_path fi fi