What are Githooks? Learn how to use Githooks to prevent careless commits

What are Githooks? Learn how to use Githooks to prevent careless commits

Daily short news for you
  • There is a rather interesting study that I came across: "Users never bother to read things they don't want to." (That's a bold statement, but it's more true than not. 😅)

    Don't believe it? I bet you've encountered situations where you've clicked on a button repeatedly and it doesn't respond, but in reality, it has displayed an error message somewhere. Or you've filled out everything and then when you hit the submit button, it doesn't go through. Frustrated, you scroll up or down to read and find out... oh, it turns out there's an extra step or two you need to take, right?

    It’s not far from the blog here. I thought that anyone who cares about the blog would click on the "Allow notifications" button just below the post. But the truth is, no one bothers to click it. Is it because they don't want to receive notifications? Probably not! I think it's because they just didn’t read that line.

    The evidence is that only when a notification pops up and takes up half the screen, or suddenly appears to grab attention, do they actually read it—and of course, it attracts a few more subscribers—something that was never achieved before.

    » Read more
  • A short article about the concepts of Functors, Applicatives, and Monads in functional programming that every time I read, I understand a little more 😅

    Functors, Applicatives, And Monads In Pictures

    » Read more
  • Rust is the time of its coming... It's "redefining" a whole bunch of things. Even the coreutils package containing basic Linux commands has been rewritten by it, and it runs on multiple platforms too 🫣

    uutils.github.io

    » Read more

Problem

You might not know that Git has a concept called hooks, and they are called Githooks. Githooks are triggered by events, allowing you to insert additional tasks to be executed before or after performing that action.

What are Githooks?

Githooks are scripts that Git executes before or after events such as commit, push, and receive. Githooks are a built-in feature in Git, so you don't need to download anything extra.
Git provides many hooks, some common hooks include:

  • pre-commit: Called when using the git commit command and it runs before git commit
  • pre-receive: This is a hook that is performed on the server side and is called before git push.
  • post-commit: Called after using the git commit command. The behavior in post-commit does not affect the result of the commit because it is activated after a successful commit.
  • post-receive: This is a hook that is performed on the server side and is called after using the git push. The behavior in post-receive does not affect the result of the push because it is activated after a successful push.

To see a complete list and description of hooks, refer to the git documentation page.

Each Git repository has a directory .git/hooks that contains corresponding files for each hook you want to use. You can modify the contents of these files, and Git will execute them when those events occur.

Git hooks can be divided into two types: client-side and server-side hooks. Client-side hooks are executed before or after actions in the local repository, while server-side hooks are executed before or after being pushed to the server (remote repository).

Server-side hooks are used to enforce stronger policies that we want because they are checked remotely, while client-side hooks can be easily bypassed by many tricks. To know which hooks run on the client or server side, you can refer to the details in the git documentation.

How to use Githooks

When using git init to initialize a git repository for a project, Git also creates example files of the hooks in the .git/hooks directory, which you can take a look at. In essence, these are bash scripts.

.git/hooks directory

For example, this is the content of the pre-commit.sample file:

#!/bin/sh
#
# An example hook script to verify what is about to be committed.  
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.  
#
# To enable this hook, rename this file to "pre-commit".  

if git rev-parse --verify HEAD >/dev/null 2>&1
then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=$(git hash-object -t tree /dev/null)
fi

# If you want to allow non-ASCII filenames set this variable to true.  
allownonascii=$(git config --type=bool hooks.allownonascii)

# Redirect output to stderr.  
exec 1>&2

# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.  
if [ "$allownonascii" != "true" ] &&
  # Note that the use of brackets around a tr range is ok here, (it's
  # even required, for portability to Solaris 10's /usr/bin/tr), since
  # the square bracket bytes happen to fall in the designated range.  
  test $(git diff --cached --name-only --diff-filter=A -z $against |
    LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
  cat <<\EOF
Error: Attempt to add a non-ASCII file name.  

This can cause problems if you want to work with people on other platforms.  

To be portable it is advisable to rename the file.  

If you know what you are doing you can disable this check using:  

  git config hooks.allownonascii true
EOF
  exit 1
fi

# If there are whitespace errors, print the offending file names and fail.  
exec git diff-index --check --cached $against --

For the pre-commit hook, if you return an exit status other than 0, the commit will be immediately aborted and return an error. To configure which hook to use, simply rename the file to the hook name in the .git/hooks directory (removing the .sample extension).

Using pre-commit to prevent careless commits

Careless commits can be commits that haven't gone through ESLint to check syntax or haven't run unit tests beforehand. Depending on your case, there may be times when you want to prevent commits that violate a predefined rule. In such cases, applying the pre-commit hook is a perfect solution.

For example, suppose I want to run unit tests every time I commit. If the tests are successful, then proceed with the commit; otherwise, display an error. Here's how:

Create the .git/hooks/pre-commit file with the following content:

#!/bin/sh
git stash -q --keep-index
npm run test
status=$?  
git stash pop -q
exit $status

Before running npm run test, I stash the files beforehand because those files are not included in the commit, and then unstash them and return an exit status with the status of the npm run test command. The $? syntax in bash retrieves the exit code of the last command. In other cases, you can modify npm run test to any command you want to check before committing.

Summary

The above is just a small example of using Githooks, and there are many other hooks besides pre-commit. By combining different hooks, you can solve more problems.

References:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (1)

Leave a comment...
Avatar
Jess Vanes2 years ago
Cũng có thư viện giúp bạn làm việc dễ dàng hơn với hook của git nữa
Reply