Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Last active October 4, 2023 06:57
Show Gist options
  • Save jakeonrails/942b0d316185d0fac1af to your computer and use it in GitHub Desktop.
Save jakeonrails/942b0d316185d0fac1af to your computer and use it in GitHub Desktop.
prepare-commit-message that requires a JIRA ID and adds it if the branch name contains one
#!/usr/bin/env ruby
# Git Prepare Commit Message Hook Script
#
# Location: <repository>/.git/hooks/prepare-commit-msg
#
# This script will automatically add the correct
# JIRA ISSUE ID to the end of each commit message
# When the branch ID starts with the JIRA ISSUE ID.
# It can be overridden if specified in the message.
#
# Example:
#
# jira-123/branch-name => 'JIRA-123 commit message'
#
# The name of the commit file is the first argument
message_filename = ARGV[0]
#puts filename: message_filename
# Read the contents of the commit file
message = File.read(message_filename)
#puts message: message
# Match a JIRA ID in the commit message that
jira_pattern = /^([A-Z]{1,32}-[0-9]{1,32})\s/
# Capture the JIRA ID if one is present in the commit message
jira_id = message[jira_pattern, 1]
#puts jira_id: jira_id
# Do nothing if the commit message has a JIRA ID
if jira_id.nil?
# Otherwise we need to add one to the message
# Grab the current git branch
current_branch_name = `git rev-parse --abbrev-ref HEAD`
exit if current_branch_name[/^(master|develop|release|hotfix)/]
# Match the JIRA ID at the beginning of the branch name
jira_branch_pattern = /^([a-zA-Z]{1,32}-[0-9]{1,32})[-_\/]?/
# Capture the JIRA ID from the branch name
jira_branch_id = current_branch_name[jira_branch_pattern, 1]
#puts jira_branch_id: jira_branch_id
if jira_branch_id.nil? || jira_branch_id.empty?
# Blow up and let the user know they're missing a JIRA ID
raise "Commit message missing JIRA ID and/or branch name does not have one"
else
# Append a link to the JIRA issue and the JIRA ID to the message
jira_url = "https://teespring.atlassian.net/browse/#{jira_branch_id}"
new_message = "#{message}\n#{jira_url}\n#{jira_branch_id.upcase}"
#puts new_message: message
# Write the updated message back to the commit file
File.open(message_filename, 'w') { |f| f.write(new_message) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment