git_hooks
git hooks
Automate actions at Git events.
π Hook Location
Hooks are in .git/hooks/
ls .git/hooks/
Lists available hook samples.
π Hook Types
graph TD
A[Client Hooks] --> B[pre-commit]
A --> C[commit-msg]
A --> D[pre-push]
E[Server Hooks] --> F[pre-receive]
E --> G[post-receive]
π§ Create Hook
Make Hook File
touch .git/hooks/pre-commit
Creates hook file.
Make Executable
chmod +x .git/hooks/pre-commit
Makes hook executable (required).
π Common Client Hooks
pre-commit
Runs before commit is created.
#!/bin/bash
# .git/hooks/pre-commit
npm test
Exit non-zero to cancel commit.
commit-msg
Validates commit message.
#!/bin/bash
# .git/hooks/commit-msg
message=$(cat "$1")
if ! [[ "$message" =~ ^(feat|fix|docs): ]]; then
echo "Error: Message must start with feat:, fix:, or docs:"
exit 1
fi
Enforces commit message format.
pre-push
Runs before push.
#!/bin/bash
# .git/hooks/pre-push
npm test
Cancel push if tests fail.
post-checkout
Runs after checkout.
#!/bin/bash
# .git/hooks/post-checkout
npm install
Install dependencies after checkout.
π¦ Sharing Hooks
Create Hooks Directory
mkdir .githooks
Create hooks in version control.
Configure Git to Use
git config core.hooksPath .githooks
Points Git to shared hooks.
π οΈ Hook Management Tools
Install Husky
npm install husky --save-dev
Popular hook manager for Node.js projects.
Initialize Husky
npx husky install
Sets up Husky.
Add Husky Pre-commit
npx husky add .husky/pre-commit "npm test"
Adds pre-commit hook.
Install pre-commit (Python)
pip install pre-commit
Python-based hook manager.
Run pre-commit Install
pre-commit install
Installs hooks from config.
π Example .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
Configuration for pre-commit.
βοΈ Skip Hooks
Skip Pre-commit
git commit --no-verify -m "Message"
Skips pre-commit and commit-msg hooks.
Skip Pre-push
git push --no-verify
Skips pre-push hooks.
π‘ Tips
Debug Hooks
Add set -x at top of script for debugging.
Keep Hooks Fast
Slow hooks annoy developers. Use caching.
π Related
#git #hooks #automation #advanced