Git hooks are scripts that run automatically at certain points in the Git workflow. They allow you to enforce rules, automate tasks, and customize Git behavior.
Hooks are stored in the .git/hooks/ directory inside a Git repository and are executed locally. There are two main types of hooks:
- Client-side hooks: Run on developers' machines (e.g., pre-commit, pre-push, post-merge).
- Server-side hooks: Run on the remote repository (e.g., pre-receive, post-receive).
- Navigate to the
.git/hooks/directory inside your repository. - Rename the sample hook (e.g.,
pre-commit.sampletopre-commit). - Make the script executable:
chmod +x .git/hooks/pre-commit. - Write the script using a supported language (e.g., Bash, Python, or another scripting language).
Runs before a commit is created, preventing commits that don’t meet certain criteria.
#!/bin/bash
# Run linting before committing
if ! flake8; then
echo "Code does not meet style guidelines. Fix errors before committing."
exit 1
fiRuns before a git push command is executed, allowing you to enforce policies.
#!/bin/bash
branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$branch" = "main" ]; then
echo "You cannot push directly to main! Use a feature branch and create a pull request."
exit 1
fiEnsures that commit messages follow a specific pattern.
#!/bin/bash
commit_msg_file=$1
commit_msg=$(cat "$commit_msg_file")
if ! [[ "$commit_msg" =~ ^(feat|fix|docs|style|refactor|test|chore): ]]; then
echo "Commit message must follow the format: <type>: <message> (e.g., feat: add new API)"
exit 1
fiAutomatically installs dependencies when a merge is completed.
#!/bin/bash
echo "Running post-merge hook: Installing dependencies"
npm installUsed on remote repositories to validate incoming changes.
#!/bin/bash
while read oldrev newrev refname; do
if [[ "$refname" == "refs/heads/main" ]]; then
echo "Direct commits to main are not allowed!"
exit 1
fi
doneBy default, hooks are stored in .git/hooks/, but you can centralize them using:
git config core.hooksPath path/to/hooks-directoryThis allows teams to share hooks in a repository without modifying the local .git/hooks/ folder.
Git hooks are a powerful way to enforce rules, automate tasks, and improve workflow efficiency. By implementing them, teams can ensure code quality and streamline their Git operations.