🔗 Git Hooks = Automation Power
Manual checks are error-prone. Git hooks automate tasks before commits, pushes, and merges.
📝 Git Hook Setup
# Navigate to hooks directory
cd .git/hooks
# Common hooks
pre-commit # Run before commit
prepare-commit-msg # Edit commit message
commit-msg # Validate commit message
post-commit # Run after commit
pre-push # Run before push
post-checkout # Run after checkout
pre-rebase # Run before rebase
post-merge # Run after merge
# Create a pre-commit hook
#!/bin/sh
# .git/hooks/pre-commit
# Run linter before commit
npm run lint
# Run tests before commit
npm test
# Check for debugging code
if grep -r 'console.log' src/; then
echo 'Error: Console.log found in code'
exit 1
fi
# Make it executable
chmod +x .git/hooks/pre-commit
🎯 Advanced Git Hooks
# commit-msg (Validate commit messages)
#!/bin/sh
# .git/hooks/commit-msg
commit_msg_file=$1
commit_msg=$(cat "$commit_msg_file")
# Check commit message format
if ! echo "$commit_msg" | grep -qE '^(feat|fix|docs|style|refactor|test|chore): .+'; then
echo "Error: Commit message must follow conventional commits format:"
echo "feat: add feature X"
echo "fix: resolve bug Y"
exit 1
fi
# pre-push (Run tests before push)
#!/bin/sh
# .git/hooks/pre-push
echo "Running tests before push..."
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Push aborted."
exit 1
fi
# post-merge (Install dependencies after merge)
#!/bin/sh
# .git/hooks/post-merge
if [ -f package.json ]; then
npm install
fi
# pre-rebase (Prevent rebase on main)
#!/bin/sh
# .git/hooks/pre-rebase
branch=$(git branch --show-current)
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
echo "Error: Cannot rebase on main branch"
exit 1
fi
💡 Git Hook Best Practices
- Keep hooks fast (<1-2 seconds)
- Use husky for team hook management
- Validate commit messages
- Run tests before push
- Install dependencies after merge
Git hooks enforce quality automatically. They catch issues before they reach the repository.
