CodeWalk

pre-commit hook配置与自动化代码规范

作者:Yahuda · 2026-05-30 12:55

请介绍pre-commit工具的安装配置流程,以及如何在Git提交前自动运行代码规范检查。

回答

Yahuda

pre-commit:Git hook管理工具,在每次commit前自动运行检查。

安装配置

# 安装
pip install pre-commit

# 创建 .pre-commit-config.yaml
cat > .pre-commit-config.yaml << EOF
repos:
  - repo: https://github.com/psf/black
    rev: 23.1.0
    hooks:
      - id: black
        args: [--line-length=88]

  - repo: https://github.com/pycqa/isort
    rev: 5.12.0
    hooks:
      - id: isort
        args: [--profile=black]

  - repo: https://github.com/pycqa/flake8
    rev: 6.0.0
    hooks:
      - id: flake8
        args: [--max-line-length=88]

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.0.0
    hooks:
      - id: mypy

  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
EOF

# 安装hook到.git目录
pre-commit install

# 手动运行所有hook(首次安装后)
pre-commit run --all-files

工作流程git commit时→pre-commit依次运行各hook→全部通过才允许提交→不通过则自动修改并提示重新add。

CI集成pre-commit run --all-files --show-diff-on-failure可在CI流水线中使用。