定义一个常用的Python项目Pre commit配置文件,配置了ruff作为代码格式检查工具。注意两个local插件,language 需要设置为 system,才能运行本地shell命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
default_language_version:
python: python3.11

default_install_hook_types: [pre-commit, pre-push, commit-msg]

default_stages: [commit]

exclude: |
(?x)^(
backend/.vscode/
)

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-json
- id: check-yaml
args: ["--allow-multiple-documents"]
- id: check-toml
- id: check-xml
- id: check-ast
- id: check-case-conflict
- id: check-docstring-first
- id: check-merge-conflict
- id: check-executables-have-shebangs
- id: check-added-large-files
args: ["--maxkb=1000"]
- id: detect-private-key
- id: mixed-line-ending
- id: end-of-file-fixer
- id: trailing-whitespace
- id: pretty-format-json
args: ["--autofix", "--no-sort-keys",]
- id: fix-byte-order-marker
- id: name-tests-test
args: ["--pytest-test-first"]
exclude: backend/app/tests/datas/user_data.py

# 代码格式化ruff,使用pyproject.toml中的配置
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.10
hooks:
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format

# 代码安全检测
- repo: https://github.com/PyCQA/bandit
rev: 1.7.9
hooks:
- id: bandit
exclude: ^backend/app/tests
args: ["--severity-level=medium"]

# 检测硬编码的password,key,token等内容
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4
hooks:
- id: gitleaks

# 在提交前使用系统pytest进行测试,仅测试标记为fast的单元测试.
# 因pytest未找到单元测试返回码为5,需要安装pip install pytest-custom_exit_code进行调整
- repo: local
hooks:
- id: tests
name: run tests
entry: pytest -v -m fast --suppress-no-test-exit-code
language: system
always_run: true
pass_filenames: false
types: [python]
stages: [commit]

# 在push到服务器前使用系统pytest进行测试
- repo: local
hooks:
- id: tests
name: run all tests
entry: pytest -x --suppress-no-test-exit-code
language: system
types: [python]
stages: [push]

# 检测提交信息格式化
- repo: https://github.com/compilerla/conventional-pre-commit
rev: v3.2.0
hooks:
- id: conventional-pre-commit
stages: [commit-msg]
args: ["--strict"]