git-hooks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git 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
.git/hooks/
by default, but can be version-controlled using
core.hooksPath
configuration.
Git hooks是Git在仓库发生特定事件时自动运行的可执行脚本。它们可以帮助您:
  • 在提交进入仓库前强制保证代码质量
  • 运行自动化测试,尽早发现问题
  • 验证提交信息,保持标准一致
  • 防止意外的破坏性操作,比如强制推送
  • 在推送事件触发CI/CD工作流
  • 为发布自动化版本控制与打标签
默认情况下,Hooks存放在
.git/hooks/
目录中,但可以通过
core.hooksPath
配置进行版本控制。

Core Concepts

核心概念

Hook Types

钩子类型

Client-side hooks (run on developer machines):
  • pre-commit
    - Before commit is created, validate staged changes
  • prepare-commit-msg
    - Populate commit message template
  • commit-msg
    - Validate commit message format
  • post-commit
    - Notification after successful commit
  • pre-push
    - Before pushing to remote, run tests
  • post-checkout
    - After checkout, clean up working directory
  • pre-rebase
    - Before rebasing, check for conflicts
Server-side hooks (run on remote repository):
  • pre-receive
    - Before accepting pushed refs, enforce policies
  • update
    - Like pre-receive, but runs per branch
  • post-receive
    - After successful push, trigger CI/CD
客户端钩子(在开发者机器上运行):
  • pre-commit
    - 在创建提交前,验证暂存的变更
  • prepare-commit-msg
    - 填充提交信息模板
  • commit-msg
    - 验证提交信息格式
  • post-commit
    - 提交成功后发送通知
  • pre-push
    - 推送到远程仓库前,运行测试
  • post-checkout
    - 切换分支后,清理工作目录
  • pre-rebase
    - 变基前,检查冲突
服务端钩子(在远程仓库上运行):
  • pre-receive
    - 接受推送的引用前,执行策略检查
  • update
    - 类似pre-receive,但针对每个分支运行
  • post-receive
    - 推送成功后,触发CI/CD

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-commit

Essential Workflows

关键工作流

Setting Up Version-Controlled Hooks

设置可版本控制的钩子

Git doesn't version-control
.git/hooks/
by default. Use
core.hooksPath
to enable team-wide hooks:
1. Create hooks directory in repository:
bash
mkdir .githooks
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
.githooks/
directory for working examples.
Git默认不会对
.git/hooks/
进行版本控制。使用
core.hooksPath
来启用团队共享的钩子:
1. 在仓库中创建钩子目录:
bash
mkdir .githooks
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
本项目采用此模式。请查看
.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:
bash
undefined
问题: 单个钩子文件包含多个验证逻辑后会变得复杂。
解决方案: 使用编排器模式,发现并运行模块化的钩子脚本。
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. 添加独立的验证脚本:
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
undefined
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
undefined

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
undefined
npm test || { echo "❌ Tests failed. Push aborted." exit 1 }
echo "✅ All tests passed" exit 0
undefined

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系统。您可以为自己的项目遵循此实现模式。

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                     # Documentation

Installation

安装

Automated setup:
bash
./setup-hooks.sh
This configures
git config core.hooksPath .githooks
automatically.
自动化设置:
bash
./setup-hooks.sh
该脚本会自动配置
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
15-validate-json.sh
between 10 and 20).
模块化钩子采用以下命名模式:
the-perfect-developer-base-collection-<number>-<description>.sh
  • 前缀: 项目/团队标识符
  • 数字: 执行顺序(以10为增量:10、20、30...)
  • 描述: 钩子的验证内容
以10为增量的数字允许在现有钩子之间插入新钩子(例如,在10和20之间添加
15-validate-json.sh
)。

Testing Individual Hooks

测试独立钩子

Run hooks independently for testing:
bash
undefined
可以独立运行钩子进行测试:
bash
undefined

Test 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}
undefined
mv .githooks/hooks.d/20-validate-skills.sh{,.disabled}
undefined

Hook 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
undefined
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
undefined

Hook Parameters and Environment

钩子参数与环境

Common Parameters

常见参数

Different hooks receive different parameters:
pre-commit: No parameters
bash
#!/bin/bash
不同的钩子会接收不同的参数:
pre-commit: 无参数
bash
#!/bin/bash

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:
  • GIT_DIR
    - Path to .git directory
  • GIT_WORK_TREE
    - Path to working directory
  • GIT_INDEX_FILE
    - Path to index file
  • GIT_AUTHOR_NAME
    ,
    GIT_AUTHOR_EMAIL
    - Commit author
  • GIT_COMMITTER_NAME
    ,
    GIT_COMMITTER_EMAIL
    - Committer info
Test environment variables:
bash
#!/bin/bash
echo "Running $BASH_SOURCE"
set | grep GIT
echo "PWD is $PWD"
Git会设置钩子可以访问的环境变量:
  • GIT_DIR
    - .git目录的路径
  • 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
undefined

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
bash
undefined
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
避免敏感信息: 永远不要在钩子中硬编码凭据
bash
undefined

Bad: 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:
  1. Check execute permissions:
    ls -l .githooks/pre-commit
  2. Verify
    core.hooksPath
    config:
    git config core.hooksPath
  3. Ensure file has no
    .sample
    extension
  4. Check shebang line is correct:
    #!/bin/bash
Hook runs but fails unexpectedly:
  1. Run hook manually to see errors:
    .githooks/pre-commit
  2. Check exit codes:
    echo $?
    after running
  3. Verify dependencies are installed
  4. Test with minimal staged changes
  5. Add debug output:
    set -x
    at start of script
Cannot commit:
  1. Read hook error message carefully
  2. Fix validation issues or unstage problematic files
  3. Temporarily disable hook if needed:
    git commit --no-verify
  4. Note:
    --no-verify
    bypasses all hooks—use sparingly
Hooks not version-controlled:
  1. Ensure using
    core.hooksPath
    , not
    .git/hooks/
  2. Verify
    .githooks/
    is committed:
    git ls-files .githooks/
  3. Check team members ran setup:
    git config core.hooksPath
钩子未运行:
  1. 检查执行权限:
    ls -l .githooks/pre-commit
  2. 验证
    core.hooksPath
    配置:
    git config core.hooksPath
  3. 确保文件没有
    .sample
    扩展名
  4. 检查shebang行是否正确:
    #!/bin/bash
钩子运行但意外失败:
  1. 手动运行钩子查看错误:
    .githooks/pre-commit
  2. 检查退出码: 运行后执行
    echo $?
  3. 验证依赖是否已安装
  4. 使用最少的暂存变更进行测试
  5. 添加调试输出: 在脚本开头加入
    set -x
无法提交:
  1. 仔细阅读钩子的错误信息
  2. 修复验证问题或取消暂存有问题的文件
  3. 必要时临时禁用钩子:
    git commit --no-verify
  4. 注意:
    --no-verify
    会绕过所有钩子——请谨慎使用
钩子未被版本控制:
  1. 确保使用
    core.hooksPath
    ,而非
    .git/hooks/
  2. 验证
    .githooks/
    已提交:
    git ls-files .githooks/
  3. 检查团队成员是否运行了设置命令:
    git config core.hooksPath

Additional Resources

额外资源

Reference Documentation

参考文档

For detailed information on advanced topics:
  • references/hook-types.md
    - 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
如需了解高级主题的详细信息:
  • references/hook-types.md
    - 所有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
  • examples/setup-hooks.sh
    - Installation script for team setup
本项目中的可用示例:
  • examples/modular-pre-commit/
    - 带有hooks.d/目录的编排器模式
  • examples/validate-bash.sh
    - Bash语法验证钩子
  • examples/validate-skills.sh
    - SKILL.md验证钩子
  • examples/setup-hooks.sh
    - 团队设置用的安装脚本

External Resources

外部资源

Official Git documentation:
Comprehensive tutorials:
官方Git文档:
综合教程:

Quick Reference

快速参考

Configure version-controlled hooks:
bash
git config core.hooksPath .githooks
Make hook executable:
bash
chmod +x .githooks/pre-commit
Test hook manually:
bash
.githooks/pre-commit
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
.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:
bash
command || exit 1
echo "✅ Validation passed" exit 0

**获取暂存文件**:
```bash
git diff --cached --name-only --diff-filter=ACM
验证失败则退出:
bash
command || exit 1