Skip to content

Instantly share code, notes, and snippets.

@mrinterweb
Last active November 1, 2022 04:28
Show Gist options
  • Save mrinterweb/8568614 to your computer and use it in GitHub Desktop.
Save mrinterweb/8568614 to your computer and use it in GitHub Desktop.
git hook that modifies your commit messages to how CrowdCompass formats feature commit messages based on current feature branch.
#!/usr/bin/env ruby
# This takes hook changes the commit message based on the branch name
# to prepend the CrowdCompass Jira "CCD-<ticket_number>" to the commit message
# If the branch name begins with a 4+ character number, CCD-<4+char number> will be prepended
# unless the commit contains a ':'
#
# For example:
# Given I am on a feature branch named 1234-my-special-feature
# When I commit with the message "me fixum good"
# The commit will be transformed into "CCD-1234: me fixum good"
#
# Given I am on a feature branch named 1234-my-special-feature
# Given I am on a feature branch named 1234-my-special-feature
# When I commit with the message with a ':' like "wip: me try fix"
# The commit will not be transformed
#
# Given I am not on a branch starting with numbers or CCD-numbers
# When I commit with the message "me fixum good"
# The commit will not be transformed and remain "me fixum good"
COMMIT_FILE = ARGV[0]
BRANCH_NAME = `git symbolic-ref --short HEAD`
REGEXP = %r~^(?<prefix>(?<ccd>CCD-)?(?<num>[0-9]{4,})?(:\s|\-)?)?(?<the_rest>.+)~im
COMMIT_MESSAGE = open(COMMIT_FILE).read
bm = BRANCH_NAME.match(REGEXP)
cm = COMMIT_MESSAGE.match(REGEXP)
# puts "bm: #{bm.inspect}"
# puts "cm: #{cm.inspect}"
if bm and bm[:num] and !(COMMIT_MESSAGE =~ /\:/)
if new_commit_msg = \
if bm[:num] && cm[:the_rest]
"CCD-#{bm[:num]}: #{cm[:the_rest]}"
else
false
end
puts "Modified commit message to: #{new_commit_msg}"
File.open(COMMIT_FILE, 'w') { |f| f.write new_commit_msg }
end
end
# Now if we are committing without the -m option
commit_msg_lines = COMMIT_MESSAGE.split("\n")
if commit_msg_lines.first == ''
commit_msg_lines[0] = "CCD-#{bm[:num]}: "
File.open(COMMIT_FILE, 'w') { |f| f.write commit_msg_lines.join("\n") }
# puts open(COMMIT_FILE).read
end
# exit(1) # this is just for debugging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment