⚙️ Run Scripts Automatically on Git Events
Run tests before commit? Lint before push? Git hooks automate anything. No more forgotten steps.
📝 pre-commit Hook
#!/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) echo "✅ pre-commit checks passed" exit 0
🎯 commit-msg Hook
#!/bin/bash
# .git/hooks/commit-msg
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'
if ! grep -qE $commit_regex "$1"; then
echo "❌ Invalid commit message format!"
echo " Allowed: feat|fix|docs|style|refactor|test|chore"
echo " Example: feat(api): add user authentication"
exit 1
fi
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.”
