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
  • After many years, I finally had the 'courage' to do this: Rewrite the series of articles on 'Node.js Architecture'.

    There is a truth that when re-reading my past articles, the more I read, the more I want to correct them, which means that my writing skills have improved significantly. There are some articles that I had to delete and rewrite from scratch because... I can't understand why I could write like that back then!?

    By the way, I apologize to those of you who had to read my unrefined articles 🙏. And now is the time to make amends 😇

    Node.js Architecture - Introduction to Node.js

    » Read more
  • Maybe soon we won't need new Date() in JavaScript/Node.js anymore. Because it’s on the verge of being deprecated 🫣

    Temporal

    » Read more
  • NotebookLM has officially added Vietnamese language support for audio output today, everyone. It's absolutely fantastic.

    NotebookLM Audio Overviews are now available in over 50 languages

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

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

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