Skip to content

Instantly share code, notes, and snippets.

@cmrd-senya
Forked from jakeonrails/prepare-commit-message
Last active October 6, 2023 06:54
Show Gist options
  • Save cmrd-senya/e69b68ab9d4df340d2154e07fd594d6f to your computer and use it in GitHub Desktop.
Save cmrd-senya/e69b68ab9d4df340d2154e07fd594d6f 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
exit unless 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
exit if jira_branch_id.nil? || jira_branch_id.empty?
# Append a link to the JIRA issue and the JIRA ID to the message
new_message = "[#{jira_branch_id.upcase}] #{message}"
#puts new_message: message
# Write the updated message back to the commit file
File.open(message_filename, 'w') { |f| f.write(new_message) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment