如何给 git 仓库安装 pre-commit hook

165 阅读2分钟

给 git 仓库安装 pre-commit hook 有什么好处?

给 python 仓库安装 pre-commit hook 可以有这些好处:

  • 使用 blackruff format 等工具格式化代码,强制大家使用一致的代码风格
  • 使用 flake8ruff check 等静态检查代码的 linter 工具,阻止有问题的代码合入仓库

如何给 git 仓库安装 pre-commit hook?

使用 pre-commit 软件包安装 pre-commit hook,并修改配置文件。

step 1:安装 pre-commit 软件包
pip install pre-commit

step 2:添加 pre-commit 配置文件
touch .pre-commit-config.yaml
配置文件的内容见下文。

step 3:安装 pre-commit hook
pre-commit install

pre-commit hook 配置

配置文件是 git 仓库目录下的 .pre-commit-config.yaml

例子 1:使用 black

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
    - id: end-of-file-fixer
      types: [python]
    - id: trailing-whitespace
      types: [python]
    - id: check-yaml
    - id: check-merge-conflict

  # 用 black 自动格式化代码风格
  # Using this mirror lets us use mypyc-compiled black, which is about 2x faster
  - repo: https://github.com/psf/black-pre-commit-mirror
    rev: 25.1.0
    hooks:
    - id: black

  - repo: https://github.com/pycqa/isort
    rev: 6.0.1
    hooks:
    - id: isort
      args: ["--profile", "black", "--filter-files"]

#  # 用 flake8 检查潜在的问题
#  - repo: https://github.com/PyCQA/flake8
#    rev: 7.0.0
#    hooks:
#    - id: flake8
#      args:
#      - --ignore=E501

例子 2:使用 ruff

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
    - id: end-of-file-fixer
      types: [python]
    - id: trailing-whitespace
      types: [python]
    - id: check-yaml
    - id: check-merge-conflict

- repo: https://github.com/astral-sh/ruff-pre-commit
  # Ruff version.
  rev: v0.11.2
  hooks:
    # Run the linter.
    - id: ruff
      args: [ --fix ]
      types: [python]
    # Run the formatter.
    - id: ruff-format
      types: [python]

golang 版本

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
    - id: check-yaml
    - id: check-merge-conflict

  # TODO: 后续把 formatter 都集成到 golangci-lint fmt
  - repo: https://github.com/tekwizely/pre-commit-golang
    rev: master
    hooks:
    - id: go-mod-tidy-repo
    - id: go-fumpt-repo
      args: ['-w', '-l']

  - repo: https://github.com/segmentio/golines
    rev: v0.12.2
    hooks:
    - id: golines

  - repo: https://github.com/golangci/golangci-lint
    rev: v2.0.2
    hooks:
    - id: golangci-lint
      alias: linter
    - id: golangci-lint-config-verify

手动执行 pre-commit

我们可以不必等 git commit 时才执行 pre-commit ,可以选择手动执行全部或部分模块。

# 手动对所有的文件执行hooks,新增hook的时候可以执行,使得代码均符合规范。直接执行该指令则无需等到pre-commit阶段再触发hooks
pre-commit run --all-files

# 执行特定hooks
pre-commit run <hook_id> 
pre-commit run <hook_id> --all-files

# 将所有的hook更新到最新的版本/tag
pre-commit autoupdate