Pre-Commit & Git Hooks: Automate High Code Quality

How to improve your code quality with pre-commit and git hooks

Photo by Pankaj Patel on Unsplash

What is Pre-Commit?

Pre-commit is a Python package that makes creating pre-commit hooks much easier. A hook is something native to git, which are scripts that run before specific git commands are executed.

You can find hooks in your repo’s .git/hooks directory, which is automatically populated by git. If you look inside this directory, you will find files that look like this:

applypatch-msg.sample     pre-commit.sample         prepare-commit-msg.sample
commit-msg.sample pre-merge-commit.sample push-to-checkout.sample
fsmonitor-watchman.sample pre-push.sample update.sample
post-update.sample pre-rebase.sample
pre-applypatch.sample pre-receive.sample

The .sample extension prevents these hooks from being executed. To enable the hooks, remove the .sample extension and edit the file.

However, this is tedious and not very user-friendly, and it is tough to manage with version control. This is where pre-commit comes in. It creates a hook for the commit command to automatically detect any issues in the code and makes creating the script seamless.