我正在寻找一些帮助来在 Windows 上编写一个预提交钩子,以便在提交时检查 Jira 问题密钥。如果 Jira 密钥不存在,则不应允许提交。我找不到任何办法。我是脚本新手。任何帮助将不胜感激。
我假设您正在谈论 Git 存储库中的钩子。
- 导航到本地 Git 存储库并进入文件夹 .git\hooks
- 创建一个名为 commit-msg 的文件
- 插入以下内容(不知道如何正确格式化(
#!/bin/bash
# The script below adds the branch name automatically to
# every one of your commit messages. The regular expression
# below searches for JIRA issue key's. The issue key will
# be extracted out of your branch name
REGEX_ISSUE_ID="[a-zA-Z0-9,._-]+-[0-9]+"
# Find current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
if [[ -z "$BRANCH_NAME" ]]; then
echo "No branch name... "; exit 1
fi
# Extract issue id from branch name
ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID")
echo "$ISSUE_ID"': '$(cat "$1") > "$1"
如果您现在有一个名为 feature/MYKEY-1234-That-a-a-name 的分支并添加为提交消息"添加新功能"您的最终提交消息将如下所示 MYKEY-1234: Add a new feature
您可以在使用 Git 2.9 时全局放置钩子。请在此处找到更多有用的信息:
https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
Git hooks : apply 'git config core.hooksPath'
您可以使用 git 服务器端预接收钩子。https://git-scm.com/docs/git-receive-pack
在下面的代码中,要成功推送,您必须在提交注释中指定 Jira 问题密钥。
#!/bin/bash
#
# check commit messages for JIRA issue numbers
# This file must be named pre-receive, and be saved in the hook directory in a bare git repository.
# Run "chmod +x pre-receive" to make it executable.
#
# Don't forget to change
# - Jira id regex
jiraIdRegex="[JIRA-[0-9]*]"
error_msg="[POLICY] The commit doesn't reference a JIRA issue"
while read oldrev newrev refname
do
for sha1Commit in $(git rev-list $oldrev..$newrev);
do
echo "sha1 : $sha1Commit";
commitMessage=$(git log --format=%B -n 1 $sha1Commit)
jiraIds=$(echo $commitMessage | grep -Pqo $jiraIdRegex)
if ! jiraIds; then
echo "$error_msg: $commitMessage" >&2
exit 1
fi
done
done
exit 0
以下脚本放在本地 Git 存储库中,地址为 .git/hooks/prepare-commit-msg。这将在您添加新提交时运行。
#!/bin/bash
# get current branch
branchName=`git rev-parse --abbrev-ref HEAD`
# search jira issue id in pattern
jiraId=$(echo $branchName | sed -nr 's,[a-z]*/*([A-Z]+-[0-9]+)-.+,1,p')
# only prepare commit message if pattern matched and jiraId was found
if [[ ! -z $jiraId ]]; then
# $1 is the name of the file containing the commit message
sed -i.bak -e "1s/^/nn$jiraId: /" $1
fi
首先,我们获取分支名称,例如 feature/JIRA-2393-add-max-character-limit。
接下来,我们提取密钥,删除前缀功能。
生成的提交消息将以"JIRA-2393:"为前缀
该脚本在没有前缀时也可以工作,例如没有功能/、错误修复/等。