As a JS developer, while working on projects we frequently need to run npm install
command on git pull or checkout to a different git branch where package.json is modified.
In majority of the cases, the dependencies won’t cause any issues, but if there any breaking change introduced by the dependency packages then we need to reinstall. We somehow forget to run the command. (I mostly forget it at least 😛).
How do we automate this?
Well, it's quite simple. Hooks!!!
Yes. Git hooks.
We can make use of git hooks to trigger npm install
command if a package.json file has been modified.
Script to run inside git hooks.
#/usr/bin/env bash
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
echo "$changed_files" | grep --quiet "$1" && eval "$2"
}
check_run package.json "npm install"
Here we check whether package.json file is present in the diff between the current HEAD and original HEAD. To learn more about these refer to this Q&A
In order to do the magic,
- Save the script with git hook name (eg.
post-merge
) - Make it executable by running
chmod +x {HOOK_NAME}
- Finally put the file into git hook by
mv {HOOK_NAME} .git/hooks/
Git Hooks
Name | Invoked By |
---|---|
post-merge | git pull / git merge |
post-checkout | git checkout / git clone |
References:
Top comments (0)