Git hooks

am2701
3 min readApr 28, 2021
Commit process
Commit Process

What is a hook ?

In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a hook. — wikipedia

How can I use them ?

Git hooks is usable to add specific functions at specific state like, for example, linting. Like that, you could be sure your code meets your company’s requirements.

What is linting ?

lint, or a linter, is a static code analysis tool used to flag programming errors, bugs, stylistic errors, and suspicious constructs. The term originates from a Unix utility that examined C language source code. — wikipedia

What are the different hooks ?

hook process

Some hooks are used locally and some other are used on the server.

I will explain you local hooks.

You can force to omit it in typing:

git commit -m "your message" --no-verify

pre-commit

pre-commit is the first hook executed.

It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code.

It’s usually used to verify code style, check for trailing whitespace, or check for appropriate documentation on new methods.

prepare-commit

It lets you edit the default message before the commit author sees it.

This hook generally isn’t useful for normal commits; rather, it’s good for commits where the default message is auto-generated, such as templated commit messages, merge commits, squashed commits, and amended commits. You may use it in conjunction with a commit template to programmatically insert information.

commit-msg

Generally, this script is used for notification or something similar.

pre-rebase

pre-receive

Where can I find them ?

Global

If you want to use same actions for every projects, you could configure git to use some global hooks.

With the next command line, you will enable git templates:

git config --global init.templatedir '~/.gittemplates'

After that you have to make the directory,

mkdir -p ~/.gittemplates/hooks

And create your own hooks. For that, just copy hook samples in a repository. Each time you create a repository, hook samples are initialized.

cp <repository>/.git/hooks/*.sample ~/.gittemplates/hooks/

Samples files are not used by git but that give you some example to begin. To use one, just rename them in removing “.sample”.

Project

One project could have different interaction to do that global. To modify it, you just need to edit the hook file in:

.git/hooks/<hook_name>

--

--