Git Hooks are scripts that Git executes before or after events such as commit, push, and receive. They are a powerful way to automate your workflow and enforce project standards.
Where are Hooks Stored?
Hooks are stored in the .git/hooks directory of every Git repository. By default, this directory contains several example scripts.
Command:
ls .git/hooksResult:
applypatch-msg.sample pre-push.sample
commit-msg.sample pre-rebase.sample
post-update.sample pre-receive.sample
pre-applypatch.sample prepare-commit-msg.sample
pre-commit.sample update.sampleClient-Side vs. Server-Side Hooks
- Client-Side Hooks: Run on your local machine (e.g.,
pre-commit,pre-push). - Server-Side Hooks: Run on the server (e.g., GitHub, GitLab) when receiving pushed commits (e.g.,
pre-receive,post-receive).
The pre-commit Hook
The pre-commit hook runs before you even type a commit message. It's perfect for:
- Running linters (ESLint, Prettier)
- Running unit tests
- Checking for secrets (API keys) in code
Example: Simple Pre-commit Linter
Create a file at .git/hooks/pre-commit:
#!/bin/bash
echo "Running pre-commit checks..."
# Check for 'TODO' in code
if grep -q "TODO" . -r --exclude-dir=.git; then
echo "ERROR: You have TODOs in your code. Please fix them before committing."
exit 1
fi
echo "Checks passed!"
exit 0Action:
chmod +x .git/hooks/pre-commit
git commit -m "Add new feature"Result (if TODO found):
Running pre-commit checks...
ERROR: You have TODOs in your code. Please fix them before committing.The pre-push Hook
Runs before git push sends data to the remote. Use this for "heavy" tasks like integration tests or build checks.
Using Husky (Modern Workflow)
In the JavaScript/DevOps ecosystem, Husky is the industry standard for managing hooks because Git hooks in .git/hooks are NOT committed to the repository. Husky allows you to share hooks with your team.
Command:
npx husky-init && npm install
npx husky add .husky/pre-commit "npm test"Result:
This creates a .husky/ directory that is tracked by Git, ensuring every developer runs the same checks.
DevOps Use Cases for Hooks
- Security: Run
gitleaksortrufflehogto prevent secrets from being committed. - Quality: Enforce conventional commit messages (e.g.,
feat:,fix:) usingcommit-msghooks. - Efficiency: Automatically update documentation or build artifacts.
Summary
- Hooks live in
.git/hooks/. pre-commitis the most common hook.- Use Husky to share hooks with your team.
- Hooks are your first line of defense in a CI/CD pipeline.