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
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » 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