Chapter 10 — Git Hooks and Automation
10.1 Introduction
Modern software development emphasizes automation, policy enforcement, and workflow consistency. Git hooks provide a mechanism to execute scripts automatically in response to repository events.
Hooks enable:
-
Code quality enforcement
-
Testing automation
-
Security validation
-
CI trigger preparation
-
Deployment orchestration
This chapter explores Git hook architecture, hook lifecycle, implementation patterns, and automation strategies.
10.2 What are Git Hooks?
Git hooks are executable scripts triggered by Git actions.
Examples:
-
Before commit
-
After commit
-
Before push
-
After merge
Hooks reside inside the repository’s internal directory and operate locally unless explicitly propagated.
10.3 Hook Storage Location
Hooks are stored in:
.git/hooks/
Directory contents include sample scripts:
pre-commit.sample
pre-push.sample
commit-msg.sample
To activate a hook:
-
Rename file (remove
.sample) -
Add executable permission
10.4 Hook Categories
Hooks fall into two major groups:
1. Client-side hooks
Triggered by local Git operations.
2. Server-side hooks
Triggered on remote repositories during push operations.
10.5 Client-Side Hooks Overview
| Hook | Trigger |
|---|---|
| pre-commit | Before commit creation |
| prepare-commit-msg | Before commit editor opens |
| commit-msg | After commit message entry |
| post-commit | After commit |
| pre-rebase | Before rebase |
| post-checkout | After branch switch |
| pre-push | Before push |
10.6 Server-Side Hooks Overview
| Hook | Trigger |
|---|---|
| pre-receive | Before push accepted |
| update | Per branch update |
| post-receive | After push completion |
Commonly used in centralized repositories.
10.7 Hook Execution Model
Key characteristics:
-
Executed synchronously
-
Non-zero exit → operation aborted
-
Environment variables available
-
STDIN may contain metadata
Thus, hooks can enforce strict policies.
10.8 Creating a Pre-Commit Hook
Example: Prevent empty commits
Create file:
.git/hooks/pre-commit
Script:
#!/bin/sh
if git diff --cached --quiet; then
echo "No staged changes"
exit 1
fi
Make executable:
chmod +x .git/hooks/pre-commit
10.9 Code Quality Enforcement Hook
Example: Run linter before commit
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
echo "Lint errors found"
exit 1
fi
Ensures repository standards.
10.10 Commit Message Validation
Hook:
.git/hooks/commit-msg
Script:
#!/bin/sh
grep -qE "^(feat|fix|docs|style|refactor)" "$1"
if [ $? -ne 0 ]; then
echo "Invalid commit message"
exit 1
fi
Enforces conventional commit format.
10.11 Pre-Push Testing Hook
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
echo "Tests failed"
exit 1
fi
Prevents broken code from reaching remote.
10.12 Post-Commit Automation
Post-commit hooks cannot block commits.
Typical uses:
-
Desktop notifications
-
Auto documentation generation
-
Metrics logging
Example:
echo "Commit created" >> commit.log
10.13 Post-Checkout Hook
Triggered after branch change.
Use cases:
-
Dependency installation
-
Environment configuration
-
Cache invalidation
Example:
npm install
10.14 Pre-Rebase Hook
Used to prevent rebasing protected branches.
branch=$(git symbolic-ref --short HEAD)
if [ "$branch" = "main" ]; then
echo "Cannot rebase main"
exit 1
fi
10.15 Server-Side Pre-Receive Hook
Executed before accepting push.
Common policies:
-
Block large files
-
Enforce commit message rules
-
Validate signatures
Example concept:
while read oldrev newrev refname
do
echo "Processing $refname"
done
10.16 Update Hook
Runs per branch update.
Allows fine-grained branch policies.
Example:
-
Protect release branches
-
Validate branch naming
10.17 Post-Receive Hook
Runs after successful push.
Common automation:
-
CI trigger
-
Deployment
-
Notification
Example:
echo "Push received"
10.18 Hook Distribution Challenge
Hooks are not version-controlled by default.
Solutions:
-
Template repositories
-
Shared scripts
-
Package-managed hooks
-
Symbolic linking
10.19 Hooks Path Configuration
Custom hook directory:
git config core.hooksPath .githooks
Allows hooks to be versioned.
10.20 Hook Development Languages
Hooks can be written in:
-
Shell
-
Python
-
Node.js
-
PHP
-
PowerShell
Requirement: executable script.
10.21 Environment Variables in Hooks
Common variables:
-
GIT_DIR -
GIT_WORK_TREE -
GIT_INDEX_FILE
These provide repository context.
10.22 Automation Patterns
1. Quality gate automation
Lint + tests
2. Security automation
Secret scanning
3. Policy enforcement
Commit message rules
4. Environment automation
Auto setup
10.23 Integration with CI/CD
Hooks complement CI pipelines.
Comparison:
| Hooks | CI |
|---|---|
| Local enforcement | Remote enforcement |
| Fast feedback | Full pipeline |
| Developer-centric | System-centric |
Together they create layered automation.
10.24 Performance Considerations
Heavy hooks may:
-
Slow commits
-
Frustrate developers
-
Reduce adoption
Mitigation:
-
Fast checks locally
-
Heavy checks in CI
10.25 Security Considerations
Risks:
-
Malicious hooks
-
Credential exposure
-
Arbitrary code execution
Mitigation:
-
Review shared hooks
-
Restrict permissions
-
Avoid executing unknown scripts
10.26 Practical Example Workflow
# commit
pre-commit → lint
commit-msg → message validation
post-commit → notification
pre-push → tests
# push
server pre-receive → policy check
post-receive → deployment
Represents complete automated lifecycle.
10.27 Best Practices
-
Keep hooks lightweight
-
Provide clear failure messages
-
Version hooks when possible
-
Document hook behavior
-
Avoid platform-specific scripts
10.28 Common Mistakes
| Mistake | Impact |
|---|---|
| Complex hooks | Developer bypass |
| Hidden hook behavior | Confusion |
| Missing documentation | Maintenance difficulty |
| Ignoring cross-platform issues | Execution failures |
10.29 Summary
This chapter examined:
-
Git hook architecture
-
Client and server hook taxonomy
-
Hook lifecycle
-
Script implementation
-
Automation patterns
-
Hook distribution strategies
-
Security and performance considerations
Git hooks enable repository-centric automation, enforcing quality and policy before code enters shared history.
No comments:
Post a Comment