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

如何用pre-commit验证提交消息含指定字符串?解决pygrep多行问题

解决pre-commit验证多行提交消息中指定字符串的问题

方案一:调整pygrep钩子的正则表达式

pygrep默认使用Python正则引擎,默认是单行模式,无法适配多行文本匹配。你可以通过添加多行模式标志(?m),让正则能匹配多行消息里任意位置的目标字符串。

在.pre-commit-config.yaml中配置如下:

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.6.0
    hooks:
    -   id: pygrep
        name: check changelog in commit message
        entry: Changelog:
        args: ['--regexp', '(?m)Changelog:']
        stages: [commit-msg]
        files: ^$
  • stages: [commit-msg]:指定钩子仅在提交消息验证阶段运行
  • files: ^$:commit-msg钩子无需匹配代码文件,用空匹配指定仅针对提交消息
  • (?m):启用多行模式,确保Changelog:出现在任意行都能被匹配到

方案二:自定义Shell脚本钩子

如果pygrep仍不符合需求,你可以写一个简单的Shell脚本作为commit-msg钩子,直接检查提交消息文件内容:

  1. 新建脚本文件check-changelog.sh,内容如下:
#!/bin/bash

COMMIT_MSG_FILE="$1"

if ! grep -q "Changelog:" "$COMMIT_MSG_FILE"; then
    echo "错误:提交消息中必须包含 'Changelog:' 字符串"
    exit 1
fi
  1. 给脚本添加执行权限:chmod +x check-changelog.sh
  2. 在.pre-commit-config.yaml中配置自定义钩子:
repos:
-   repo: local
    hooks:
    -   id: check-changelog
        name: Check changelog in commit message
        entry: ./check-changelog.sh
        language: script
        stages: [commit-msg]

无论提交消息是单行还是多行,只要包含Changelog:就能通过验证,否则会报错阻止提交。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:50:39