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:

  1. git pull
  2. verify if package.json was modified
  3. 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
{
"scripts": {
"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:

{
"scripts": {
"...": "...",
"postmerge": "do_something_here",
"...": "..."
}
}

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):

#/usr/bin/env bash
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
if echo "$changed_files" | grep -q "$1"; then
echo "Found diff in $1"
eval "$2"
else
echo "Not found any diff in $1"
fi
}
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:

{
"scripts": {
...
"postmerge": "sh hooks/postmerge"
}
}

That's it. Hope it helps you guys somehow. 😉