Automating repetitive tasks is essential for efficiency, consistency, and reducing human error in software development. Git offers a built-in way to trigger custom scripts at key points in your workflow through a feature called "hooks." In this article, I’ll introduce you to Git hooks, show common examples, and provide tips for managing hooks in team projects.
What Are Git Hooks?
Git hooks are executable scripts placed in your repository’s .git/hooks/
directory. These scripts run automatically when particular events occur in your Git workflow, allowing you to automate tasks like:
- Enforcing coding standards before commits
- Running tests before pushing
- Sending notifications after a merge
There are two types of hooks: client-side (triggered by actions like committing or merging) and server-side (used in bare repositories to control pushes and updates).
Common Use Cases for Git Hooks
1. Pre-commit: Checking Your Code
A pre-commit
hook can run code linters, formatters, or validators on staged files. For example, to prevent committing code that doesn’t meet your standards:
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Commit aborted."
exit 1
fi
2. Pre-push: Running Tests
A pre-push
hook lets you catch failing tests before code reaches the remote repo:
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Push aborted."
exit 1
fi
3. Commit-msg: Enforcing Commit Message Format
You might require each commit message to follow a convention. The commit-msg
hook validates the message:
#!/bin/sh
if ! grep -qE "^[A-Z]+: ".git/COMMIT_EDITMSG; then
echo "Commit message must start with a type: e.g., FIX: description"
exit 1
fi
Managing Git Hooks Across a Team
By default, Git doesn’t track the contents of .git/hooks/
, making team-wide hooks tricky. A common approach is:
- Store hook scripts in a directory like
scripts/hooks/
in your repo. - Add a setup script to symlink or copy these scripts into
.git/hooks/
for each developer.
Or, use tools like Husky (for JavaScript projects) to manage hooks more easily and ensure consistency.
Best Practices
- Keep hooks fast: Slow hooks can annoy developers.
- Provide clear error messages: Make it easy for others to fix what caused a hook to fail.
- Document your hooks: Let your team know which hooks are enforced and how to install them.
Conclusion
Git hooks are a powerhouse for automating tasks and enforcing standards before code ever leaves your machine. Start simple—set up a pre-commit or pre-push hook—and you’ll quickly see the benefits of less manual work and more reliable code.
Have you automated something useful with a Git hook? Share your experiences in the comments!
— Joe Git
Leave a Reply to Drew Cancel reply