如何在Windows中配置Sourcetree,以便在提交消息中自动添加Jira Ticket ID



我们在Windows和Jira上使用SourceTree,我们的规则是提交消息总是必须包含来自Jira的票证ID,如HAD-4234

感觉这是可以自动化的。而且,有时候人们会忘记这一点。

我现在已经尝试过了,但没有想出一个方法来做到这一点。我尝试的主要事情是在项目的.githooks中设置一个prepare-commit-msg钩子,但这个钩子似乎根本没有任何效果(也就是说,看起来SourceTree只是忽略了它)。我尝试了一些变化,如以下:

#!C:/Programs/Git/bin/sh.exe
#
# Inspects branch name and checks if it contains a Jira ticket number (i.e. ABC-123).
# If yes, commit message will be automatically prepended with [ABC-123].
#
# Useful for looking through git history and relating a commit or group of commits
# back to a user story.
#
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
# Ensure BRANCH_NAME is not empty and is not in a detached HEAD state (i.e. rebase).
# SKIP_PREPARE_COMMIT_MSG may be used as an escape hatch to disable this hook,
# while still allowing other githooks to run.
if [ ! -z "$BRANCH_NAME" ] && [ "$BRANCH_NAME" != "HEAD" ] && [ "$SKIP_PREPARE_COMMIT_MSG" != 1 ]; then
PREFIX_PATTERN='[A-Z]{2,5}-[0-9]{1,4}'
[[ $BRANCH_NAME =~ $PREFIX_PATTERN ]]
PREFIX=${BASH_REMATCH[0]}
PREFIX_IN_COMMIT=$(grep -c "[$PREFIX]" $1)
# Ensure PREFIX exists in BRANCH_NAME and is not already present in the commit message
if [[ -n "$PREFIX" ]] && ! [[ $PREFIX_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s~^~[$PREFIX] ~" $1
fi
fi

最后,我仍然留下一个空白的提交消息框。我确实设法配置SourceTree,使其在输入提交ID时自动链接到Jira票据,但这不是我想要的。

我想要的是我团队中的每个开发人员,当他打开提交对话框时,已经在提交消息框中提供了ticket ID,如"HAD-4234: ">

我读过一种叫做提交消息模板的东西,但我的最新状态是这些还没有在Windows上的SourceTree中实现。

那么,有没有办法在Windows的SourceTree上实现这一点?还是说目前还不可能?

好了,我发现上面的代码确实有效。唯一要记住的是,在SourceTree中的commit message框中输入Jira ID时,它实际上不会在提交消息中显示Jira ID。然而,一旦你点击提交,票据ID会自动添加。

那么,这里有一个一步一步的说明如何让它工作:

  1. 在您的项目中,转到.git/hooks文件夹(如果不存在则创建hooks文件夹)
  2. 在该文件夹中,创建一个名为prepare-commit-msg的文件
  3. 复制并粘贴以下内容到该文件中,然后保存:
#!C:/Program Files/Git/usr/bin/sh.exe
#
# Inspects branch name and checks if it contains a Jira ticket number (i.e. ABC-123).
# If yes, commit message will be automatically prepended with [ABC-123].
#
# Useful for looking through git history and relating a commit or group of commits
# back to a user story.
#

BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

# Ensure BRANCH_NAME is not empty and is not in a detached HEAD state (i.e. rebase).
# SKIP_PREPARE_COMMIT_MSG may be used as an escape hatch to disable this hook,
# while still allowing other githooks to run.
if [ ! -z "$BRANCH_NAME" ] && [ "$BRANCH_NAME" != "HEAD" ] && [ "$SKIP_PREPARE_COMMIT_MSG" != 1 ]; then

PREFIX_PATTERN='[A-Z]{2,5}-[0-9]{1,4}'

[[ $BRANCH_NAME =~ $PREFIX_PATTERN ]]

PREFIX=${BASH_REMATCH[0]}

PREFIX_IN_COMMIT=$(grep -c "[$PREFIX]" $1)

# Ensure PREFIX exists in BRANCH_NAME and is not already present in the commit message
if [[ -n "$PREFIX" ]] && ! [[ $PREFIX_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s~^~$PREFIX: ~" $1
fi

fi
  • 如果没有C:/Program Files/Git下安装Git,你必须相应地调整第一行
  • 以上将以格式"HAD-234: ">
    • 如果你想让它以另一种格式显示,调整prepare-commit-msg-File中的$PREFIX:部分(在两个fis之前的最底部的两个~之间)
      • 。:[$PREFIX]会将其格式化为"[HAD-234] ">

最新更新