Git钩子强制要求在提交信息中包含JIRA票据号。

9

我想要强制用户在git提交中添加JIRA票据。

我使用了一个pre-receive hook,但它只能在推送后才起作用。我希望它在提交后也能起作用,这样如果消息格式不正确,提交将失败,并且用户将有编辑提交的选项。

这是我的代码示例:

#!/usr/bin/env bash

# set this to your active development branch
#develop_branch="master"
#current_branch="$(git rev-parse --abbrev-ref HEAD)"

# only check commit messages on main development branch
#[ "$current_branch" != "$develop_branch" ] && exit 0

# regex to validate in commit msg
commit_regex='(#-[0-9]+|merge)'
error_msg="Aborting commit. Your commit message is missing either a JIRA Issue ('#-1111') '"
rm -rf fl.txt
echo $1 >> fl.txt
fil="fl.txt"

if ! grep -iE $commit_regex $fil; then
    echo "$error_msg" >&2
    exit 1
fi
rm -rf fl.txt

如果你想要提交失败,你需要一个 precommit 钩子。它不应该在提交之后生效。 - jonrsharpe
也许我漏掉了什么。如果我使用pre-commit,那么它会失败并允许用户进行编辑?我唯一成功的是pre-receive。也许你有一个代码示例吗? - sarit
我必须同时拥有 pre-commit 和 pre-receive 才能使 pre-receive 生效吗? - sarit
2
我放弃了。祝你好运。 - jonrsharpe
1
我认为我理解了@sarit的意思,他想要一个预提交钩子作为对开发人员的一种礼貌提醒,以便提醒他们添加票据号码,并且还需要一个预接收钩子来强制执行他们没有绕过预提交钩子。至少这就是我正在寻找的内容。 - Be Kind To New Users
显示剩余8条评论
2个回答

3
我能够通过以下方法在本地使其工作:

进入<项目目录>/.git/hooks/

  1. commit-msg.sample文件中删除扩展名.sample
  2. 使用文本编辑器打开commit-msg文件
  3. 将以下代码复制并粘贴到该文件中。
#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message.  The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit.  The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".

# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"

# This example catches duplicate Signed-off-by lines.

HOOK_FILE=$1
COMMIT_MSG=`head -n1 $HOOK_FILE`
PATTERN="^[A-Z][A-Z0-9]+-[0-9]+"
if [[ ! ${COMMIT_MSG} =~ $PATTERN ]]; then
  echo ""
  echo "    ERROR! Bad commit message. "
  echo "    '$COMMIT_MSG' is missing JIRA Ticket Number."
  echo "    example: 'JIRA-1234: my commit'"
  echo ""
  exit 1
fi


事后,您应该能够在每次尝试提交没有 JIRA 票据的消息时看到错误。

2

我唯一成功的是pre-receive

这是正确的方法:在服务器端(此处为您的GitLab服务器,使用GitLab自定义钩子)强制执行策略(检查提交消息是否包含jira票号),这是通过服务器端钩子完成的。

这意味着它会阻止git push,并强制用户修改他/她的提交并再次推送。

我必须同时拥有pre-commit和pre-receive才能让pre-receive工作吗?

不需要,只需要pre-receive钩子。试图在服务器级别使pre-commit钩子起作用是不可能的:您必须以某种方式将其分发给所有开发人员,以便他们在自己的本地存储库中激活它。这是不切实际的。


嘿,谢谢你的回复。 如果这可以帮助我使它工作,那么为开发人员分发钩子不是问题 :) pre-receive仅在推送后起作用,但我希望该过程在提交级别失败,以便用户可以编辑他的消息并再次提交。 - sarit
实际上这是一个分发问题,因为预提交钩子必须由开发人员在本地激活,而且他/她可以绕过钩子。 - VonC
与服务器端的 pre-receive 钩子不同,后者无法被绕过,而且可能会导致推送失败。因此,这是正确的方法。 - VonC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接