You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置pre-commit仅在push时运行pytest,其余钩子仅在commit执行?

实现仅在Push时运行Pytest的Pre-Commit配置方案

要实现仅在push时运行pytest,其他钩子只在commit时执行,只需调整全局默认执行阶段,保留已有pytest钩子的专属配置即可,具体操作如下:

1. 修改全局默认阶段

把配置开头的default_stages: [commit, push]改成default_stages: [commit]——这个全局设置会让所有未单独指定stages的钩子(比如flake8、black、trailing-whitespace等)仅在commit代码时触发,不会在push阶段运行。

2. 保留Pytest钩子的专属配置

你已经在local仓库的pytest-check钩子中设置了stages: [push],这个配置会覆盖全局默认规则,确保pytest只在push阶段执行,无需修改。

修改后的完整配置

default_stages: [commit]
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files
        args: [ "--maxkb=120000" ]
    -   id: check-json
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.3.0
    hooks:
    - id: flake8
-   repo: https://github.com/psf/black
    rev: 22.3.0
    hooks:
    -   id: black
        language_version: python3.9
-   repo: https://github.com/pre-commit/mirrors-jshint
    rev: v2.9.7
    hooks:
    -   id: jshint
-   repo: https://github.com/pre-commit/mirrors-scss-lint
    rev: v0.57.1-1
    hooks:
    -   id: scss-lint
-   repo: https://github.com/asottile/reorder_python_imports
    rev: v1.7.0
    hooks:
    -   id: reorder-python-imports
-   repo: local
    hooks:
    -   id: pytest-check
        stages: [push]
        types: [python]
        name: pytest-check
        entry: python -m pytest -v tests/
        language: system
        pass_filenames: false
        always_run: true

验证方法

可以用以下命令模拟push阶段的钩子执行,确认只有pytest会运行:

pre-commit run --all-files --hook-stage push

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:21:17