Tried introducing Local CI Testing with Git Hooks in a startup.

Tried introducing Local CI Testing with Git Hooks in a startup.

I attempted to implement Local CI Testing with Git Hooks in a startup, and now I'd like to share how I accomplished that with actual code.

What was our goal?

  • Automate tests on local commits as events.

  • Reject Git commits if the tests fail.

  • Share the Git Hooks script with the team.

Why is it necessary?

Running tests as events triggered by commits can enhance the reliability of the code. Furthermore, automating these tests can help prevent oversights and improve efficiency.

Let's get to the main point.

What is Git Hooks?

Like many other Version Control Systems, Git has a way to fire off custom scripts when certain important actions occur. There are two groups of these hooks: client-side and server-side. Client-side hooks are triggered by operations such as committing and merging, while server-side hooks run on network operations such as receiving pushed commits. You can use these hooks for all sorts of reasons.

Customizing Git - Git Hooks

Implementation

There are three steps to complete this process

Create a .githooks directory.

Begin by creating a .githooks directory in the root repository
$ mkdir .githooks

Write a Hooks script

As the next step, let's create a Hooks script to be executed as an event.

make test-run

# if test fail, reject the commit.
if [ $? -ne 0 ]; then
    echo "Tests failed. Commit aborted."
    exit 1
fi

Place the Hooks script under the .githooks directory. This will make the code appear as.githooks/pre-commit .

Grant execution rights

Grant execution rights to the Hooks script file with the following code.

$ chmod a+x .githooks/*

Change Git Hooks references

By default, Git is set to refer to .git/hooks. You should modify this reference to point to the Hooks Script located under .githooks/ which is shared by the team.

Execute the following command to change the reference:

$ git config --local core.hooksPath .githooks

Every team member should adjust their reference settings. This way, the team can share the Git Hooks script more easily and also improve its maintainability.