I'd like to run black to format all the staged .py files on a commit. Unfortunately due to employer network VPN and restrictions I'm unable to use the pre-commit package because it times out when trying to load the repo.
So I decided to write my own pre-commit hook. Currently I have this
#!/bin/sh
# Check if this is the initial commit
if git rev-parse --verify HEAD >/dev/null 2>&1
then
echo "pre-commit: About to create a new commit..."
against=HEAD
else
echo "pre-commit: About to create the first commit..."
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Autoformat with black
echo "pre-commit: Autoformatting Python code with black"
black $(git diff-index --cached --name-only --diff-filter=d $against)
The first part I found from Atlassian. The second part needs a filter of some sort to only take the .py files from the column which is returned by diff-index. How to get only the .py files from the list?
Also: I'm quite new to git hooks. Is this a robust way for me and my colleagues to make sure all code is formatted with black?
git add
modified files at the end of the hook. – Aluminate