Last active
August 17, 2017 14:06
-
-
Save usefulthink/a7df81859a924a33516d2c7e55632fca to your computer and use it in GitHub Desktop.
automatically add current node-binary path to $PATH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LAST_PWD="" | |
LAST_NPM_BIN="" | |
# find the npm binary path for a given directory ($1). | |
# Mostly equivalent to calling `npm bin` (except it doesn't report | |
# non-existing directories), but around 40x faster. | |
function fastNpmBin() { | |
local dir="${1}" | |
local candidate="" | |
while [ "${dir}" != "/" ] ; do | |
candidate="${dir}/node_modules/.bin" | |
if [ -d "${candidate}" ] ; then | |
echo -n "${candidate}" | |
return 0 | |
fi | |
dir=`dirname "${dir}"` | |
done | |
return 1 | |
} | |
function updatePath() { | |
# dont do anything if we did stay in the same directory | |
if [ "$(pwd)" == "${LAST_PWD}" ] ; then return; fi | |
# store pwd to prevent rechecking | |
LAST_PWD="$(pwd)" | |
# get npm bin | |
local npmBin="$(fastNpmBin ${LAST_PWD})" | |
# check if npmBin changed since the last path-update | |
if [ "${npmBin}" != "${LAST_NPM_BIN}" ] ; then | |
# purge all entries for commands from node_modules/.bin from the | |
# path-lookup cache | |
hash -l | grep node_modules/.bin | while read x x x x name ; do | |
hash -d "${name}" | |
done | |
LAST_NPM_BIN="${npmBin}" | |
# remove any previous PATH-entries containing `node_modules/.bin` and | |
# prepend the new bin-dir | |
PATH="${npmBin}$( | |
IFS=':' | |
for d in $PATH ; do | |
[[ "${d/node_modules\/.bin/}" != "${d}" ]] || printf ":$d" | |
done | |
)" | |
# remove a trailing colon (if $npmBin is empty) | |
export PATH=${PATH#:} | |
fi | |
} | |
export PROMPT_COMMAND=updatePath |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment