Automatically updating npm dependencies when doing git pull
Me and my team are working in a new project and as expected we are going through a lot of experiments with some packages.
When installing some new package, we always (tried to 😅) tell in our Slack Channel to run npm install or npm prune if some package was installed or removed. But as it wasn't an automatically process, sometimes it has failed.
To avoid these situations I decided to turn the manual process into an automatically process, and it's pipeline would be sort of:
- git pull
- verify if package.json was modified
- in case modified, we run npm install && npm prune
To do that I used a package called husky. It allows us to put git hooks actions in our package tasks, like precommits stuff. It helps to mantain the the code quality, because we can run eslint validator and unit tests before we push new code to the repository. As it's in documentation:
// Edit package.json
"precommit": "npm test",
"prepush": "npm test",
So if we want to verify on every git pull, we need to add postmerge task in our package.json (https://github.com/typicode/husky/blob/master/HOOKS.md). Then we add this:
This do_something_here should actually do something, so we are going to create an shellscript (hooks/postmerge for example) to achieve our goal (I’ve adapted from here the shellscript):
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
if echo "$changed_files" | grep -q "$1"; then
echo "Found diff in $1"
echo "Not found any diff in $1"
check_run package.json "npm install && npm prune"
Basically it'll check the new stuff that is coming from repository and verify if package.json is one of them. In case it is, just call our commands.
Now we just call it from our postmerge task:
"postmerge": "sh hooks/postmerge"
That's it. Hope it helps you guys somehow. 😉