我希望在Git提交之前检查提交信息。
我使用预提交钩子来实现,但是我无法在.git/pre-commit脚本中获取提交信息。请问如何获取?
pre-commit
钩子中,提交消息通常尚未创建1。您可能希望改用prepare-commit-msg
或commit-msg
钩子之一。在Pro Git的一个不错的章节中介绍了这些钩子的运行顺序以及通常可以使用它们做什么。
1. 特别情况是提交者可能已使用-m
提供了提交消息,但是该消息仍然无法被pre-commit
钩子访问,而可以被prepare-commit-msg
或commit-msg
访问。我在 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.
在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
PATTERN=^\[.*-\d*\].*
- PJ127#!/bin/sh
# The below input_file is file ".git/COMMIT_EDITMSG" where commits are stored
INPUT_FILE=$1
# It will copy the commit string from ".git/COMMIT_EDITMSG"
START_LINE=`head -n1 $INPUT_FILE`
# Initial index value
sum=0
# Add commit in an array variable separated by -
IFS='- ' read -r -a array_value <<< "$START_LINE"
# Count array index
for i in ${!array_value[@]}
do
sum=`expr $sum + $i`
done
# Verify commit
if [ ${sum} == 3 ]; then
BRANCH_NAME=`git branch | awk '/\*/ { print $2; }'`
TICKET_DIGIT=`awk -F '[0-9]' '{print NF-1}' <<< "${array_value[1]}"`
if [ ${array_value[0]} != ${BRANCH_NAME} ]; then
echo "please enter current branch name"
exit 1
fi
if [ "${TICKET_DIGIT}" != "4" ]; then
echo "INVALID TICKET ID"
exit 1
else
echo "verify ticket ID ${array_value[1]}"
fi
else
echo "pattern must be <CURRENT_BRANCH_NAME>-<4_DIGIT_TICKETID>-<COMMIT_DECRIPTION> without space and don't use - in commit_description"
exit 1
fi
commit-msg
,否则它将不会被调用:commit-msg
的第一个参数,这也与文件 .git/COMMIT_EDITMSG
的内容相同。 - Alexander Mills如果您想从除了commit-msg
之外的钩子访问提交消息,可以读取文件.git/COMMIT_EDITMSG
。
简单的Python示例:(Git钩子可以使用#!/usr/bin/env python
shebang运行Python)
#!/usr/bin/env python
from pathlib import Path
print(Path(".git/COMMIT_EDITMSG").read_text())
请确保根据您当前的工作目录正确获取相对路径
您可以使用Python在服务器端的pre-receive
钩子中执行以下操作,这将显示修订信息。
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])
the commit message hasn't been created yet
yes it has .. when the user typedgit commit -m "foobar"
- user7898461