Skip to content

Git Hook

Automating workflows 使用 Git Hook — pre-提交, pre-推送, and 提交-msg scripts.

你将学到

  • 什么 Git Hook 是 and 哪里它们 live
  • 常见 Hook: pre-提交, pre-推送, 提交-msg
  • 编写 Hook scripts 到 enforce quality 标准
  • Using Hook 框架如 Husky and pre-提交

概念讲解

What Are Git Hooks?

Git hooks are scripts that Git executes automatically at specific points in the Git workflow. They let you enforce code quality, run tests, format code, and prevent bad commits — all without manual intervention.

Hooks live in the .git/Hook/ directory of every repository. They are shell scripts (or any executable) that run when the corresponding Git event occurs.

ls .git/hooks/
# pre-commit.sample
# pre-push.sample
# commit-msg.sample
# ...

The .sample files are examples. To activate a hook, remove the .sample extension and make the script executable.

Common Hooks

pre-commit

Runs before a commit is created. Use it to:

  • Run linters and formatters
  • Check for debug code (console.log, print)
  • Validate file sizes
  • Exit non-zero to block the commit
# .git/hooks/pre-commit
#!/bin/sh
# Run the linter
npm run lint
if [ $? -ne 0 ]; then
  echo "Linting 失败. 提交 blocked."
  exit 1
fi

pre-push

Runs before a push to the remote. Use it to:

  • Run the full test suite
  • Check that the branch is up to date
  • Exit non-zero to block the push
# .git/hooks/pre-push
#!/bin/sh
# Run tests before pushing
npm test
if [ $? -ne 0 ]; then
  echo "测试失败. 推送 blocked."
  exit 1
fi

commit-msg

Runs after the commit message is written. Use it to:

  • Enforce commit message conventions (Conventional Commits)
  • Check message length
  • Exit non-zero to reject the message
# .git/hooks/commit-msg
#!/bin/sh
# Enforce Conventional Commits format
pattern="^(feat|fix|docs|样式|refactor|测试|chore): .+"
if ! grep -qP "$模式" "$1"; then
  echo "提交消息必须 follow Conventional 提交: '类型: 消息'"
  exit 1
fi

Other Useful Hooks

  • pre-合并-提交 — runs before a merge commit is created
  • post-提交 — runs after a commit (e.g., notifications)
  • pre-rebase — runs before a rebase (can block it)
  • prepare-提交-msg — modify the commit message before the editor opens (e.g., add branch name)

The Problem with Native Hooks

Native hooks in .git/Hook/ have a problem: they are not version-controlled. The .git folder is not committed, so hooks are not shared with your team. Each developer must set them up manually.

Hook Frameworks

To solve this, use a hook framework that installs hooks from a config file in your repository:

Husky (JavaScript/Node projects)

npm install --save-dev husky
npx husky init

Create hooks in the husky/ directory:

# husky/pre-commit
npm run lint

Configure in 包.JSON or .huskyrc:

{
  "husky": {
    "Hook": {
      "pre-commit": "npm 运行 lint",
      "pre-push": "npm 测试"
    }
  }
}

pre-commit (Python/multi-language)

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
  - repo: https://github.com/pycqa/flake8
    rev: 7.0.0
    hooks:
      - id: flake8

Install with pip 安装 pre-提交 and run pre-提交 安装.

Best Practices for Hooks

  • Keep hooks fast — developers run them on every commit. If they take 30 seconds, people will bypass them.
  • Make hooks informative — clear error messages explain what failed and how to fix it.
  • Auto-fix when possible — run formatters that fix code, not just linters that report problems.
  • Do not block on style nits in pre-commit — use CI for thorough checks; hooks should catch only critical issues.
  • Document your hooks — so new team members understand what is being enforced.

示例代码

              # --- Set up a native pre-commit hook ---
cd .git/hooks
cp pre-commit.sample pre-commit
chmod +x pre-commit

# Write the hook script
cat > pre-commit << 'EOF'
#!/bin/sh
# Block commits with console.log statements
if git diff --cached | grep -q "console.log"; then
  echo "ERROR: Remove console.log before committing."
  echo "Found in:"
  git diff --cached --name-only | xargs grep -l "console.log"
  exit 1
fi

# Run the linter
npm run lint
EOF

# --- Set up a commit-msg hook for Conventional Commits ---
cat > .git/hooks/commit-msg << 'EOF'
#!/bin/sh
pattern="^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\(.+\))?: .+"
if ! grep -qP "$pattern" "$1"; then
  echo "Commit message must follow Conventional Commits format:"
  echo "  type(scope): description"
  echo "Types: feat, fix, docs, style, refactor, test, chore, perf, ci, build, revert"
  exit 1
fi
EOF
chmod +x .git/hooks/commit-msg

# --- Set up Husky (Node.js project) ---
npm install --save-dev husky lint-staged
npx husky init
echo "npm run lint" > .husky/pre-commit
echo "npm test" > .husky/pre-push

# package.json lint-staged config:
# "lint-staged": {
#   "*.{js,ts}": ["eslint --fix", "prettier --write"]
# }

# --- Set up pre-commit framework (Python project) ---
pip install pre-commit
cat > .pre-commit-config.yaml << 'EOF'
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-added-large-files
EOF
pre-commit install

# --- List available hooks ---
ls .git/hooks/*.sample
            

Shows 设置 native pre-提交 and 提交-msg Hook, using Husky for 节点.js 项目使用 lint-staged, and pre-提交框架 for Python/multi-language 项目. 提交-msg Hook enforces Conventional 提交格式. Hook 框架解决 problem 的 sharing Hook 使用你的 team.

动手试一试

  • CI/CD YAML Generator

    Hook 运行 locally; CI 运行 in cloud — generate 两者都 for defense in 深度.

  • .gitignore Generator

    Keep Hook dependencies and 配置 files properly ignored or committed.

常见错误

错误写法

编写 Hook 那个是 也慢 and developers 开始 bypassing 它们使用 --否-验证

正确做法

Keep pre-提交 Hook under 少数 seconds. 运行仅 快检查 (lint, 格式) in pre-提交; 运行慢 检查 (完整测试 suite) in pre-推送 or CI. 如果 Hook takes 30 seconds, developers 将 use git 提交 --否-验证到 bypass 它, defeating purpose. Use lint-staged 到运行检查仅 on 更改 files.

错误写法

设置 Hook in .git/Hook/ and expecting 它们到 是 shared 使用 team

正确做法

.git directory 是不 version-controlled, 所以 native Hook 是不 shared. Use Hook 框架如 Husky (节点.js) or pre-提交 (Python) 那个存储 Hook 配置 in 你的仓库. Team 成员运行 one 安装 command 到设置所有 Hook. Document 设置 in 你的 README.

相关速查表

练习 Git Hook

1 个练习

练习 Git Hook

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误