Black Pre-Commit Hook In Git

Updated: 1 minute read

Background/Problem

I’m a big fan of coding standards. I like when code within a project or even across projects is always formatted the same way. Unfortunately that is something that is pretty difficult to archive manually (at least for me). Therefore, I was looking for a code formatter (for python) and came across black [1] – “The Uncompromising Code Formatter”. I decided to use it.

In order to keep myself from commit code to a git repo that is not formatted with black, I wanted to have a pre-commit hook, that checks if my code is correctly formatted. Since hooks are not pushed to remote repos, I needed another way to set it up, whenever I clone one of my repos.

Solution

First of all, I had to install black on my system. At the moment I run an Arch Linux machine. On that, installing black was as easy as running:

sudo pacman -S python-black

Since the necessary pre-commit hook script for git is rather short, I decided to let make create the hook. This was pretty easy to archive. I just wrote two short make targets that (from now on) I will place in a Makefile in all my python projects. This is what it looks like:

hooks: .git/hooks/pre-commit

.git/hooks/pre-commit:
	echo -e "#/bin/sh\n" > $@
	echo "black --check ." >> $@
	chmod u+x $@

The second target actually generates the hook. The first is there for convenience and can be extended, in case I want to add more hooks. Now, whenever I clone one of my repos, all I have to do is run:

make hooks

Well, I hope I actually remember using this in the future.

Change Log

2022-09-23:

  • Changed wording slightly.



Take care,
Andreas


References

  1. Ł. Langa, “black.” [Online]. Available at: https://github.com/psf/black. [Accessed: 22-Apr-2022].

Updated:

Leave a comment