在 git hook 中获取提交消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5393178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 10:26:22  来源:igfitidea点击:

get commit message in git hook

githook

提问by fish potato

I would like to check commit message before git commit. I use pre-commit hook to do that, but couldn't find the way to get commit message in .git/pre-commit script. How could I get it?

我想在 git commit 之前检查提交消息。我使用预提交钩子来做到这一点,但找不到在 .git/pre-commit 脚本中获取提交消息的方法。我怎么能得到它?

回答by Mark Longair

In the pre-commithook, the commit message usually hasn't been created yet 1. You probably want to use one of the prepare-commit-msgor commit-msghooks instead. There's a nice section in Pro Giton the order in which these hooks are run, and what you typically might do with them.

pre-commit钩子中,提交消息通常尚未创建1。您可能想改用prepare-commit-msgorcommit-msg钩子之一。Pro Git 中有一个很好的部分介绍了这些钩子的运行顺序,以及您通常可以用它们做什么。

1. The exception is that the committer might have supplied a commit message with -m, but the message still isn't accessible to the pre-commithook, whereas it is to prepare-commit-msgor commit-msg

1. 例外是提交者可能已经提供了一个提交消息-m,但是pre-commit钩子仍然无法访问该消息,而它是prepare-commit-msgcommit-msg

回答by Neo

I implemented this in the commit-msghook. See documentation.

我在commit-msg钩子中实现了这个。请参阅文档

commit-msg
This hook is invoked by git commit, and can be bypassed with the --no-verify option. 
It takes a single parameter, the name of the file that holds the proposed commit log message. 
Exiting with a non-zero status causes the git commit to abort.

Under my_git_project/.git/hooks, I added this file commit.msg(has to be this name). I added the following bash contents inside this file which did the validation.

在 下my_git_project/.git/hooks,我添加了这个文件commit.msg(必须是这个名字)。我在这个文件中添加了以下 bash 内容来进行验证。

#!/usr/bin/env bash
INPUT_FILE=
START_LINE=`head -n1 $INPUT_FILE`
PATTERN="^(MYPROJ)-[[:digit:]]+: "
if ! [[ "$START_LINE" =~ $PATTERN ]]; then
  echo "Bad commit message, see example: MYPROJ-123: commit message"
  exit 1
fi

回答by JammingThebBits

The hook name should be:

钩子名称应该是:

commit-msg, otherwise it won't get invoked:

commit-msg,否则它不会被调用:

回答by ugurarpaci

You can do the following in a pre-receivehook (for server side) using Python, and that will display the revision information.

您可以pre-receive使用 Python在钩子(用于服务器端)中执行以下操作,这将显示修订信息。

import sys
import subprocess
old, new, branch = sys.stdin.read().split()
proc = subprocess.Popen(["git", "rev-list", "--oneline","--first-parent" , "%s..%s" %(old, new)], stdout=subprocess.PIPE)
commitMessage=str(proc.stdout.readlines()[0])