Git hooks automation tool that enforces code quality before commits
Core Idea: Husky simplifies the implementation of Git hooks, particularly pre-commit hooks, allowing developers to automatically run scripts (like linters and tests) before code is committed to ensure quality standards.
Key Elements
-
Key Features:
- Easy git hooks configuration through package.json or dedicated files
- Prevents poor quality code from being committed
- Can be bypassed when necessary with
--no-verify
flag - Supports all git hook types (pre-commit, pre-push, etc.)
- Minimal configuration required
-
Technical Specifications:
- Node.js based tool
- Creates actual git hook scripts in the .git/hooks directory
- Works across different operating systems
- Highly configurable with custom scripts
- Modern version (Husky 5+) uses native git hooks
-
Use Cases:
- Running linters before code is committed
- Executing tests to prevent breaking changes
- Enforcing commit message formats
- Preventing secrets or sensitive data from being committed
- Maintaining consistent code quality across teams
-
Implementation Steps:
- Install Husky:
npm install --save-dev husky
- Initialize Husky:
npx husky install
(or add as a prepare script) - Create a pre-commit hook:
npx husky add .husky/pre-commit "npm run lint"
- Make the hook executable (if needed):
chmod +x .husky/pre-commit
- Commit the Husky setup files to share with the team
- Install Husky:
-
Code Example:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# Run lint-staged to check only changed files
npx lint-staged
# Alternatively, run multiple commands:
# npm run lint && npm run test
Connections
- Related Concepts: ESLint (tool commonly run by Husky hooks), Lint Staged (often used with Husky to optimize performance)
- Broader Context: Git Workflow Automation (part of automated git workflow)
- Applications: Continuous Integration (local precursor to CI checks)
- Components: Git Hooks (underlying mechanism that Husky simplifies)
References
- Husky GitHub Repository: https://github.com/typicode/husky
- "Git Hooks with Husky" by Typicode
- "Automating Code Quality" by Kent C. Dodds
#git #automation #hooks #code-quality #pre-commit
Connections:
Sources: