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
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click 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