Git pre-commit hook

A very simple script to run tests before allowing a commit.

Git pre-commit hook
Photo by Yancy Min / Unsplash

A very simple script to run tests before allowing a commit.

There's a folder in the .git folder called hooks containing sample files for all the hooks you can use.

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a---        04/11/2024     17:29            478   applypatch-msg.sample
-a---        04/11/2024     17:29            896   commit-msg.sample
-a---        04/11/2024     17:29           4655   fsmonitor-watchman.sample
-a---        04/11/2024     17:29            189   post-update.sample
-a---        04/11/2024     17:29            424   pre-applypatch.sample
-a---        04/11/2024     17:29           1643   pre-commit.sample
-a---        04/11/2024     17:29            416   pre-merge-commit.sample
-a---        04/11/2024     17:29           1348   pre-push.sample
-a---        04/11/2024     17:29           4898   pre-rebase.sample
-a---        04/11/2024     17:29            544   pre-receive.sample
-a---        04/11/2024     17:29           1492   prepare-commit-msg.sample
-a---        04/11/2024     17:29           3635   update.sample

We're going to use a pre-commit hook to run the tests before allow the commit.

Create a new pre-commit file and put the following in it..

#!/bin/sh
exec dotnet test

if [ $? -ne 0 ]; then
echo "Tests must pass before commit!"
exit 1
fi

Now when you commit anything the tests will run and stop the commit if anything fails.