December 2024 · TIL
Formatting Code with a Git Hook
Here’s a git pre-commit hook to auto-format code on commit. It’s useful if you’re working with code whose formatting guidelines differ from the ones you’ve configured in your code editor.
#!/bin/bash
# .git/hooks/pre-commit
# Store list of staged files that match your target pattern.
# The `git diff` command returns a list of staged files.
files=$(git diff --cached --name-only | grep -E '\.(js|ts|svelte)$')
if [ -n "$files" ]; then
pnpm format
# Add all of the previously staged files back to the staging area
# to check in the formatted files.
git add $files
fi
# Exit with an error when there are no longer any staged changes,
# since otherwise git will create an empty commit.
if git diff --cached --quiet; then
echo "Error: After formatting, there are no longer any files are staged for commit" >&2
exit 1
fi