Skip to content

Instantly share code, notes, and snippets.

@VarunSriram99
Last active July 4, 2023 09:24
Show Gist options
  • Save VarunSriram99/2976e0e653eea42a98a2fd987a3b0295 to your computer and use it in GitHub Desktop.
Save VarunSriram99/2976e0e653eea42a98a2fd987a3b0295 to your computer and use it in GitHub Desktop.
Pre-commit hook to prefix the jira issue number to commit message using ruby
#!/usr/bin/env ruby
class PrepareCommitMsgHandler
JIRA_PROJECT_ABBREVIATIONS = ["JIRA_BOARD_ABBRV"].freeze # Replace JIRA_BOARD_ABBRV with you Jira board abbreviation
def handle
filepath = ARGV[0]
commit_file = File.open(filepath, "r")
commit_message = commit_file.read
update_commit_message(commit_message, filepath) if is_issue_branch? && !is_commit_prefixed?(commit_message)
exit 0
end
private
def red_background(text)
"\e[41m#{text}\e[0m"
end
def is_issue_branch?
JIRA_PROJECT_ABBREVIATIONS.include?(current_branch.split("-").first.downcase)
end
def is_commit_prefixed?(message)
JIRA_PROJECT_ABBREVIATIONS.include?(message.split(" ").first.split("-").first.downcase)
end
def current_branch
result = %x{git branch}.split("\n")
if result.empty?
puts red_background("It seems your app is not a git repository.")
exit 1
else
result.select { |b| b =~ /^\*/ }.first.split(" ").last.strip
end
end
def issue_number
current_branch.split("-").first(2).join("-")
end
def update_commit_message(message, filepath)
commit_message = issue_number + " " + message
File.write(filepath, commit_message)
end
end
PrepareCommitMsgHandler.new.handle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment