Intro
A framework for managing and maintaining multi-language pre-commit hooks.
- pre-commit
Intro doesn’t say much. In plain english, It runs hooks(a piece of code) against files to be committed, before code is committed to a branch, sounds like an over-simplification? well it is.
How is it useful?
Well here is a small list of its uses
- Enforce rules like not allowing code to be committed with debuggers
- Run code through formatter
- Run code through linter
- Trigger test suite
- Prevent commit to specific branch or branches
- Sort and remove un-used imports
- scan known Vulnerability
Prerequisites
- Python
Getting started
Installation
pre-commit comes as a python package. use pip to install pre-commit. In case of permission issues, add --user
flag.If pip is in the path, python -m
can be removed. pre-commit will be installed in $HOME/.local/bin/
when user flag utilized, make sure it is in the path.
python -m pip install pre-commit
Configure
Navigate to any existing project root directory. This is usually the place where .git folder is located.Instead of starting with a blank file, let’s get the boiler-plate from pre-commit itself.
|
|
|
|
sample output may be different, depending on the version. There is a huge list of hooks available , that’s not it you can roll your own. It is also language agnostic, see supported languages . Adding an existing hook is a simple copy-paste from hooks page.
After adding required hooks, its time to install these hooks. install with below command.
|
|
Use auto update to keep pre-commit up to date. Auto update checks rev, compares with github repo and updates if needed.
|
|
Conclustion
pre-commit is very powerful, and it had made code review process slightly easier for me. No more discussions on what code style to use. However, users can bypass pre-commit check by adding --no-verify
flag in git commit
command.