Git Hooks
Problem
Broken code gets committed to the repository: failing tests, linting errors, unformatted code, and type errors make it to the main branch. CI pipelines fail after the fact, blocking other developers and requiring additional commits to fix issues that should have been caught locally.
Solution
Run automated checks before commits or pushes to enforce quality standards and prevent broken code from entering the repository. This catches issues locally before they trigger failed CI builds.
Example
This example demonstrates configuring Git hooks with Husky to run linting before commits and tests before pushes.
{
"husky": {
"hooks": {
"pre-commit": "lint-staged", // Run lint-staged before each commit
"pre-push": "npm test" // Run test suite before pushing to remote
}
},
"lint-staged": {
// For staged JavaScript files: run ESLint with auto-fix
"*.js": ["eslint --fix", "git add"]
}
}
Benefits
- Catches issues locally before they reach the repository and trigger CI failures.
- Enforces code quality standards consistently across all team members.
- Saves time by preventing broken commits that require follow-up fixes.
- Reduces
CIbuild costs by filtering out obvious failures before they run.
Tradeoffs
- Slows down the commit process as checks run before each commit.
- Can be frustrating when hooks block commits due to minor formatting issues.
- Requires setup and maintenance to keep hooks in sync across the team.
- May be bypassed with —no-verify flag, making enforcement optional.