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

Ruff在CLI与pre-commit钩子中检测结果不一致问题排查

问题:pre-commit配置Ruff后未检测到预期错误

我的pre-commit钩子配置

- repo: https://github.com/astral-sh/ruff-pre-commit
  rev: v0.4.9
  hooks:
    - id: ruff
      args: [ --fix ]
    - id: ruff-format

测试脚本a.py

"""Module contains functions related to greetings."""

def get_greeting(name: str) -> str:
    """Return a greeting message.

    Args
        name (str): Name of the person to greet.

    Returns
        str: A greeting message.

    """
    return f"Hello, {name}!"

def hello() -> str:
    return "hello"

直接运行Ruff检测的结果

执行命令 ruff check a.py,输出如下:

a.py:8:5: D416 [*] Section name should end with a colon ("Args")
a.py:12:5: D416 [*] Section name should end with a colon ("Returns")
a.py:20:5: D103 Missing docstring in public function
Found 3 errors.
[*] 2 fixable with the `--fix` option.

遇到的问题

直接运行ruff check能检测到3个错误,但执行pre-commit run时却显示无错误通过,请问我的配置是否遗漏了什么?


解答
  • 核心原因:pre-commit默认只检查git暂存区中的文件,如果你的a.py还没执行git add a.py加入暂存区,pre-commit run会跳过对它的检查。可以先执行git add a.py再重新运行pre-commit run,或者用pre-commit run --all-files强制检查所有文件。
  • 补充说明:你的ruff钩子配置了--fix参数,它会自动修复可修复的D416错误,修复完成后钩子返回成功,但未修复的D103错误只有在文件被暂存或使用--all-files参数时才会被检测到。
  • 额外验证:检查项目中是否存在ruff.toml等配置文件意外禁用了D103规则,但你直接运行ruff check能检测到该错误,所以这个可能性极低。

内容的提问来源于stack exchange,提问作者Gonçalo Guedes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:10:02