I am looking for somehelp to write a pre-commit hook on windows to check for Jira issue key while commiting.Commit should not be allowed if Jira key is not present.I couldnt find any way.I am new to scripting.Any help would be highly appreciated.
I assume you are talking about a hooks in a Git repository.
#!/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"
If you have now a branch named like feature/MYKEY-1234-That-a-branch-name
and add as commit message "Add a new feature"
Your final commit message will look like
MYKEY-1234: Add a new feature
You can put the hook globally when using Git 2.9. Please find here further useful information:
https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
Git hooks : applying `git config core.hooksPath`
You have to put the following script in your local Git repository at .git/hooks/prepare-commit-msg. This will be run whenever you add a new commit.
#!/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
First, we get the branch name, for example feature/JIRA-2393-add-max-character-limit.
Next, we extract the key, removing the prefix feature.
The resulting commit message will be prefixed by "JIRA-2393: "
The script also works when there is no prefix, e.g. without feature/, bugfix/, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With