Clubhouse commit message prefixer

Posted on Jul 25, 2019

Clubhouse is the best project management software for development that I have ever used.

This is a simple git hook that will prefix your commit messages if you are using the Clubhouse branch helpers. Given the branch tomgamon/ch1234/some-ticket this will automatically prefix the ticket as below.

[ch1234] Rest of the git message

Just add it to your git hooks and ensure that the file is executable and away you go.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env ruby

###
##
# A git hook to extract the ticket numnber from the Clubhouse branch helpers and prepend it to commit messages for git.
# The format of the branch name format is tomgamon/ch4120/some-branch-name.
# This would result in a commit message starting with [ch4120].
# If you want a quick way to set it up in a project, run this in the project root.
#  curl -s https://gist.githubusercontent.com/thrgamon/76838290870145a33ded1ecffb432c59/raw > .git/hooks/prepare-commit-msg && chmod a+x .git/hooks/prepare-commit-msg
##
###

BRANCHES_TO_SKIP = ['master', 'develop'].freeze

# Matches 'ch' plus any number of digits that appear between two '/'
# For example it would match ch4120 in tomgamon/ch4120/option-values-strip-special-characters
PREFIX_REGEX = /(?<=\/)ch\d+?(?=\/)/.freeze

# Matches the format of a clubhouse branch which is some username, '/', 
# 'ch' plus some digits, '/', some combination of words and hyphens.
CLUBHOUSE_BRANCH_REGEX = /\w+\/ch\d+\/[\w-]+/.freeze

message_file = ARGV[0]

branch_name = `git symbolic-ref --short HEAD`.strip

return if BRANCHES_TO_SKIP.include?(branch_name)
return unless branch_name =~ CLUBHOUSE_BRANCH_REGEX
return unless branch_name =~ PREFIX_REGEX

club_ticket_prefix = branch_name.scan(PREFIX_REGEX).flatten.first

formatted_prefix =  '[' + club_ticket_prefix.upcase + ']'

message_text = File.read(message_file)

return if message_text.include?(formatted_prefix)

new_message_text = [formatted_prefix, message_text].join(' ')

File.write(message_file, new_message_text)