预提交钩子以检查Jira问题密钥

时间:2018-01-09 14:53:35

标签: windows svn pre-commit-hook

我正在寻找帮助在Windows上编写预提交挂钩来检查Jira问题密钥,而如果Jira密钥不存在则不应该允许提交。我无法找到任何方法。我是脚本新手。任何帮助都将受到高度赞赏。

3 个答案:

答案 0 :(得分:2)

我假设您正在谈论Git存储库中的钩子。

  • 导航到本地Git存储库,然后进入文件夹.git \ hooks
  • 创建一个名为commit-msg的文件
  • 插入以下内容(不知道如何正确格式化)

    #!/bin/bash The script below adds the branch name automatically to every 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 brach 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-branch-name的分支 并添加为提交消息“添加新功能” 您的最终提交消息看起来像 MYKEY-1234: Add a new feature

使用Git 2.9时,您可以全局放置该钩子。 请在此处找到更多有用的信息:

https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks

Git hooks : applying `git config core.hooksPath`

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分: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/^/\n\n$jiraId: /" $1
fi

首先,我们获得分支名称,例如feature / JIRA-2393-add-max-character-limit。

接下来,我们提取密钥,删除前缀功能。

生成的提交消息将以“ JIRA-2393:”为前缀

在没有前缀的情况下(例如,没有功能/,错误修正/等。