Skip to content

Instantly share code, notes, and snippets.

@mattrasband
Last active November 25, 2023 12:51
Show Gist options
  • Save mattrasband/fa8c07a1c63d685f4796c439089ef3ab to your computer and use it in GitHub Desktop.
Save mattrasband/fa8c07a1c63d685f4796c439089ef3ab to your computer and use it in GitHub Desktop.
pre-commit hook to run `black` for python auto-formatting
#!/bin/sh
# make sure black is available
which black > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Unable to run precommit hook, black is not available"
exit 1
fi
# find any staged py files
files="$(git diff --name-only --cached | grep '.*\.py$' | paste -sd ' ' -)"
if [ "$files" == "" ]; then
echo "No files to reformat, skipping"
exit 0
fi
# run the autoformatting, your settings from pyproject.toml will be picked up.
black $files
# re-stage
git add $files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment