Git Hooks & Automation
Git hooks are scripts that run automatically every time a particular event occurs in a Git repository.What are Git Hooks?
Hooks are stored in the.git/hooks directory. They are shell scripts that can run before or after Git actions.
Common Hooks
| Hook | When it runs | Use Case |
|---|---|---|
| pre-commit | Before git commit | Linting, formatting, running unit tests. |
| commit-msg | After entering message | Enforcing commit message patterns (e.g., “JIRA-123: …“). |
| pre-push | Before git push | Running integration tests, preventing accidental push to main. |
Creating a Hook (Manual)
Create a file.git/hooks/pre-commit:
Automating with Husky (JavaScript/Node)
Sharing hooks via.git/hooks is hard because that directory isn’t committed. Husky solves this by configuring hooks in your project files.
1. Install Husky
2. Add a Hook
This creates a.husky/pre-commit file.
git commit, npm test will run first. If it fails, the commit fails.
Lint-Staged
Running tests on the entire project for every commit is slow. lint-staged allows you to run scripts only on the files that are currently staged. package.json:Key Takeaways
- Use Hooks to shift quality checks “left” (to the developer’s machine).
- Use Husky to share hooks across your team.
- Use Lint-Staged to keep commits fast.
- Don’t rely only on hooks (developers can bypass them with
git commit --no-verify). Always run checks in CI too.
Next: Linux Crash Course →