git-hooks
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Hooks
Git Hooks
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/core.hooksPathGit hooks是Git在仓库发生特定事件时自动运行的可执行脚本。它们可以帮助您:
- 在提交进入仓库前强制保证代码质量
- 运行自动化测试,尽早发现问题
- 验证提交信息,保持标准一致
- 防止意外的破坏性操作,比如强制推送
- 在推送事件触发CI/CD工作流
- 为发布自动化版本控制与打标签
默认情况下,Hooks存放在目录中,但可以通过配置进行版本控制。
.git/hooks/core.hooksPathCore Concepts
核心概念
Hook Types
钩子类型
Client-side hooks (run on developer machines):
- - Before commit is created, validate staged changes
pre-commit - - Populate commit message template
prepare-commit-msg - - Validate commit message format
commit-msg - - Notification after successful commit
post-commit - - Before pushing to remote, run tests
pre-push - - After checkout, clean up working directory
post-checkout - - Before rebasing, check for conflicts
pre-rebase
Server-side hooks (run on remote repository):
- - Before accepting pushed refs, enforce policies
pre-receive - - Like pre-receive, but runs per branch
update - - After successful push, trigger CI/CD
post-receive
客户端钩子(在开发者机器上运行):
- - 在创建提交前,验证暂存的变更
pre-commit - - 填充提交信息模板
prepare-commit-msg - - 验证提交信息格式
commit-msg - - 提交成功后发送通知
post-commit - - 推送到远程仓库前,运行测试
pre-push - - 切换分支后,清理工作目录
post-checkout - - 变基前,检查冲突
pre-rebase
服务端钩子(在远程仓库上运行):
- - 接受推送的引用前,执行策略检查
pre-receive - - 类似pre-receive,但针对每个分支运行
update - - 推送成功后,触发CI/CD
post-receive
Hook Lifecycle
钩子生命周期
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-commitEssential Workflows
关键工作流
Setting Up Version-Controlled Hooks
设置可版本控制的钩子
Git doesn't version-control by default. Use to enable team-wide hooks:
.git/hooks/core.hooksPath1. Create hooks directory in repository:
bash
mkdir .githooks2. Configure Git to use custom hooks path:
bash
git config core.hooksPath .githooks3. 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 .githooksThis project follows this pattern. See directory for working examples.
.githooks/Git默认不会对进行版本控制。使用来启用团队共享的钩子:
.git/hooks/core.hooksPath1. 在仓库中创建钩子目录:
bash
mkdir .githooks2. 配置Git使用自定义钩子路径:
bash
git config core.hooksPath .githooks3. 将钩子加入版本控制:
bash
git add .githooks/
git commit -m "Add version-controlled git hooks"4. 团队成员克隆仓库后运行:
bash
git config core.hooksPath .githooks本项目采用此模式。请查看目录获取可用示例。
.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-commit2. Add validation logic:
bash
#!/bin/bash
set -e
echo "🔍 Validating bash scripts..."使用场景: 提交前验证bash脚本。
1. 创建钩子文件:
bash
touch .githooks/pre-commit
chmod +x .githooks/pre-commit2. 添加验证逻辑:
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 failurefor 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.d2. 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 03. Add individual validation scripts:
bash
undefined问题: 单个钩子文件包含多个验证逻辑后会变得复杂。
解决方案: 使用编排器模式,发现并运行模块化的钩子脚本。
1. 创建hooks.d/目录:
bash
mkdir .githooks/hooks.d2. 在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 03. 添加独立的验证脚本:
bash
undefined.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
undefinedPATTERN="^(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
undefinedRunning 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
undefinednpm test || {
echo "❌ Tests failed. Push aborted."
exit 1
}
echo "✅ All tests passed"
exit 0
undefinedPreventing 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 0Project-Specific Implementation
项目特定实现
This repository implements a production-ready Git hooks system. Follow this implementation pattern for your projects.
本仓库实现了一套生产可用的Git hooks系统。您可以为自己的项目遵循此实现模式。
Directory Structure
目录结构
.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 # DocumentationInstallation
安装
Automated setup:
bash
./setup-hooks.shThis configures automatically.
git config core.hooksPath .githooks自动化设置:
bash
./setup-hooks.sh该脚本会自动配置。
git config core.hooksPath .githooksHook 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).
15-validate-json.sh模块化钩子采用以下命名模式:
the-perfect-developer-base-collection-<number>-<description>.sh- 前缀: 项目/团队标识符
- 数字: 执行顺序(以10为增量:10、20、30...)
- 描述: 钩子的验证内容
以10为增量的数字允许在现有钩子之间插入新钩子(例如,在10和20之间添加)。
15-validate-json.shTesting Individual Hooks
测试独立钩子
Run hooks independently for testing:
bash
undefined可以独立运行钩子进行测试:
bash
undefinedTest single hook
Test single hook
.githooks/hooks.d/10-validate-bash.sh
.githooks/hooks.d/10-validate-bash.sh
Test orchestrator
Test orchestrator
.githooks/pre-commit
.githooks/pre-commit
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}
undefinedmv .githooks/hooks.d/20-validate-skills.sh{,.disabled}
undefinedHook Template
钩子模板
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
undefinedfor 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
undefinedHook Parameters and Environment
钩子参数与环境
Common Parameters
常见参数
Different hooks receive different parameters:
pre-commit: No parameters
bash
#!/bin/bash不同的钩子会接收不同的参数:
pre-commit: 无参数
bash
#!/bin/bashAccess 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
donepost-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 checkoutSTAGED=$(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
donepost-checkout: 前一个HEAD、新HEAD、分支标志
bash
#!/bin/bash
PREV_HEAD=$1
NEW_HEAD=$2
IS_BRANCH=$3 # 1 for branch checkout, 0 for file checkoutEnvironment Variables
环境变量
Git sets environment variables hooks can access:
- - Path to .git directory
GIT_DIR - - Path to working directory
GIT_WORK_TREE - - Path to index file
GIT_INDEX_FILE - ,
GIT_AUTHOR_NAME- Commit authorGIT_AUTHOR_EMAIL - ,
GIT_COMMITTER_NAME- Committer infoGIT_COMMITTER_EMAIL
Test environment variables:
bash
#!/bin/bash
echo "Running $BASH_SOURCE"
set | grep GIT
echo "PWD is $PWD"Git会设置钩子可以访问的环境变量:
- - .git目录的路径
GIT_DIR - - 工作目录的路径
GIT_WORK_TREE - - 索引文件的路径
GIT_INDEX_FILE - ,
GIT_AUTHOR_NAME- 提交作者信息GIT_AUTHOR_EMAIL - ,
GIT_COMMITTER_NAME- 提交者信息GIT_COMMITTER_EMAIL
测试环境变量:
bash
#!/bin/bash
echo "Running $BASH_SOURCE"
set | grep GIT
echo "PWD is $PWD"Best Practices
最佳实践
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
core.hooksPath - 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
建议:
- 钩子要快速——开发者会频繁运行它们
- 当没有相关文件暂存时提前退出
- 提供清晰、可操作的错误信息
- 使用视觉标识(✅ ❌ 🔍)方便快速查看
- 使用对钩子进行版本控制
core.hooksPath - 集成前独立测试钩子
- 在README中记录钩子行为
- 对复杂验证使用模块化架构
- 让钩子可以轻松临时禁用
不建议:
- 在pre-commit中执行长时间运行的操作
- 无明确说明就阻止提交
- 硬编码文件路径——使用相对路径
- 假设依赖已安装——先进行检查
- 创建无限循环或复杂递归
- 在一个钩子脚本中混合多个关注点
- 跳过错误处理与验证
- 未经团队共识就强制使用钩子
Security Considerations
安全注意事项
Validate inputs: Never trust user input in hooks
bash
undefined验证输入: 永远不要信任钩子中的用户输入
bash
undefinedBad: 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+executeAvoid secrets: Never hardcode credentials in hooks
bash
undefinedgit 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避免敏感信息: 永远不要在钩子中硬编码凭据
bash
undefinedBad: Hardcoded token
Bad: Hardcoded token
API_TOKEN="secret123"
API_TOKEN="secret123"
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)}"
**审查第三方钩子**: 使用前要理解脚本的功能。Troubleshooting
故障排除
Hook not running:
- Check execute permissions:
ls -l .githooks/pre-commit - Verify config:
core.hooksPathgit config core.hooksPath - Ensure file has no extension
.sample - Check shebang line is correct:
#!/bin/bash
Hook runs but fails unexpectedly:
- Run hook manually to see errors:
.githooks/pre-commit - Check exit codes: after running
echo $? - Verify dependencies are installed
- Test with minimal staged changes
- Add debug output: at start of script
set -x
Cannot commit:
- Read hook error message carefully
- Fix validation issues or unstage problematic files
- Temporarily disable hook if needed:
git commit --no-verify - Note: bypasses all hooks—use sparingly
--no-verify
Hooks not version-controlled:
- Ensure using , not
core.hooksPath.git/hooks/ - Verify is committed:
.githooks/git ls-files .githooks/ - Check team members ran setup:
git config core.hooksPath
钩子未运行:
- 检查执行权限:
ls -l .githooks/pre-commit - 验证配置:
core.hooksPathgit config core.hooksPath - 确保文件没有扩展名
.sample - 检查shebang行是否正确:
#!/bin/bash
钩子运行但意外失败:
- 手动运行钩子查看错误:
.githooks/pre-commit - 检查退出码: 运行后执行
echo $? - 验证依赖是否已安装
- 使用最少的暂存变更进行测试
- 添加调试输出: 在脚本开头加入
set -x
无法提交:
- 仔细阅读钩子的错误信息
- 修复验证问题或取消暂存有问题的文件
- 必要时临时禁用钩子:
git commit --no-verify - 注意: 会绕过所有钩子——请谨慎使用
--no-verify
钩子未被版本控制:
- 确保使用,而非
core.hooksPath.git/hooks/ - 验证已提交:
.githooks/git ls-files .githooks/ - 检查团队成员是否运行了设置命令:
git config core.hooksPath
Additional Resources
额外资源
Reference Documentation
参考文档
For detailed information on advanced topics:
- - Complete list of all Git hooks with parameters and use cases
references/hook-types.md - - Server-side hooks for CI/CD and policy enforcement
references/server-side-hooks.md - - Complex validation patterns and techniques
references/advanced-patterns.md - - Integrating hooks with continuous integration pipelines
references/ci-cd-integration.md
如需了解高级主题的详细信息:
- - 所有Git钩子的完整列表,包含参数与使用场景
references/hook-types.md - - 用于CI/CD与策略执行的服务端钩子
references/server-side-hooks.md - - 复杂验证模式与技巧
references/advanced-patterns.md - - 将钩子与持续集成流水线集成
references/ci-cd-integration.md
Example Implementations
示例实现
Working examples from this project:
- - Orchestrator pattern with hooks.d/ directory
examples/modular-pre-commit/ - - Bash syntax validation hook
examples/validate-bash.sh - - SKILL.md validation hook
examples/validate-skills.sh - - Installation script for team setup
examples/setup-hooks.sh
本项目中的可用示例:
- - 带有hooks.d/目录的编排器模式
examples/modular-pre-commit/ - - Bash语法验证钩子
examples/validate-bash.sh - - SKILL.md验证钩子
examples/validate-skills.sh - - 团队设置用的安装脚本
examples/setup-hooks.sh
External Resources
外部资源
Official Git documentation:
- Git Hooks Documentation - Complete reference
- Git Hooks Guide - Community-maintained guide
Comprehensive tutorials:
- Kinsta Git Hooks Guide - Advanced techniques
- Atlassian Git Hooks Tutorial - Conceptual overview
官方Git文档:
- Git Hooks Documentation - 完整参考
- Git Hooks Guide - 社区维护的指南
综合教程:
- Kinsta Git Hooks Guide - 高级技巧
- Atlassian Git Hooks Tutorial - 概念概述
Quick Reference
快速参考
Configure version-controlled hooks:
bash
git config core.hooksPath .githooksMake hook executable:
bash
chmod +x .githooks/pre-commitTest hook manually:
bash
.githooks/pre-commitBypass hooks temporarily:
bash
git commit --no-verifyCommon hook skeleton:
bash
#!/bin/bash
set -e
echo "🔍 Running validation..."配置可版本控制的钩子:
bash
git config core.hooksPath .githooks使钩子可执行:
bash
chmod +x .githooks/pre-commit手动测试钩子:
bash
.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=ACMValidate and exit on failure:
bash
command || exit 1echo "✅ Validation passed"
exit 0
**获取暂存文件**:
```bash
git diff --cached --name-only --diff-filter=ACM验证失败则退出:
bash
command || exit 1