10. Git hooks — pre-commit & pre-push
Git & GitHub · 48 pages source format
Hooks run scripts at Git lifecycle events. pre-commit: lint/format. pre-push: tests. Husky or plain .git/hooks.
What you'll learn
- Hook scripts in .git/hooks
- pre-commit framework
- Husky for Node projects
- CI vs local hooks
Simple pre-commit hook
Executable script in .git/hooks/pre-commit. Exit 1 blocks commit. Test in practice repo.
#!/bin/sh
# .git/hooks/pre-commit
if ! grep -q "." README.md 2>/dev/null; then
echo "README must not be empty"
exit 1
fiDo this now
Hook that rejects commits if README is empty.
pre-commit framework
pip install pre-commit. .pre-commit-config.yaml with ruff, trailing-whitespace. pre-commit install.
Do this now
Add pre-commit to py-journey or git-practice with trailing-whitespace hook.
Husky for JS projects
npx husky init. pre-commit runs lint-staged. Complements CI — catches issues before push.
Do this now
If you have a JS project: add Husky pre-commit running npm test or lint.
Pro tip. Hooks are local — CI is the enforcement layer for teams. Both matter.