⚙️ Run Scripts Automatically on Git Events
Run tests before commit? Lint before push? Format code? Git hooks automate anything. No more forgotten steps.
📝 Available Hooks
.git/hooks/ (create executable files) Client-side: - pre-commit # Run tests before commit (cancel if fails) - prepare-commit-msg # Edit commit message before editor opens - commit-msg # Validate commit message - post-commit # Notify after commit - pre-push # Run before push (CI checks) - pre-rebase # Cancel rebase if conditions not met Server-side: - pre-receive # Before accepting push - update # Per-branch check - post-receive # After push (deploy, notify)
🎯 pre-commit Example
#!/bin/bash # .git/hooks/pre-commit # Run linter npm run lint if [ $? -ne 0 ]; then echo "❌ Linter failed. Fix errors before commit." exit 1 fi # Run tests (only staged files) npm test -- --findRelatedTests $(git diff --cached --name-only --diff-filter=ACM | grep '\.js$') if [ $? -ne 0 ]; then echo "❌ Tests failed. Fix before commit." exit 1 fi # Format code npm run format git add $(git diff --name-only) # Stage formatted files echo "✅ pre-commit checks passed" exit 0
✅ Tools for Hook Management
- Husky (Node.js): Manage hooks in package.json
- pre-commit (Python): Framework for hooks
- lefthook (Cross-language): Fast, polyglot hooks
- overcommit (Ruby): Extensive hook library
“Team kept committing failing tests. Added pre-commit hook → tests run automatically. Broken commits dropped 90%. Git hooks are non-negotiable for teams.”
