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.
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:
git commit
command and it runs before git commit
git push
. git commit
command. The behavior in post-commit does not affect the result of the commit because it is activated after a successful commit. 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.
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.
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).
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.
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:
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!
Subscribe to receive new article notifications
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.
Comments (1)