【发布时间】:2022-11-02 21:44:27
【问题描述】:
我想确保我的提交消息是否包含使用预提交的给定字符串。我尝试使用基于 pygrep 的钩子,但它没有按预期处理多行。
例如,我的提交信息是:
My commit message
Changelog: trial
我想验证提交消息是否包含“Changelog:”。
有人有想法吗?
【问题讨论】:
我想确保我的提交消息是否包含使用预提交的给定字符串。我尝试使用基于 pygrep 的钩子,但它没有按预期处理多行。
例如,我的提交信息是:
My commit message
Changelog: trial
我想验证提交消息是否包含“Changelog:”。
有人有想法吗?
【问题讨论】:
使用pygrep 这很容易——但您需要颠倒pygrep 的通常行为(当当下)
repos:
- repo: local
hooks:
- id: needs-changelog
name: commit message needs "Changelog:"
language: pygrep
entry: '^Changelog:'
args: [--multiline, --negate]
stages: [commit-msg]
这也利用了--multiline,这样正则表达式就可以匹配消息中的任何位置。 --negate 翻转了通常的 pygrep 行为
$ git commit -m "foo"
commit message needs "Changelog:"........................................Failed
- hook id: needs-changelog
- exit code: 1
.git/COMMIT_EDITMSG
$ git commit -m $'foo
Changelog: whatever'
commit message needs "Changelog:"........................................Passed
[main (root-commit) 5d10868] foo Changelog: whatever
1 file changed, 9 insertions(+)
create mode 100644 .pre-commit-config.yaml
免责声明:我创建了预提交
【讨论】:
pre-commit install 期间未安装 commit-msg 阶段配置的原因是什么?文档说您总是在回购结帐时运行pre-commit install,但这不会安装所有指定的配置条目。我认为这是有正当理由的,但这难道不是让它反直觉,因为预提交的惊人之处在于无需复杂和手动的提交挂钩设置即可轻松管理项目提交标准?
喜欢上面@anthony-sottile 提供的答案,我对其进行了调整以适用于常规提交消息!这也是我的第一个答案贡献!
在项目的根目录中创建一个 .pre-commit-config.yaml 文件,或者只是将此挂钩添加到现有文件中。
# project_root/.pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: commit-msg
name: conventional commit messages
language: pygrep
entry: '^(chore|test|feat|fix|build|docs|refactor)!?: ((?!.*(ing))(?!.*(ed))).*$'
args:
- --multiline
- --negate # fails if the entry is NOT matched
stages:
- commit-msg
一定要安装 commit-msg 钩子,否则这个 pre-commit hoox 阶段将不起作用。这些命令可以单独在 bash 终端中运行。
pip install pre-commit &&
pre-commit install --hook-type commit-msg &&
# make a file change to be committed
# git commit -a -m "failing commit message"
如果有人需要将其重新用于其出色的用例,请对正则表达式进行一些澄清:
【讨论】: