1. 安装pre-commit (建议直接使用pipx全局安装,无需每个项目单独安装)
pipx install pre-commit
2. 模板:
一、需要兼容3.10以下版本的:
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.11
repos:
- repo: git@github.com:pre-commit/pre-commit-hooks
# https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 # Use the ref you want to point at
hooks:
- id: check-added-large-files
- id: check-toml
- id: check-yaml
args: [ --unsafe ]
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: git@github.com:astral-sh/ruff-pre-commit
# https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.2 # Ruff version.
hooks:
# Run the linter. 导入排序、删除多余导入、pep8规范检查
- id: ruff
args: [ --fix, --extend-select=I ]
# Run the formatter. 格式化代码
- id: ruff-format
二、使用Python3.10+的
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.11
repos:
- repo: git@github.com:pre-commit/pre-commit-hooks
# https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 # Use the ref you want to point at
hooks:
- id: check-added-large-files
- id: check-toml
- id: check-yaml
args: [ --unsafe ]
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: local
hooks:
- id: format
name: check and reformat by ruff/mypy
entry: poetry run fast lint
language: system
types: [python]
三、需要使用本地shell脚本的
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.11
repos:
- repo: git@github.com:pre-commit/pre-commit-hooks
# https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 # Use the ref you want to point at
hooks:
- id: check-added-large-files
- id: check-toml
- id: check-yaml
args: [ --unsafe ]
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: local
hooks:
- id: check
name: check by ruff/mypy
entry: ./scripts/check.sh
language: script
3. 检查所有文件
pre-commit run --all-files