Skip to content

Instantly share code, notes, and snippets.

@Xegyn
Last active December 8, 2015 19:46
Show Gist options
  • Save Xegyn/f8fe0a2600d630176f6a to your computer and use it in GitHub Desktop.
Save Xegyn/f8fe0a2600d630176f6a to your computer and use it in GitHub Desktop.
Ruby git hook example prepare-commit-msg that parses pivotal story id and inserts it and a link in the commit message
#!/usr/bin/env ruby
# parse Pivotal ticket names out of branches named similar to
# xxxx-9999-xxxx-xxxx
# make sure the hook has permissions to execute after copying it over
message_file = ARGV[0]
original_message = File.read(message_file)
# Don't do anything if the commit already has a pivotal id i.e. in the case of --amend
unless original_message.match(/\[\d+\]/)
message = ""
current_branch = `git rev-parse --abbrev-ref HEAD`
match = current_branch.match(/[a-zA-Z]+-([0-9]+)-/)
if match
pivotal_id = match[1]
pivotal_link = "https://www.pivotaltracker.com/story/show/#{pivotal_id}"
line_break_match = original_message.match(/\n/)
if line_break_match
id_position = line_break_match.offset(0)[0]
else
id_position = original_message.length - 1
end
original_message.insert(id_position, " [#{pivotal_id}]")
# Insert pivotal 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
pivotal_link_position = comment_match.offset(0)[0]
else
pivotal_link_position = original_message.length - 1
end
# Need an extra line break when message is passed in as -m
if ARGV[1] == "message"
pivotal_link_string = "\n\n#{pivotal_link}\n"
else
pivotal_link_string = "\n#{pivotal_link}\n"
end
original_message.insert(pivotal_link_position, pivotal_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