Skip to content

Instantly share code, notes, and snippets.

@IharKrasnik
Last active July 20, 2017 13:34
Show Gist options
  • Save IharKrasnik/abb6b3387504d17859c946193f5341bd to your computer and use it in GitHub Desktop.
Save IharKrasnik/abb6b3387504d17859c946193f5341bd to your computer and use it in GitHub Desktop.
Bash script to be used as post-merge git hook to install NPM modules recursively only for changed package.json files (and package-lock.json files for npm > v5)
#!/bin/bash
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
PROJECT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) # script assumes that you placed it in the root of your project dir
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)" # find all files changed by commit first
printf "${PURPLE}\nChecking updated NPM modules.. ${NC} \n"
PROCESSED_DIRS=()
for package in $(echo "$changed_files" | grep "package.json") # iterate over changed package.json files
do
printf "\n${CYAN}Installing updated NPM modules for $package${NC}\n\n"
package_path="$PROJECT_DIR/$package"
package_dir=$(dirname "${package_path}")
printf "npm install --prefix $package_dir\n\n"
npm install --prefix $package_dir # install modules for changed package.json file
PROCESSED_DIRS+=($package_dir)
done
for package in $(echo "$changed_files" | grep "package-lock.json")
do
package_path="$PROJECT_DIR/$package"
package_dir=$(dirname "${package_path}")
if [[ " ${PROCESSED_DIRS[@]} " =~ " ${package_dir} " ]]; then
printf "\Contains $package_dir"
else
printf "\nDoes not contain $package_dir"
printf "\n${CYAN}Installing updated NPM modules for $package${NC}\n\n"
printf "npm install --prefix $package_dir\n\n"
npm install --prefix $package_dir
fi
done
echo "All NPM modules are up-to-date"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment