Skip to content

Instantly share code, notes, and snippets.

@bogdanbujdea
Last active May 15, 2017 08:38
Show Gist options
  • Select an option

  • Save bogdanbujdea/feb728495b31eda499230c1fda04addd to your computer and use it in GitHub Desktop.

Select an option

Save bogdanbujdea/feb728495b31eda499230c1fda04addd to your computer and use it in GitHub Desktop.
Git hook for enforcing a commit message that includes project name and JIRA ticket number
#!/bin/sh
#read https://gist.github.com/thewindev/feb728495b31eda499230c1fda04addd for instructions
excluded_branches="develop master" #the branches where you don't want commit message validation
project_name="MyAwesomeProject" #the name of the project in JIRA
current_branch="$(git rev-parse --abbrev-ref HEAD)"
for e in $excluded_branches
do [[ "$e" == "$current_branch" ]] && exit 0; done #if you're on an excluded branch then we don't check the message
commit_regex='(project-[0-9])'
commit_regex="${commit_regex/project/$project_name}"
error_msg="Aborting commit because the message is incorrect. Please start with $project_name-XYZ where XYZ is the JIRA ticket number.\nIf you want to skip this check use git commit with --no-verify"
#I also added the option to check the message only if the branch name is following the pattern
#so it will apply only on branches that contain the text "MyAwesomeProject-XYZ"
#if you want to remove validation and apply on all branches except excluded_branches, just remove the lines 18, 19 and 24
if [[ "$current_branch" = *"$project_name"* ]]
then
if ! grep -qE "$commit_regex" "$1"; then
printf "$error_msg" >&2
exit 1
fi
fi
exit 0
@bogdanbujdea
Copy link
Copy Markdown
Author

bogdanbujdea commented May 3, 2017

What is this?

  • git hook that validates the commit message

How can this help you?

  • it won't allow you to commit if your message doesn't follow the structure PROJECT_NAME-ISSUE_NUMBER-MESSAGE
  • it won't enforce this type of message on develop and master by default, but you can change this by modifying "excluded_branches"
  • it also won't enforce this message if the branch name doesn't follow the same convention

Examples
project_name=OUTLOOK
ticket number=123
branch name=feature/OUTLOOK-123_BugFixing

  • In this case your commit must start with "OUTLOOK-123" or it won't let you do it

branch name=develop

  • You can use any commit message.

branch name=bug/Outlook-123_BugFixing

  • You can use any commit message because the script is case sensitive(OUTLOOK != Outlook)

How to use:

  • Download this file or create a new one with the same name and content
  • Configure it by changing the variables "project_name", "excluded_branches" and "error_msg"
  • Copy the file to your .git/hooks folder
  • Profit $$$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment