Tools needed

Hook Purpose

In this example, we'll create a pre-commit hook. This hook validates the git config's global user email and checks whether a gpg key exists. The hook is useful so that the commits contain the correct committer email address and also to ensure the commits are signed.

Creating the git hook

Step 1

First navigate to the hooks directory for the target repo. Open a Visual Studio Code window and navigate to repo .git hooks. From here, add a new file to the .git/hooks directory called pre-commit.

Note 📝 - To make the .git folder visible in Visual Studio Code you will need to remove **/.git from files.exclude in the Visual Studio Code settings.

Step 2

Now that we have our pre-commit file, we need to make it executable. To do this we will need the command line.

Open a terminal window by using option + T in GitKraken. Once the terminal windows is open, change directory to .git/hooks.

Then use the command chmod +x pre-commit to make the pre-commit file executable.

Note 📝 - If you do not have your terminal setup in GitKraken, please review the Start Here Tips for setup details.

Step 3

Now we create our scrip using bash. In order for the script to run, we first need to specify our shell. Do this by using #!/bin/bash at the beginning of your script for bash or #!/bin/sh if using the sh shell. Any script that exits with anything other than exit code 0 is considered a fail.

This pre-commit hook watches for incorrect commit authors and unsigned commits using the script below.

Now to explore the conditions we have set for our script. First we validate that the working directory contains demo and that the global git config user.email matches with our workEmail. If it fails we will see: