Skip to content

🪝 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

# Emergency bypass (use sparingly)
git commit --no-verify
git push --no-verify

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

# Configure git to use hooks directory
git config core.hooksPath .githooks/

📝 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

  1. Keep hooks fast
  2. pre-commit: < 5s
  3. pre-push: < 60s
  4. Defer heavy tasks to CI

  5. Make hooks optional

  6. Always allow --no-verify
  7. CI is the source of truth

  8. Test hooks locally

  9. Run hooks manually before committing
  10. Verify they work on all platforms

  11. Version control hooks

  12. Store in project root
  13. Document installation process
  14. Keep platform compatibility

🔍 Troubleshooting

Hook not running

# Check if executable
ls -la .git/hooks/pre-commit

# Make executable
chmod +x .git/hooks/pre-commit

Hook failing incorrectly

# Debug mode
bash -x .git/hooks/pre-commit

# Check exit code
echo $?

Windows compatibility

  • Use #!/usr/bin/env bash shebang
  • Test with Git Bash
  • Avoid platform-specific commands