Skip to content

Instantly share code, notes, and snippets.

@DanielBlanco
Created November 14, 2016 14:39
Show Gist options
  • Save DanielBlanco/1eec9604a3674a642018d255efd02432 to your computer and use it in GitHub Desktop.
Save DanielBlanco/1eec9604a3674a642018d255efd02432 to your computer and use it in GitHub Desktop.
Git hook in ruby code to insert a JIRA link when commiting.
#!/usr/bin/env ruby
# This way you can customize which branches should be skipped when
# prepending commit message.
message_file = ARGV[0]
branches_to_skip = (ENV['BRANCHES_TO_SKIP'] || 'master').split(' ')
original_message = File.read(message_file)
current_branch = `git symbolic-ref --short HEAD`
# Don't do anything if the commit already has a link i.e. in the case of --amend
if !original_message.match(/Ticket/) && !branches_to_skip.include?(current_branch)
match = current_branch.match(/([a-zA-Z]*-[0-9]*)/)
if match
ticket = match[1]
jira_server = `git config jira.server`
jira_link = "Ticket: #{jira_server.chomp}/browse/#{ticket}\n"
# Insert jira link immediately before comments begin
# Match where there are 3 or more lines of comments
comment_match = original_message.match(/((^\#.*$\n){3})/)
jira_link_position = if comment_match
comment_match.offset(0)[0]
else
original_message.length - 1
end
# Need an extra line break when message is passed in as -m
jira_link = "\n#{jira_link}" if ARGV[1] == "message"
original_message.insert(jira_link_position, jira_link)
end
File.open(message_file, 'w') { |f| f.write original_message }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment