Automate code quality, testing, and validation using Git hooks—scripts that run automatically at key points in the Git workflow.
使用Git hooks自动化代码质量检查、测试与验证——这些脚本会在Git工作流的关键节点自动运行。
What Are Git Hooks
什么是Git Hooks
Git hooks are executable scripts that Git runs automatically when specific events occur in a repository. They enable you to:
- Enforce code quality before commits reach the repository
- Run automated tests to catch issues early
- Validate commit messages to maintain consistent standards
- Prevent accidental destructive actions like force pushes
- Trigger CI/CD workflows on push events
- Automate versioning and tagging for releases
Hooks reside in
by default, but can be version-controlled using
configuration.
Git hooks是Git在仓库发生特定事件时自动运行的可执行脚本。它们可以帮助您:
- 在提交进入仓库前强制保证代码质量
- 运行自动化测试,尽早发现问题
- 验证提交信息,保持标准一致
- 防止意外的破坏性操作,比如强制推送
- 在推送事件触发CI/CD工作流
- 为发布自动化版本控制与打标签
默认情况下,Hooks存放在
目录中,但可以通过
配置进行版本控制。
Client-side hooks (run on developer machines):
- - Before commit is created, validate staged changes
- - Populate commit message template
- - Validate commit message format
- - Notification after successful commit
- - Before pushing to remote, run tests
- - After checkout, clean up working directory
- - Before rebasing, check for conflicts
Server-side hooks (run on remote repository):
- - Before accepting pushed refs, enforce policies
- - Like pre-receive, but runs per branch
- - After successful push, trigger CI/CD
客户端钩子(在开发者机器上运行):
- - 在创建提交前,验证暂存的变更
- - 填充提交信息模板
- - 验证提交信息格式
- - 提交成功后发送通知
- - 推送到远程仓库前,运行测试
- - 切换分支后,清理工作目录
- - 变基前,检查冲突
服务端钩子(在远程仓库上运行):
- - 接受推送的引用前,执行策略检查
- - 类似pre-receive,但针对每个分支运行
- - 推送成功后,触发CI/CD
Developer action → Git event → Hook script runs → Exit code determines outcome
- Exit 0: Continue with Git operation
- Exit non-zero: Abort Git operation with error message
开发者操作 → Git事件 → 钩子脚本运行 → 退出码决定结果
- Exit 0: 继续执行Git操作
- Exit non-zero: 终止Git操作并显示错误信息
Making Hooks Executable
使钩子可执行
Hooks must have execute permissions:
bash
chmod +x .git/hooks/pre-commit
钩子必须具备执行权限:
bash
chmod +x .git/hooks/pre-commit
Setting Up Version-Controlled Hooks
设置可版本控制的钩子
Git doesn't version-control
by default. Use
to enable team-wide hooks:
1. Create hooks directory in repository:
2. Configure Git to use custom hooks path:
bash
git config core.hooksPath .githooks
3. Add hooks to version control:
bash
git add .githooks/
git commit -m "Add version-controlled git hooks"
4. Team members run after cloning:
bash
git config core.hooksPath .githooks
This project follows this pattern. See
directory for working examples.
Git默认不会对
进行版本控制。使用
来启用团队共享的钩子:
1. 在仓库中创建钩子目录:
2. 配置Git使用自定义钩子路径:
bash
git config core.hooksPath .githooks
3. 将钩子加入版本控制:
bash
git add .githooks/
git commit -m "Add version-controlled git hooks"
4. 团队成员克隆仓库后运行:
bash
git config core.hooksPath .githooks
Creating a Basic Pre-Commit Hook
创建基础的Pre-Commit钩子
Use case: Validate bash scripts before committing.
1. Create hook file:
bash
touch .githooks/pre-commit
chmod +x .githooks/pre-commit
2. Add validation logic:
bash
#!/bin/bash
set -e
echo "🔍 Validating bash scripts..."
使用场景: 提交前验证bash脚本。
1. 创建钩子文件:
bash
touch .githooks/pre-commit
chmod +x .githooks/pre-commit
2. 添加验证逻辑:
bash
#!/bin/bash
set -e
echo "🔍 Validating bash scripts..."
Get staged .sh files
Get staged .sh files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '.sh$' || true)
if [ -z "$STAGED_FILES" ]; then
echo "✅ No bash scripts to validate"
exit 0
fi
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '.sh$' || true)
if [ -z "$STAGED_FILES" ]; then
echo "✅ No bash scripts to validate"
exit 0
fi
Validate syntax
Validate syntax
for file in $STAGED_FILES; do
if [ -f "$file" ]; then
echo "Checking $file..."
bash -n "$file" || exit 1
fi
done
echo "✅ All bash scripts valid"
exit 0
**Key patterns**:
- Use `set -e` to fail fast on errors
- Check for staged files with `git diff --cached`
- Exit early if no relevant files
- Provide clear visual feedback with emojis
- Exit with non-zero on validation failure
for file in $STAGED_FILES; do
if [ -f "$file" ]; then
echo "Checking $file..."
bash -n "$file" || exit 1
fi
done
echo "✅ All bash scripts valid"
exit 0
**核心模式**:
- 使用`set -e`在出错时立即终止
- 通过`git diff --cached`检查暂存文件
- 若无相关文件则提前退出
- 使用表情符号提供清晰的视觉反馈
- 验证失败时返回非零退出码
Modular Hook Architecture
模块化钩子架构
Problem: Single hook file becomes complex with multiple validations.
Solution: Orchestrator pattern that discovers and runs modular hook scripts.
1. Create hooks.d/ directory:
bash
mkdir .githooks/hooks.d
2. Create orchestrator in pre-commit:
bash
#!/bin/bash
set -e
HOOKS_DIR="$(dirname "$0")/hooks.d"
if [ -d "$HOOKS_DIR" ]; then
for hook in "$HOOKS_DIR"/*; do
if [ -x "$hook" ]; then
echo "Running: $(basename "$hook")"
"$hook" || exit 1
fi
done
fi
exit 0
3. Add individual validation scripts:
问题: 单个钩子文件包含多个验证逻辑后会变得复杂。
解决方案: 使用编排器模式,发现并运行模块化的钩子脚本。
1. 创建hooks.d/目录:
bash
mkdir .githooks/hooks.d
2. 在pre-commit中创建编排器:
bash
#!/bin/bash
set -e
HOOKS_DIR="$(dirname "$0")/hooks.d"
if [ -d "$HOOKS_DIR" ]; then
for hook in "$HOOKS_DIR"/*; do
if [ -x "$hook" ]; then
echo "Running: $(basename "$hook")"
"$hook" || exit 1
fi
done
fi
exit 0
3. 添加独立的验证脚本:
.githooks/hooks.d/10-validate-bash.sh
.githooks/hooks.d/10-validate-bash.sh
.githooks/hooks.d/20-validate-yaml.sh
.githooks/hooks.d/20-validate-yaml.sh
.githooks/hooks.d/30-run-tests.sh
.githooks/hooks.d/30-run-tests.sh
**Naming convention**: Use numbered prefixes (10, 20, 30) to control execution order and allow inserting new hooks between existing ones (e.g., add a hypothetical `15-validate-json.sh` between 10 and 20).
This project uses this pattern. See `.githooks/hooks.d/` for examples.
**命名约定**: 使用数字前缀(10、20、30)控制执行顺序,方便在现有钩子之间插入新钩子(例如,在10和20之间添加假设的`15-validate-json.sh`)。
本项目采用此模式。请查看`.githooks/hooks.d/`目录获取示例。
Validating Commit Messages
验证提交信息
Use case: Enforce conventional commit format.
Create commit-msg hook:
bash
#!/bin/bash
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")
使用场景: 强制遵循规范的提交格式。
创建commit-msg钩子:
bash
#!/bin/bash
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")
Pattern: type(scope): description
Pattern: type(scope): description
PATTERN="^(feat|fix|docs|style|refactor|test|chore)((.+))?: .{10,}$"
if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
echo "❌ Invalid commit message format"
echo ""
echo "Expected format: type(scope): description"
echo "Types: feat, fix, docs, style, refactor, test, chore"
echo "Example: feat(auth): add OAuth2 login support"
exit 1
fi
echo "✅ Commit message valid"
exit 0
PATTERN="^(feat|fix|docs|style|refactor|test|chore)((.+))?: .{10,}$"
if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
echo "❌ Invalid commit message format"
echo ""
echo "Expected format: type(scope): description"
echo "Types: feat, fix, docs, style, refactor, test, chore"
echo "Example: feat(auth): add OAuth2 login support"
exit 1
fi
echo "✅ Commit message valid"
exit 0
Running Tests Before Push
推送前运行测试
Use case: Prevent pushing broken code to remote.
Create pre-push hook:
bash
#!/bin/bash
set -e
echo "🧪 Running tests before push..."
使用场景: 防止将有问题的代码推送到远程仓库。
创建pre-push钩子:
bash
#!/bin/bash
set -e
echo "🧪 Running tests before push..."
Run test suite
Run test suite
npm test || {
echo "❌ Tests failed. Push aborted."
exit 1
}
echo "✅ All tests passed"
exit 0
npm test || {
echo "❌ Tests failed. Push aborted."
exit 1
}
echo "✅ All tests passed"
exit 0
Preventing Force Push to Main
禁止向Main分支强制推送
Use case: Protect production branches from destructive operations.
Create pre-push hook:
bash
#!/bin/bash
PROTECTED_BRANCHES="^(main|master|production)$"
while read local_ref local_sha remote_ref remote_sha; do
remote_branch=$(echo "$remote_ref" | sed 's/refs\/heads\///')
if echo "$remote_branch" | grep -qE "$PROTECTED_BRANCHES"; then
# Check if it's a force push
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
echo "❌ Deleting $remote_branch is not allowed"
exit 1
fi
# Check for force push
if ! git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null; then
echo "❌ Force push to $remote_branch is not allowed"
exit 1
fi
fi
done
exit 0
使用场景: 保护生产分支免受破坏性操作影响。
创建pre-push钩子:
bash
#!/bin/bash
PROTECTED_BRANCHES="^(main|master|production)$"
while read local_ref local_sha remote_ref remote_sha; do
remote_branch=$(echo "$remote_ref" | sed 's/refs\/heads\///')
if echo "$remote_branch" | grep -qE "$PROTECTED_BRANCHES"; then
# Check if it's a force push
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
echo "❌ Deleting $remote_branch is not allowed"
exit 1
fi
# Check for force push
if ! git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null; then
echo "❌ Force push to $remote_branch is not allowed"
exit 1
fi
fi
done
exit 0
Project-Specific Implementation
项目特定实现
This repository implements a production-ready Git hooks system. Follow this implementation pattern for your projects.
本仓库实现了一套生产可用的Git hooks系统。您可以为自己的项目遵循此实现模式。
.githooks/
├── pre-commit # Orchestrator script
├── hooks.d/ # Individual validation scripts
│ ├── the-perfect-developer-base-collection-10-validate-bash.sh
│ └── the-perfect-developer-base-collection-20-validate-skills.sh
└── README.md # Documentation
.githooks/
├── pre-commit # Orchestrator script
├── hooks.d/ # Individual validation scripts
│ ├── the-perfect-developer-base-collection-10-validate-bash.sh
│ └── the-perfect-developer-base-collection-20-validate-skills.sh
└── README.md # Documentation
Automated setup:
This configures
git config core.hooksPath .githooks
automatically.
自动化设置:
该脚本会自动配置
git config core.hooksPath .githooks
。
Hook Naming Convention
钩子命名约定
Use this pattern for modular hooks:
the-perfect-developer-base-collection-<number>-<description>.sh
- Prefix: Project/team identifier
- Number: Execution order (increments of 10: 10, 20, 30...)
- Description: What the hook validates
Increments of 10 allow inserting new hooks between existing ones (e.g., add
between 10 and 20).
模块化钩子采用以下命名模式:
the-perfect-developer-base-collection-<number>-<description>.sh
- 前缀: 项目/团队标识符
- 数字: 执行顺序(以10为增量:10、20、30...)
- 描述: 钩子的验证内容
以10为增量的数字允许在现有钩子之间插入新钩子(例如,在10和20之间添加
)。
Testing Individual Hooks
测试独立钩子
Run hooks independently for testing:
Test single hook
Test single hook
.githooks/hooks.d/10-validate-bash.sh
.githooks/hooks.d/10-validate-bash.sh
Test orchestrator
Test orchestrator
Temporarily disable a hook
Temporarily disable a hook
chmod -x .githooks/hooks.d/20-validate-skills.sh
chmod -x .githooks/hooks.d/20-validate-skills.sh
Or rename with .disabled extension
Or rename with .disabled extension
mv .githooks/hooks.d/20-validate-skills.sh{,.disabled}
mv .githooks/hooks.d/20-validate-skills.sh{,.disabled}
Use this template for new validation hooks:
bash
#!/bin/bash
set -e
echo "🔍 Running [VALIDATION NAME]..."
使用以下模板创建新的验证钩子:
bash
#!/bin/bash
set -e
echo "🔍 Running [VALIDATION NAME]..."
Get staged files matching pattern
Get staged files matching pattern
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep 'pattern' || true)
if [ -z "$STAGED_FILES" ]; then
echo "✅ No files to validate"
exit 0
fi
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep 'pattern' || true)
if [ -z "$STAGED_FILES" ]; then
echo "✅ No files to validate"
exit 0
fi
Validation logic
Validation logic
for file in $STAGED_FILES; do
if [ -f "$file" ]; then
echo "Validating $file..."
# Add validation command here
# validation-command "$file" || exit 1
fi
done
echo "✅ Validation passed"
exit 0
for file in $STAGED_FILES; do
if [ -f "$file" ]; then
echo "Validating $file..."
# Add validation command here
# validation-command "$file" || exit 1
fi
done
echo "✅ Validation passed"
exit 0
Hook Parameters and Environment
钩子参数与环境
Different hooks receive different parameters:
pre-commit: No parameters
不同的钩子会接收不同的参数:
pre-commit: 无参数
Access staged files via git commands
Access staged files via git commands
STAGED=$(git diff --cached --name-only)
**commit-msg**: Commit message file path
```bash
#!/bin/bash
COMMIT_MSG_FILE=$1
message=$(cat "$COMMIT_MSG_FILE")
pre-push: stdin with refs being pushed
bash
#!/bin/bash
while read local_ref local_sha remote_ref remote_sha; do
# Process each ref
done
post-checkout: prev HEAD, new HEAD, branch flag
bash
#!/bin/bash
PREV_HEAD=$1
NEW_HEAD=$2
IS_BRANCH=$3 # 1 for branch checkout, 0 for file checkout
STAGED=$(git diff --cached --name-only)
**commit-msg**: 提交信息文件路径
```bash
#!/bin/bash
COMMIT_MSG_FILE=$1
message=$(cat "$COMMIT_MSG_FILE")
pre-push: 标准输入包含要推送的引用信息
bash
#!/bin/bash
while read local_ref local_sha remote_ref remote_sha; do
# Process each ref
done
post-checkout: 前一个HEAD、新HEAD、分支标志
bash
#!/bin/bash
PREV_HEAD=$1
NEW_HEAD=$2
IS_BRANCH=$3 # 1 for branch checkout, 0 for file checkout
Environment Variables
环境变量
Git sets environment variables hooks can access:
- - Path to .git directory
- - Path to working directory
- - Path to index file
- , - Commit author
- , - Committer info
Test environment variables:
bash
#!/bin/bash
echo "Running $BASH_SOURCE"
set | grep GIT
echo "PWD is $PWD"
Git会设置钩子可以访问的环境变量:
- - .git目录的路径
- - 工作目录的路径
- - 索引文件的路径
- , - 提交作者信息
- , - 提交者信息
测试环境变量:
bash
#!/bin/bash
echo "Running $BASH_SOURCE"
set | grep GIT
echo "PWD is $PWD"
DO:
- Make hooks fast—developers run them frequently
- Exit early when no relevant files are staged
- Provide clear, actionable error messages
- Use visual indicators (✅ ❌ 🔍) for quick scanning
- Version-control hooks using
- Test hooks independently before integration
- Document hook behavior in README
- Use modular architecture for complex validation
- Make hooks easy to temporarily disable
DON'T:
- Perform long-running operations in pre-commit
- Block commits without clear explanation
- Hardcode file paths—use relative paths
- Assume dependencies are installed—check first
- Create infinite loops or complex recursion
- Mix multiple concerns in one hook script
- Skip error handling and validation
- Force hooks on team without consensus
建议:
- 钩子要快速——开发者会频繁运行它们
- 当没有相关文件暂存时提前退出
- 提供清晰、可操作的错误信息
- 使用视觉标识(✅ ❌ 🔍)方便快速查看
- 使用对钩子进行版本控制
- 集成前独立测试钩子
- 在README中记录钩子行为
- 对复杂验证使用模块化架构
- 让钩子可以轻松临时禁用
不建议:
- 在pre-commit中执行长时间运行的操作
- 无明确说明就阻止提交
- 硬编码文件路径——使用相对路径
- 假设依赖已安装——先进行检查
- 创建无限循环或复杂递归
- 在一个钩子脚本中混合多个关注点
- 跳过错误处理与验证
- 未经团队共识就强制使用钩子
Security Considerations
安全注意事项
Validate inputs: Never trust user input in hooks
Bad: Command injection risk
Bad: Command injection risk
git diff --cached --name-only | xargs some-command
git diff --cached --name-only | xargs some-command
Good: Proper quoting and validation
Good: Proper quoting and validation
git diff --cached --name-only | while read file; do
if [ -f "$file" ]; then
some-command "$file"
fi
done
**Check permissions**: Ensure hooks are executable by intended users only
```bash
chmod 755 .githooks/pre-commit # Owner write, others read+execute
Avoid secrets: Never hardcode credentials in hooks
git diff --cached --name-only | while read file; do
if [ -f "$file" ]; then
some-command "$file"
fi
done
**检查权限**: 确保钩子仅允许目标用户执行
```bash
chmod 755 .githooks/pre-commit # Owner write, others read+execute
避免敏感信息: 永远不要在钩子中硬编码凭据
Bad: Hardcoded token
Bad: Hardcoded token
Good: Read from environment
Good: Read from environment
API_TOKEN="${API_TOKEN:-$(cat ~/.api_token)}"
**Review third-party hooks**: Understand what scripts do before using them.
API_TOKEN="${API_TOKEN:-$(cat ~/.api_token)}"
**审查第三方钩子**: 使用前要理解脚本的功能。
Hook not running:
- Check execute permissions:
ls -l .githooks/pre-commit
- Verify config:
git config core.hooksPath
- Ensure file has no extension
- Check shebang line is correct:
Hook runs but fails unexpectedly:
- Run hook manually to see errors:
- Check exit codes: after running
- Verify dependencies are installed
- Test with minimal staged changes
- Add debug output: at start of script
Cannot commit:
- Read hook error message carefully
- Fix validation issues or unstage problematic files
- Temporarily disable hook if needed:
- Note: bypasses all hooks—use sparingly
Hooks not version-controlled:
- Ensure using , not
- Verify is committed:
- Check team members ran setup:
git config core.hooksPath
钩子未运行:
- 检查执行权限:
ls -l .githooks/pre-commit
- 验证配置:
git config core.hooksPath
- 确保文件没有扩展名
- 检查shebang行是否正确:
钩子运行但意外失败:
- 手动运行钩子查看错误:
- 检查退出码: 运行后执行
- 验证依赖是否已安装
- 使用最少的暂存变更进行测试
- 添加调试输出: 在脚本开头加入
无法提交:
- 仔细阅读钩子的错误信息
- 修复验证问题或取消暂存有问题的文件
- 必要时临时禁用钩子:
- 注意: 会绕过所有钩子——请谨慎使用
钩子未被版本控制:
- 确保使用,而非
- 验证已提交:
- 检查团队成员是否运行了设置命令:
git config core.hooksPath
Reference Documentation
参考文档
For detailed information on advanced topics:
- - Complete list of all Git hooks with parameters and use cases
references/server-side-hooks.md
- Server-side hooks for CI/CD and policy enforcement
references/advanced-patterns.md
- Complex validation patterns and techniques
references/ci-cd-integration.md
- Integrating hooks with continuous integration pipelines
如需了解高级主题的详细信息:
- - 所有Git钩子的完整列表,包含参数与使用场景
references/server-side-hooks.md
- 用于CI/CD与策略执行的服务端钩子
references/advanced-patterns.md
- 复杂验证模式与技巧
references/ci-cd-integration.md
- 将钩子与持续集成流水线集成
Example Implementations
示例实现
Working examples from this project:
examples/modular-pre-commit/
- Orchestrator pattern with hooks.d/ directory
examples/validate-bash.sh
- Bash syntax validation hook
examples/validate-skills.sh
- SKILL.md validation hook
- - Installation script for team setup
本项目中的可用示例:
examples/modular-pre-commit/
- 带有hooks.d/目录的编排器模式
examples/validate-bash.sh
- Bash语法验证钩子
examples/validate-skills.sh
- SKILL.md验证钩子
- - 团队设置用的安装脚本
Configure version-controlled hooks:
bash
git config core.hooksPath .githooks
Make hook executable:
bash
chmod +x .githooks/pre-commit
Test hook manually:
Bypass hooks temporarily:
bash
git commit --no-verify
Common hook skeleton:
bash
#!/bin/bash
set -e
echo "🔍 Running validation..."
配置可版本控制的钩子:
bash
git config core.hooksPath .githooks
使钩子可执行:
bash
chmod +x .githooks/pre-commit
手动测试钩子:
临时绕过钩子:
bash
git commit --no-verify
通用钩子骨架:
bash
#!/bin/bash
set -e
echo "🔍 Running validation..."
Validation logic here
Validation logic here
echo "✅ Validation passed"
exit 0
**Get staged files**:
```bash
git diff --cached --name-only --diff-filter=ACM
Validate and exit on failure:
echo "✅ Validation passed"
exit 0
**获取暂存文件**:
```bash
git diff --cached --name-only --diff-filter=ACM
验证失败则退出: