🪝 Git Hooks Guide¶
🎯 Hook Types¶
╔═══════════════════════════════════════════════════════════╗ ║ Hook │ When │ Purpose ║ ╠═══════════════╪═══════════════╪══════════════════════════╣ ║ pre-commit │ Before commit │ Lint, format check ║ ║ commit-msg │ After message │ Validate message format ║ ║ pre-push │ Before push │ Run local tests ║ ║ post-receive │ After push │ Trigger CI webhook ║ ╚═══════════════════════════════════════════════════════════╝
📋 Installation¶
# Copy hooks to .git/hooks/
cp hooks/* .git/hooks/
chmod +x .git/hooks/*
# Or use a hook manager like Husky (for npm projects)
npm install --save-dev husky
npx husky install
npx husky add .husky/pre-commit "bash hooks/pre-commit"
⚠️ Skip Hooks¶
Note: Only skip hooks when absolutely necessary. Document the reason in your commit message.
🔧 Configuration¶
Environment Variables¶
Set these in your CI/CD environment or .git/config:
# Webhook URL for post-receive
export CI_WEBHOOK_URL="https://ci.example.com/webhook"
# Formatter path
export CLANG_FORMAT_PATH="/usr/bin/clang-format"
Local Configuration¶
📝 Hook Details¶
pre-commit¶
- Runs before commit is created
- Fast checks only (< 5 seconds)
- Format validation, basic linting
- Can modify staged files
commit-msg¶
- Validates commit message format
- Enforces conventional commits
- Checks ticket references
pre-push¶
- Runs before push to remote
- Can run longer tests (< 1 minute)
- Local build verification
- Branch name validation
post-receive¶
- Server-side hook
- Triggers CI/CD pipeline
- Sends notifications
- Updates deployment status
🚨 Best Practices¶
- Keep hooks fast
- pre-commit: < 5s
- pre-push: < 60s
-
Defer heavy tasks to CI
-
Make hooks optional
- Always allow
--no-verify -
CI is the source of truth
-
Test hooks locally
- Run hooks manually before committing
-
Verify they work on all platforms
-
Version control hooks
- Store in project root
- Document installation process
- Keep platform compatibility
🔍 Troubleshooting¶
Hook not running¶
Hook failing incorrectly¶
Windows compatibility¶
- Use
#!/usr/bin/env bashshebang - Test with Git Bash
- Avoid platform-specific commands