在git hook中获取提交消息

fis*_*ato 23 git hook

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

Mar*_*air 27

在预提交钩子中,尚未创建提交消息.你可能想要使用其中一个pre-commitprepare-commit-msg钩子.Pro Git中有一个很好的部分,关于这些钩子运行的顺序,以及你通常可以用它们做什么.


Neo*_*Neo 9

我在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.
Run Code Online (Sandbox Code Playgroud)

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

#!/usr/bin/env bash
INPUT_FILE=$1
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
Run Code Online (Sandbox Code Playgroud)