Code Format Pre Commit Workflow
Set up a pre-commit hook that automatically formats code before each commit to maintain consistent style across the team.
Objective
Enforce consistent code formatting automatically before any commit is created.
Environment
- A project with a code formatter installed
- Git repository with hooks directory
- Team agreement on formatting rules
Steps
1. Install hook
Create a .git/hooks/pre-commit script that runs the formatter on staged files.
Expected state: A pre-commit hook exists and is executable.
2. Test the hook
Make a formatting violation, stage the file, and attempt to commit.
Expected state: The commit is blocked or the file is auto-formatted.
3. Verify formatting
Check that staged files are formatted correctly after the hook runs.
Expected state: All staged files conform to the formatting rules.
Decision points
Should the hook auto-format or block?
- Auto-format and commit
- Block and ask developer to fix
Auto-format for simple cases; block for complex changes that need manual review.
Expected outcome
All commits automatically have formatted code, preventing style inconsistencies from entering the repository.
Verification
Make a commit with unformatted code and confirm the hook reformats it or blocks the commit.
Cleanup
Remove the pre-commit hook if needed with rm .git/hooks/pre-commit.
Automation ensures consistency
Automatic formatting hooks ensure consistency without relying on every developer to remember.
#!/bin/sh
prettier --write $(git diff --cached --name-only --diff-filter=ACM | grep "\.js$")
Implementation Notes
-
Install hook — Create a .git/hooks/pre-commit script that runs the formatter on staged files. Expected state: A pre-commit hook exists and is executable.
-
Test the hook — Make a formatting violation, stage the file, and attempt to commit. Expected state: The commit is blocked or the file is auto-formatted.
-
Verify formatting — Check that staged files are formatted correctly after the hook runs. Expected state: All staged files conform to the formatting rules.
Common Pitfalls
- Should the hook auto-format or block? Options: Auto-format and commit / Block and ask developer to fix. Recommendation: Auto-format for simple cases; block for complex changes that need manual review.