Yuri Vishnevsky

December 2024
Formatting Code with a Git Hook
TIL

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.


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



if git diff --cached --quiet; then
    echo "Error: After formatting, there are no longer any files are staged for commit" >&2
    exit 1
fi

Back to top