Last active
December 7, 2015 19:34
-
-
Save Xegyn/323fb1e5b6c517bdb895 to your computer and use it in GitHub Desktop.
Ruby git hook example - prepare-commit-msg that parses jira ticket name and inserts it and a link in the commit message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# parse jira ticket names out of branches named similar to | |
# project-9999-xxxx-xxxx | |
# project names in the branch can be lowercase | |
# branches do not have to begin with the project-9999; xxxx-project-9999-xxxx-xxxx will also work | |
# make sure the hook has permissions to execute after copying it over | |
message_file = ARGV[0]wi | |
original_message = File.read(message_file) | |
# Don't do anything if the commit already has a jira link i.e. in the case of --amend | |
unless original_message.match(/jira\.example\.com/) | |
message = "" | |
current_branch = `git rev-parse --abbrev-ref HEAD` | |
match = current_branch.match(/([a-zA-Z]*-[0-9]*)-/) | |
if match | |
jira_ticket = match[1].upcase | |
message = message + "[#{jira_ticket}] " | |
jira_link = "http://jira.example.com/browse/#{jira_ticket}" | |
# Insert jira link immediately before comments begin | |
# Match where there are 3 or more lines of comments | |
comment_match = original_message.match(/((^\#.*$\n){3})/) | |
if comment_match | |
jira_link_position = comment_match.offset(0)[0] | |
else | |
jira_link_position = original_message.length - 1 | |
end | |
# Need an extra line break when message is passed in as -m | |
if ARGV[1] == "message" | |
jira_link_string = "\n\n#{jira_link}\n" | |
else | |
jira_link_string = "\n#{jira_link}\n" | |
end | |
original_message.insert(jira_link_position, jira_link_string) | |
end | |
message = message + original_message | |
File.open(message_file, 'w') { |f| f.write message } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment