如何验证并显示 git 提交消息的错误?

Yah*_*Raj 4 git github

我正在使用一个node.js项目,我需要使用各种应用程序,例如github、sourcetree等来检查git源代码。是否可以对 git 提交消息进行自定义验证并在提交更改时在所有应用程序中显示错误消息?

我知道 git 中有一个 git hook 'commit-msg' 可用,但我不知道如何使用它。

Elp*_*Kay 5

这是一个示例。

#!/bin/sh

path=$1
echo path is $path

a=$(cat $path)
echo commit message is
echo $a
if [[ "$a" =~ "hello world" ]];then
  echo commit format test passed
  exit 0
else
  echo commit format test failed
  exit 1
fi
Run Code Online (Sandbox Code Playgroud)

将其保存为名为commit-msg并使其可执行的文件并将其放入 .git/hooks/ 。

此示例检查提交消息是否包含“hello world”子字符串。如果是的话,提交就会成功。如果没有,提交将会失败。

这是一个Python版本

#!/usr/bin/python

import sys

path = sys.argv[1]
print "path is " + path

with open(path) as f:
  lines = f.read()
  print "commit message is"
  print lines
  if "hello world" in lines:
    print "format test passed"
    exit(0)
  else:
    print "format test failed"
    exit(1)
Run Code Online (Sandbox Code Playgroud)

你可以用你的逻辑改进这个钩子。您可以检查 .git/hooks/ 是否有commit-msg.sample. 如果是的话,你可以阅读它作为参考。您可以直接cp .git/hooks/commit-msg.smaple .git/hooks/commit-msg编辑它。

此外,如果你想将此钩子部署到每个存储库中,如果你使用的是 Ubuntu,则可以将此钩子复制到 /usr/share/git-core/templates/hooks 中。我不知道其他系统中的默认模板路径是什么。您可能需要进行检查。这样做之后,当您执行此操作时git clone,该钩子将被复制到 .git/hook/ 中。对于已经存在的repos,可以运行git initcopy hook。

另一件事,如果您不想运行挂钩,您可以添加选项--no-verify或 just -nwhen git commit,这也会绕过挂钩pre-commit(如果存在)。