From 708f3a51bc872efe9a0999d59b90f505be234a09 Mon Sep 17 00:00:00 2001 From: Hlynur Sigurthorsson Date: Fri, 26 May 2017 20:51:12 +0000 Subject: [PATCH] Adding plugin node-modules-path If chpwd is changed to a path where any folder within that subpath contains a node_modules folder, then that path + .bin is added to the PATH env variable. The reason for writing this plugin is that I often open up atom directly from the shell in a directory of interest. If I have flow installed locally then I have to add the node_modules folder in that path to PATH before I open up Atom. --- .../node-modules-path.plugin.zsh | 39 +++++++++++++++++++ plugins/node-modules-path/path_check.py | 28 +++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 plugins/node-modules-path/node-modules-path.plugin.zsh create mode 100644 plugins/node-modules-path/path_check.py diff --git a/plugins/node-modules-path/node-modules-path.plugin.zsh b/plugins/node-modules-path/node-modules-path.plugin.zsh new file mode 100644 index 00000000..1c9a5f7c --- /dev/null +++ b/plugins/node-modules-path/node-modules-path.plugin.zsh @@ -0,0 +1,39 @@ +SCRIPT_PATH=${0:a:h} +NODE_MODULES_PATH="" + +# Removes applied path from PATH. +function remove_from_path { + PATH=${PATH/":$1"/} + PATH=${PATH/"$1:"/} +} + +# Checks if given string is found in PATH. +function is_on_path { + if [[ "$1" ]]; then + echo $PATH | grep "$1" >/dev/null + else + return 1 + fi +} + +chpwd_handler() { + nearest_found_nm=`/usr/bin/env python $SCRIPT_PATH/path_check.py $PWD` + + if [[ "$nearest_found_nm" ]] && is_on_path "$nearest_found_nm/node_modules/.bin"; then + return + fi + + if [[ "$NODE_MODULES_PATH" ]]; then + remove_from_path "$NODE_MODULES_PATH/node_modules/.bin" + export NODE_MODULES_PATH="" + fi + + if [[ "$nearest_found_nm" ]]; then + echo "\033[1;34mFound node_modules in $nearest_found_nm, adding to path\033[0m" + PATH="$PATH:$nearest_found_nm/node_modules/.bin" + NODE_MODULES_PATH="$nearest_found_nm" + fi +} + +chpwd_functions=(${chpwd_functions[@]} "chpwd_handler") +chpwd_handler diff --git a/plugins/node-modules-path/path_check.py b/plugins/node-modules-path/path_check.py new file mode 100644 index 00000000..e2394d3a --- /dev/null +++ b/plugins/node-modules-path/path_check.py @@ -0,0 +1,28 @@ +import os +import sys + +def get_subpaths(path): + paths = [] + dirs = path.split('/')[1:] + + for i in range(len(dirs), 0, -1): + p = os.path.join(*dirs[0:i]) + yield p + +def has_modules_folder(path): + check_path = os.path.join('/', path, 'node_modules') + return os.path.exists(check_path) and os.path.isdir(check_path) + +def get_closes_path_dir(path): + for p in get_subpaths(path): + if has_modules_folder(p): + return '/' + p + return '' + +if __name__ == '__main__': + if len(sys.argv) == 1: + sys.exit(1) + else: + path = sys.argv[1] + print get_closes_path_dir(path) + sys.exit(0)