Python 项目之 pre-commit

  • 项目要使用git提交时,在调用 git commit 命令时,会自动执行某些脚本检测代码 pre-commit
  • 如果检测出错,则阻止 commit 代码, 也就无法 push

简单使用

在本地仓库的项目根目录

cp .git/hooks/pre-commit.sample .git/hooks/pre-commit

pip install pre-commit

pre-commit install

然后在项目根目录中 创建

.pre-commit-config.yaml 文件

添加以下内容(只想进行检查,不想被格式化的话,删除6-10行

第一个是检查git冲突的,第二个自动 pep8 的 re-format 还有 flake8可以自定义一些配置

repos:

- repo: https://github.com/pre-commit/pre-commit-hooks

rev: v2.1.0

hooks:

- id: check-merge-conflict

- repo: https://github.com/psf/black

rev: stable

hooks:

- id: black

language_version: python3.7

- repo: https://github.com/pre-commit/pre-commit-hooks

rev: v2.1.0

hooks:

- id: flake8

如果想自定义flake8配置,在项目根目录中创建 .flake8 文件

[flake8]

ignore = C901, W503, F405, E203

# C901: is too complex

# W503: line break before binary operator

# F405: may be undefined, or defined from star imports

exclude =

*.pyc,

.git,

__pycache__,

# 每行长度可以自定义啦 哈哈哈

max-line-length = 120

# 代码条件复杂度检查

max-complexity = 12

format = pylint

show_source = True

statistics = True

count = Tru

# 让 Python 代码更易维护的七种武器

https://www.cnblogs.com/bonelee/p/11045196.html

# pre-commit 官方

https://pre-commit.com/hooks.html

暂时只有这两个简单的功能, 还有些其他的,暂未研究

一些场景

  • 非空行结尾
  • re-format 以及一些check

建议在新项目中使用

  • 如果在旧的项目中使用的话,很容易因为一开始不熟悉,然后在单次提交多个文件时,被pre-commit 做了太多改动,而一头雾水,搞了半天也提交不了
  • 如果实在受不了了的话,可以通过     git commit --no-verify -m      提交 //可以跳过代码检查

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐