python项目使用pre-commit确保代码规范

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值