Get notified when lock files change

You pull the latest changes and your local project breaks 😥. After an hour of debugging, you find out that the lock file has changed. So the solution is easy: install the latest dependencies 😩. In this article, I will show you how to get notified when lock files change.

Credits to Sindre Sorhus for the original script.

For this notification we are going to use Git Hooks. Git Hooks are scripts that run automatically when certain actions occur in Git. You can use them to automate tasks, like checking code quality, linting, or installing dependencies.

In this case we are going to use the post-merge hook. This hook runs after a successful git pull command. We are going to use this hook to check if lock files have changed. If one has, a notification will be shown.

Setup the hook

Go to the root of your project and create a file called post-merge in .git/hooks. This file should be executable. You can do this by running chmod +x post-merge. Now open the file and add the following lines:

#!/bin/sh
# file name: post-merge

# Create a variable containing the list of changed files
changed_files=$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)

# This function checks if a file is in the list of changed files and shows the notification
check_run() {
    if echo "$changed_files" | grep --quiet "$1";
    then
        echo ""
        echo " 👉  $1 changed! You may want to $2!"
    fi
}

# Check for a changed `yarn.lock` file and give a suggestion to run `yarn install`
check_run yarn.lock "run yarn install"
# check_run a-lock.file "usage a command"

Now when you pull the latest changes, you will get a notification when Yarns lock file has changed.

But there are much more lock files that can change. You can add them to the script by adding a new check_run line. For example:

check_run composer.lock "run composer install"
check_run Gemfile.lock "run bundle install"
check_run package-lock.lock "run npm install"
check_run pnpm-lock.yaml "run pnpm install"
check_run yarn.lock "run yarn install"

I even use it for projects with dotenv files. When the .env.example file changes, I get a notification to update my .env file:

check_run .env.example "update your .env file"

Automate the setup for new projects

You can automate the setup for new projects by adding the hook to your Git template. This is a directory that is used when you run git init.

Set the folder with your preferred hooks globally with git config --global init.templateDire <path>. I use /User/your-name/git-templates as <path>.

Add the previously created post-merge file to /User/your-name/git-templates/hooks/. Now every time you run git init in a new project, the hook will be added to the .git/hooks directory.