Skip to content

Instantly share code, notes, and snippets.

@alechill
Forked from nathankleyn/README.md
Last active April 28, 2018 14:51
Show Gist options
  • Select an option

  • Save alechill/499edbefb8d0142bae71 to your computer and use it in GitHub Desktop.

Select an option

Save alechill/499edbefb8d0142bae71 to your computer and use it in GitHub Desktop.
Git commit message hook for automagically putting the ticket number and ticket URI in your commit messages.
  1. Save this file to repo-path/.git/hooks with the name prepare-commit-msg.
  2. Make it executable using chmod +x.
  3. Ultimate win every time you use git commit.

OR in repo directory...

curl https://gist.githubusercontent.com/alechill/499edbefb8d0142bae71/raw/a6d4b07edfc494c472e55b1e2fc190d1fc851876/prepare-commit-msg -o .git/hooks/prepare-commit-message && chmod +x .git/hooks/prepare-commit-message
#!/usr/bin/env ruby
require 'tempfile'
if ARGV[1] == 'merge'
puts 'Merging, not adding issue numbers.'
exit
end
DEFAULT_ISSUE_PREFIX = 'WEB'
ISSUE_BASE_URI = 'https://rnmfinancial.atlassian.net/browse/'
MESSAGE_FILE = ARGV[0]
BRANCH_NAME = `git branch | grep '^*' | cut -b3-`
if BRANCH_NAME =~ /rebasing/
puts 'Rebasing, not adding issue numbers.'
exit
end
if File.readlines(MESSAGE_FILE).grep(/^[a-z]+-[0-9]+/i).any?
puts 'Issues are already in commit message, not adding issue numbers.'
exit
end
branch_name = BRANCH_NAME
issues = []
tmp_file = Tempfile.new('git-commit-hook')
loop do
# Variable interpolation cannot be used, and Regex must be on left hand side.
# See http://sdqali.in/blog/2013/10/01/ruby-named-capture-groups-and-local-variables/
break unless /^(?:(?<issue_prefix>[a-z]+)[-_])?(?<issue_number>[0-9]+)[-_](?<branch_name>.*)$/i =~ branch_name
issues << "#{issue_prefix || DEFAULT_ISSUE_PREFIX}-#{issue_number}".upcase
end
unless issues.empty?
input = File.read(MESSAGE_FILE).split("\n")
comments = input.reverse.take_while { |l| l.start_with?('#') }.reverse.join("\n")
text = input[0..-comments.length].join("\n")
tmp_file.puts("#{issues.join(' ')} #{text}")
tmp_file.puts
tmp_file.write('See ticket URLs at: ')
tmp_file.puts(issues.map { |issue| "#{ISSUE_BASE_URI}#{issue}" }.join(', '))
tmp_file.puts
tmp_file.puts('![img](http://nic-cage.xyz)')
tmp_file.puts
tmp_file.puts(comments)
tmp_file.flush
FileUtils.cp(tmp_file, MESSAGE_FILE)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment